diff --git a/solidcore/crates/goldens/expected/blend.fillet_executive_p3.jsonl b/solidcore/crates/goldens/expected/blend.fillet_executive_p3.jsonl index b5a6c758191..763907e55ff 100644 --- a/solidcore/crates/goldens/expected/blend.fillet_executive_p3.jsonl +++ b/solidcore/crates/goldens/expected/blend.fillet_executive_p3.jsonl @@ -385,19 +385,19 @@ {"case":"issue_2176_tabbed_plate_tab_top_r0_5","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,14,21,9],"mass_status":[0],"result_topology":{"blocks":[[281173,35304862],[149809,9411572]],"n":386}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[4398.247970622149,4054.770107863145,4054.770107863145,-1.7969747064919106e-6,0.9105569463482839,0.9999386650113714,726367.7317135052,619662.8015560975,1335219.071998879,3683.8988696319116,-0.002825799627495796,-0.45093239645778416],"result_geometry":{"blocks":[[1343.8836492187397,1694.2856076554435,170184.6313458056],[1222.6211531467225,1579.5921858261156,136868.165819516],[454.25854806815966,560.2564243430285,22246.496666459214]],"n":596},"selected_edge_before":{"blocks":[[14125.853333333334,14128.493333333334,71330.16]],"n":17}}} {"case":"law-box10x20x30-e0-deg1-edge-map-degenerate","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,12,19,9],"mass_status":[0],"result_topology":{"blocks":[[282157,35575434],[120532,5818955]],"n":352}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2189.4574611461926,5993.756280511141,5993.756280511141,4.995127401667838,9.99576469118231,14.984712836733523,2593119.255742517,1993915.7039923212,998032.9494945229,897396.4937418099,448207.1617923292,299152.8279281863],"result_geometry":{"blocks":[[1680.6200031705825,1680.6200031705825,213530.7765447341],[2183.7520570832758,2183.7520570832758,266725.9827933028],[411.85405380836977,411.85405380836977,8682.958435059803]],"n":552},"selected_edge_before":{"blocks":[[14178.4,14178.4,71995.6]],"n":17}}} {"case":"law-box10x20x30-e0-deg1-half-to-two","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2188.3793764514203,5992.501060003924,5992.501060003924,4.9941669100814226,9.995532359196615,14.981655251685952,2591845.742623782,1992701.8102639471,997742.6327630895,896984.6673960955,447851.5156789837,299019.8027829542],"result_geometry":{"blocks":[[1712.6197407180512,1712.6197407180512,231574.67750033643],[1426.5077843004244,1426.5077843004244,128898.93102345121]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71995.6]],"n":17}}} -{"case":"law-box10x20x30-e0-deg2-edge-map-reversed","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2184.1751676986423,5986.983115083339,5986.983115083339,4.98998346873595,9.998827903224242,14.968242237332305,2586763.433112755,1987385.6856915774,996972.1062086006,895939.4707287649,446298.4124692148,298683.15406244877],"result_geometry":{"blocks":[[1707.9022304529424,1707.9022304529424,230701.67619369406],[1423.387590282367,1423.387590282367,128636.35343869733]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71995.6]],"n":17}}} -{"case":"law-box10x20x30-e0-deg2-edge-map-sub-range","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2184.1751676986423,5986.983115083339,5986.983115083339,4.98998346873595,9.998827903224242,14.968242237332305,2586763.433112755,1987385.6856915774,996972.1062086006,895939.4707287649,446298.4124692148,298683.15406244877],"result_geometry":{"blocks":[[1707.9022304529424,1707.9022304529424,230701.67619369406],[1423.387590282367,1423.387590282367,128636.35343869733]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71995.6]],"n":17}}} +{"case":"law-box10x20x30-e0-deg2-edge-map-reversed","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2184.139731654484,5986.918981222035,5986.918981222035,4.989936199976198,9.998826352597309,14.968087616040227,2586700.2857600274,1987324.5503526886,996958.7319586906,895920.347449593,446280.69264435186,298677.0350001039],"result_geometry":{"blocks":[[1707.9049532703903,1707.9049532703903,230702.20675370615],[1423.3787038494627,1423.3787038494627,128634.23155160762]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71995.6]],"n":17}}} +{"case":"law-box10x20x30-e0-deg2-edge-map-sub-range","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2184.139731654484,5986.918981222035,5986.918981222035,4.989936199976198,9.998826352597309,14.968087616040227,2586700.2857600274,1987324.5503526886,996958.7319586906,895920.347449593,446280.69264435186,298677.0350001039],"result_geometry":{"blocks":[[1707.9049532703903,1707.9049532703903,230702.20675370615],[1423.3787038494627,1423.3787038494627,128634.23155160762]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71995.6]],"n":17}}} {"case":"law-cube20-e0-deg1-4-2-4-c0-corner","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,12,19,9],"mass_status":[0],"result_topology":{"blocks":[[282157,35576940],[120532,5819421]],"n":352}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2367.8007322089193,7960.456479043605,7960.456479043605,9.953871200535904,9.999999996103337,9.953871539722803,2112904.223910805,2103886.076099821,2112904.155415373,792373.6114223865,785299.708981522,792373.5844261488],"result_geometry":{"blocks":[[1667.4373645374783,1667.4373645374783,214661.87454498917],[2130.614158023403,2130.614158023403,258072.6246650644],[407.3946223083555,407.3946223083555,8411.548724345723]],"n":552},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} {"case":"law-cube20-e0-deg1-linear-2-4","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2370.0543455325983,7960.071936129126,7960.071936129126,9.953435936283505,9.989251401250788,9.953435810975794,2111398.183434613,2103609.0024984926,2111398.2346750274,790677.2423156234,785161.491122704,790677.2544732792],"result_geometry":{"blocks":[[1684.0183897533257,1684.0183897533257,227164.9335056153],[1416.2692338016789,1416.2692338016789,127125.58369910887]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} {"case":"law-cube20-e0-deg1-two-corners","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,16,26,12],"mass_status":[0],"result_topology":{"blocks":[[281222,35326533],[265583,31560895]],"n":480}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2373.335268515069,7967.522641489464,7967.522641489464,9.961877354669278,9.99999999552616,9.961877643346037,2116953.583459068,2108985.634626045,2116953.5260383366,793714.8562428481,787842.1786587717,793714.8330935917],"result_geometry":{"blocks":[[1721.85057,1721.85057,208393.33629000006],[2489.136455059325,2489.136455059325,329320.37805788324],[1959.366653671578,1959.366653671578,252812.10225861322]],"n":748},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} {"case":"law-cube20-e0-deg2-c0-knot","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,12,19,9],"mass_status":[0],"result_topology":{"blocks":[[282157,35576940],[120532,5819421]],"n":352}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2367.800732206342,7960.45647903661,7960.45647903661,9.9538712005281,9.999999996103467,9.95387153971471,2112904.2239073175,2103886.0760947634,2112904.1554119717,792373.6114210549,785299.7089789996,792373.584424865],"result_geometry":{"blocks":[[1667.4373645374783,1667.4373645374783,214661.87454498917],[2130.6141580224885,2130.6141580224885,258072.6246648259],[407.39462230768277,407.39462230768277,8411.548724338574]],"n":552},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} -{"case":"law-cube20-e0-deg2-smooth-4-2-4","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2364.7319701022707,7952.155113708545,7952.155113708545,9.944375424905331,10.000005868156498,9.944375694071455,2108960.1774515035,2097852.7961423276,2108960.1327181733,790793.0557208423,782290.5651757707,790793.0341516513],"result_geometry":{"blocks":[[1670.2536924877857,1670.2536924877857,225228.56812894478],[1414.9315230124485,1414.9315230124485,127042.86457124968]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} -{"case":"law-cube20-e0-deg2-smooth-g2","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2364.7319701022707,7952.155113708545,7952.155113708545,9.944375424905331,10.000005868156498,9.944375694071455,2108960.1774515035,2097852.7961423276,2108960.1327181733,790793.0557208423,782290.5651757707,790793.0341516513],"result_geometry":{"blocks":[[1670.2536924877857,1670.2536924877857,225228.56812894478],[1414.9315230124485,1414.9315230124485,127042.86457124968]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} +{"case":"law-cube20-e0-deg2-smooth-4-2-4","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2364.7348064239563,7952.164069078688,7952.164069078688,9.944385376164446,10.000000065369454,9.944385666247364,2108963.694061797,2097859.136344146,2108963.642842635,790793.8735889597,782293.7195653111,790793.8503074555],"result_geometry":{"blocks":[[1670.2547412409558,1670.2547412409558,225228.7779982484],[1414.9323427400154,1414.9323427400154,127042.77253426895]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} +{"case":"law-cube20-e0-deg2-smooth-g2","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2364.7348064239563,7952.164069078688,7952.164069078688,9.944385376164446,10.000000065369454,9.944385666247364,2108963.694061797,2097859.136344146,2108963.642842635,790793.8735889597,782293.7195653111,790793.8503074555],"result_geometry":{"blocks":[[1670.2547412409558,1670.2547412409558,225228.7779982484],[1414.9323427400154,1414.9323427400154,127042.77253426895]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} {"case":"law-cube20-e0-deg2-smooth-xsect-blend-curve","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[1007,8,12,6],"mass_status":[0],"result_topology":{"blocks":[[258750,29222574]],"n":224}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2400.0,8000.0,8000.0,10.0,9.999999999999998,10.0,2133333.3333333335,2133333.3333333335,2133333.333333333,800000.0,800000.0,799999.9999999999],"result_geometry":{"blocks":[[1661.2002100000002,1661.2002100000002,200391.61977000005],[687.2000499999999,687.2000499999999,36709.60235]],"n":356},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} {"case":"law-cube20-e0-deg2-smooth-xsect-linear","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2345.2760122310365,7887.948286878954,7887.948286878954,9.873990695646446,10.000026675954922,9.873990688905714,2077813.4007994614,2053384.4736486543,2077813.4029990179,778859.128403403,760133.6867352928,778859.1297087035],"result_geometry":{"blocks":[[1670.2536924877857,1670.2536924877857,225228.56812894478],[1403.4605734752693,1403.4605734752693,126222.68861421739]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} -{"case":"law-cube20-e0-deg3-asymmetric","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2369.5749090135373,7953.640946840825,7953.640946840825,9.946160772110678,9.991926426495011,9.946161065901038,2108953.166020272,2098982.1501906263,2108953.11183758,789863.6366843694,782855.25339865,789863.612368904],"result_geometry":{"blocks":[[1689.9809462060066,1689.9809462060066,227825.14024817996],[1416.5118811852522,1416.5118811852522,127186.6827485088]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} +{"case":"law-cube20-e0-deg3-asymmetric","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301010,39996947],[15115,181394]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2369.574588530807,7953.641548809971,7953.641548809971,9.946161199353215,9.991928028189108,9.94616155864152,2108953.3103832263,2098982.453320686,2108953.2394005335,789863.9882397251,782855.4038447193,789863.9582095176],"result_geometry":{"blocks":[[1689.983321788043,1689.983321788043,227825.7095194302],[1416.5138380229491,1416.5138380229491,127186.6458504638]],"n":436},"selected_edge_before":{"blocks":[[14178.4,14178.4,71935.6]],"n":17}}} {"case":"law-cube20-e3-deg1-4-2-4-c0-corner","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,12,19,9],"mass_status":[0],"result_topology":{"blocks":[[282159,35577151],[120530,5819190]],"n":352}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2367.8007331636295,7960.4591713535165,7960.4591713535165,10.046126179310118,10.00000000333297,9.953873577527025,2112905.318706412,2118575.0390558876,2127592.793658584,792374.042515696,799447.6153564502,799717.7729130394],"result_geometry":{"blocks":[[1670.6973645371604,1670.6973645371604,194295.75454490818],[1718.579432632112,1718.579432632112,223908.2388195334],[286.68641058297936,286.68641058297936,5815.227576059539]],"n":552},"selected_edge_before":{"blocks":[[14121.4,14121.4,71278.6]],"n":17}}} -{"case":"law-cube20-e7-deg3-asymmetric","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301016,39999287],[15109,181340]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2369.574908788897,7953.643809974676,7953.643809974676,9.991926758997963,10.053836462541353,10.05383664836654,2133239.5387554187,2126082.2453157655,2126082.212372714,799983.948748652,799580.3802531472,799580.3606803443],"result_geometry":{"blocks":[[1699.017897191417,1699.017897191417,200943.09406580182],[989.3773765144091,989.3773765144091,96759.6299816668]],"n":436},"selected_edge_before":{"blocks":[[14065.4,14065.4,70475.2]],"n":17}}} +{"case":"law-cube20-e7-deg3-asymmetric","deferred":null,"error":null,"ints":{"api_status_vertex_edge_face_counts":[0,10,15,7],"mass_status":[0],"result_topology":{"blocks":[[301016,39999287],[15109,181340]],"n":278}},"topology":null,"values":{"fillet_point_step":[0.00001],"mass_properties":[2369.5745881589164,7953.644412386235,7953.644412386235,9.99192833878353,10.053835938800622,10.053836154920695,2133239.5475241877,2126082.2460252065,2126082.21290234,799983.9503478577,799580.4028557935,799580.3849744719],"result_geometry":{"blocks":[[1699.0221735460068,1699.0221735460068,200944.12697686921],[989.381870242868,989.381870242868,96759.77043840376]],"n":436},"selected_edge_before":{"blocks":[[14065.4,14065.4,70475.2]],"n":17}}} {"case":"negative-default-magnitude","deferred":null,"error":null,"ints":{"comment_bytes":{"blocks":[[4138,96800]],"n":44},"comment_lengths":[36,8],"corner_types":[0,0],"status_error_flags":[1007,1,0,5,0,0,0,0,0]},"topology":null,"values":{"fillet_point_step":[0.00001],"tolerances":[9876543.21,-1.0]}} {"case":"negative-tiny-tolerance","deferred":null,"error":null,"ints":{"comment_bytes":{"blocks":[[4138,96800]],"n":44},"comment_lengths":[36,8],"corner_types":[0,0],"status_error_flags":[1007,1,0,5,0,0,0,0,0]},"topology":null,"values":{"fillet_point_step":[0.00001],"tolerances":[1e-300,-1.0]}} {"case":"negative-tolerance","deferred":null,"error":null,"ints":{"comment_bytes":{"blocks":[[4138,96800]],"n":44},"comment_lengths":[36,8],"corner_types":[0,0],"status_error_flags":[1007,1,0,5,0,0,0,0,0]},"topology":null,"values":{"fillet_point_step":[0.00001],"tolerances":[0.25,-1.0]}} diff --git a/solidcore/crates/solidcore/src/blend/fillet_custom_solver.rs b/solidcore/crates/solidcore/src/blend/fillet_custom_solver.rs index 5d4758896f3..5e27edd6d2f 100644 --- a/solidcore/crates/solidcore/src/blend/fillet_custom_solver.rs +++ b/solidcore/crates/solidcore/src/blend/fillet_custom_solver.rs @@ -2053,7 +2053,10 @@ macro_rules! fillet_intersector_ops { points: &[TsectPnt], uv1: &mut BSplineCurve, uv2: &mut BSplineCurve, - ) -> Result> { + ) -> Result<( + Option, + Option, + )> { IntersectorOps::create_fillet_surface( &mut self.base, k, @@ -2066,6 +2069,17 @@ macro_rules! fillet_intersector_ops { ) } + fn keep_law_corner_pieces( + &mut self, + pieces: crate::blend::law_corners::LawCornerPieces, + ) -> Result<()> { + IntersectorOps::keep_law_corner_pieces(&mut self.base, pieces) + } + + fn skins_varying_balls(&self) -> Result { + IntersectorOps::skins_varying_balls(&self.base) + } + fn set_fillet_surface( &mut self, pseudo: &mut crate::blend::fillet_geom::p1::FilletBrep, diff --git a/solidcore/crates/solidcore/src/blend/fillet_intersector.rs b/solidcore/crates/solidcore/src/blend/fillet_intersector.rs index 1d5490b5a6b..cb9572224a1 100644 --- a/solidcore/crates/solidcore/src/blend/fillet_intersector.rs +++ b/solidcore/crates/solidcore/src/blend/fillet_intersector.rs @@ -86,20 +86,47 @@ //! - **Dead code.** Step 11 of `FlushCurve` (the self-intersection blending) is //! guarded by the constant `bTempTrySelfIntHandler = FALSE` and never runs; it is //! not ported. +//! - **Skin between stations.** (not upstream, #15256) Upstream accepts a span on its +//! rails alone, so a skin of balls' touch circles is unbounded between stations. +//! Where the solver's surface is the exact touch circles of balls whose radius varies +//! ([`FilletSolverOps::skins_varying_balls`]), `FlushCurve` holds the built skin to the +//! tolerance over every span (`skin_splits`): nine samples of the span's middle +//! iso-curve against the solved middle section's envelope steer, and a span they pass +//! is kept only on a proved bound over its whole rectangle of the skin against the +//! interpolated ball family `R` through the solved sections about it (`skin_bound`, +//! Bernstein enclosures with their rounding), not against the round's true balls; a span +//! over the tolerance, or not proved, takes its middle section as a station, and the +//! skin is built again. That `R` is the round's true family between its solved sections +//! is argued, not bounded, and the kept span is not marked certified: a peak or kink of +//! the radius law strictly inside a span, narrower than about a quarter of it, is not +//! seen (radius corners are found only at stations). The certified forms are #15657 (the +//! round as its definition) and #16446 (interval Newton on the section equations). The geometry builder of steps 5b to 10 is +//! `build_flush_geometry`, step 5 `equalise_spans` and step 5a `solve_mid_point`; the +//! pieces a round whose law has corners keeps are handed to the solver once, for the +//! final skin ([`FilletSolverOps::keep_law_corner_pieces`]). //! - **Loops.** `FlushCurve`'s span equalisation stops once the knot count exceeds -//! three times its start, as upstream; each pass at most doubles it. No recursion. +//! three times its start, as upstream; each pass at most doubles it. The skin's +//! stations are added in at most `SKIN_ROUNDS` rounds and to at most +//! `SKIN_STATION_FACTOR` times the stations the curve starts with; past either the +//! round is refused. No recursion. //! - **Not ported.** `Dump` and the `SM_DEBUG_CODE` drawing blocks; `SM_ASSERT`s. +mod skin_bound; + use crate::blend::fillet_custom_solver::{offset_evaluate_1st, ConstantRadiusAssistedFs}; use crate::blend::fillet_geom::p1::{set_rail_curve, FilletBrep, FilletGeomId}; use crate::blend::fillet_solver::p1::{compute_uv_vectors, FilletSolver}; use crate::blend::fillet_solver::p3::StepSolveOutcome; use crate::blend::fillet_standard_solver::p1::FilletLaw; +use crate::blend::law_corners::LawCornerPieces; use crate::curve::crv_on_surf::CrvOnSurf; use crate::curve::curve::p3::PointSolveOptions; use crate::curve::curve::Curve; use crate::curve::hermite_curve::HermiteCurve; +use crate::error::blend::BlendFailure; +use crate::error::Failure; use crate::error::{Result, SolidError}; +use crate::geom::certified::above; use crate::geom::extent1d::Extent1d; use crate::geom::extent2d::Extent2d; use crate::geom::geom_utility::p1::line_closest_point; @@ -120,10 +147,13 @@ use crate::intersect::surface_intersector::p4::{ use crate::kernel::Kernel; use crate::math::{max2, max4, min2, EFF_ZERO, EFF_ZERO_SQ}; use crate::nurbs::b_spline_curve::{BSplineCurve, BSplineCurveForm, CanonicalData, KnotType}; +use crate::nurbs::math::gamma; +use crate::offset::construction::bernstein::Binomials; use crate::surface::surface::p2::{drop_vectors, TsectCurveType}; -use crate::surface::surface::Surface; +use crate::surface::surface::{Surface, SurfaceKind}; use crate::topology::edgeuse::p1 as eu1; use crate::topology::{edge, EdgeId}; +use skin_bound::{Ball, BallFamily}; const OP_VALUES: &str = "blend::fillet_intersector::FilletIntersector::compute_point_values"; const OP_DELTA: &str = "blend::fillet_intersector::FilletIntersector::compute_point_values_delta"; @@ -146,6 +176,196 @@ const PARAMS_TO_TEST: [f64; NUM_TEST_POINTS] = [0.5, 0.17, 0.83, 0.33, 0.67]; /// The two surfaces, in upstream index order. const SRFS: [SrfIndex; 2] = [SrfIndex::First, SrfIndex::Second]; +/// The most rounds in which `FlushCurve` adds stations where a skin of balls' touch +/// circles is farther than the tolerance from them (#15256). Between stations the skin +/// is a cubic interpolant, whose distance from the balls falls about sixteenfold each +/// time a span is halved: the farthest measured, 10.2 times the tolerance, needs one +/// round, and six reach a skin `16^6` times the tolerance off. +const SKIN_ROUNDS: usize = 6; + +/// The most stations a curve's skin may take, as a multiple of the stations it starts +/// with (#15256): each round at most doubles them, and the span equalisation after it +/// at most triples them again. +const SKIN_STATION_FACTOR: usize = 64; + +/// A span the skin check splits (#15256): its index, the parameter of its new station and +/// the solver's section there. +type SkinSplit = (usize, f64, TsectPnt); + +/// What the skin check finds (#15256): the spans it splits, the largest distance it +/// measured (infinite where a span's section could not be placed on the skin), and where it +/// last computed a value that is not finite (a distance, or the balls' rate or speed). +#[derive(Debug, Default)] +struct SkinCheck { + splits: Vec, + worst: f64, + not_finite_at: Option, +} + +/// The shares of the skin's section where `FlushCurve` measures it against the balls +/// (#15256): both rails and seven points between. +const SKIN_SHARES: [f64; 9] = [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]; + +/// What steps 5b to 10 of `FlushCurve` build from its stations: the fillet geometry +/// they go to, the centre line, the rails and their UV curves, the fillet surface and +/// the pieces a round whose law has corners keeps. +struct FlushGeometry { + fillet_geom: G, + center_line: BSplineCurve, + curve1: BSplineCurve, + curve2: BSplineCurve, + uv1: BSplineCurve, + uv2: BSplineCurve, + fillet_surface: Option, + kept: Option, +} + +/// The balls' envelope to first order at a section (#15256): the ball (centre `c`, +/// radius `r`) and, where its centre moves, the unit direction `a` of the centre line +/// and the cosine and sine of the angle between `a` and the envelope's normal along the +/// touch circle, `cos = -r' / |c'|`. The envelope of the balls `|x - c - c' t| = r + r' t` +/// is the cone tangent to the true envelope along the whole touch circle. +#[derive(Debug, Clone, Copy)] +struct EnvelopeCone { + c: Point3, + r: f64, + axis: Option<(Vec3, f64, f64)>, +} + +impl EnvelopeCone { + /// The cone at the section with centre `cent` moving at `cent_d`, and rail points + /// `p1`, `p2` moving at `d1`, `d2`, all along the trace: `r` is the mean distance from + /// the centre to the rail points and `r'` its rate, read off the rails as + /// `CircularCrossSectionFsg::create_surface_from_curves_of_balls` reads it. + /// + /// # Errors + /// + /// [`BlendFailure::BallsNest`] where the radius changes at least as fast as the centre + /// moves (`|r'| >= |c'|`): each ball holds the next, so the balls have no envelope there; + /// [`BlendFailure::SkinMeasureNotFinite`] where a radius, the rate or the speed is not + /// finite. `s` is the section's parameter along the trace, for the record. + fn at_section( + s: f64, + cent: Point3, + cent_d: Vec3, + [(p1, d1), (p2, d2)]: [(Point3, Vec3); 2], + ) -> Result { + let v1 = p1 - cent; + let v2 = p2 - cent; + let r1 = v1.length(); + let r2 = v2.length(); + let r = 0.5 * (r1 + r2); + let speed = cent_d.length(); + // (in the section's own frame: the speed against the radius, each radius against + // the centre's size) + let size = 1.0 + cent.x.abs().max(cent.y.abs()).max(cent.z.abs()); + if speed <= EFF_ZERO * (1.0 + r) || r1 <= EFF_ZERO * size || r2 <= EFF_ZERO * size { + return Ok(Self { + c: cent, + r, + axis: None, + }); + } + let rate = 0.5 * (v1.dot(d1 - cent_d) / r1 + v2.dot(d2 - cent_d) / r2); + if !(r1.is_finite() && r2.is_finite() && speed.is_finite() && rate.is_finite()) { + return Err(SolidError::blend( + OP_FLUSH, + BlendFailure::SkinMeasureNotFinite { s }, + )); + } + let cos = -rate / speed; + let sin_sq = 1.0 - cos * cos; + // (refused within the rounding of `sin^2`: each of the rate's terms + // `v.(d - c') / |v|` is at most `|d - c'|` and carries `gamma_16` of it, the speed + // and the quotient `gamma_8` of `cos`, and `1 - cos^2` `gamma_2`; NaN refuses too) + let rate_err = gamma(16) * ((d1 - cent_d).length() + (d2 - cent_d).length()); + let cos_err = rate_err / speed + gamma(8) * cos.abs(); + let sin_sq_err = cos_err * (2.0 * cos.abs() + cos_err) + gamma(2); + if !above(sin_sq, sin_sq_err) { + return Err(SolidError::blend( + OP_FLUSH, + BlendFailure::BallsNest { + s, + rate: rate.abs(), + speed, + }, + )); + } + Ok(Self { + c: cent, + r, + axis: Some((cent_d / speed, cos, sqrt(sin_sq))), + }) + } + + /// The point of the section's touch circle (centre `c + r cos a`, radius `r sin`, + /// square to `a`) nearest `x`'s direction about its axis: `x` projected onto the + /// circle. Without a moving centre, `x` projected onto the ball. + fn touch_circle_point_near(&self, x: Point3) -> Point3 { + // the circle's centre and radius, and the plane `x` is dropped into + let (o, radius, axis) = match self.axis { + Some((a, cos, sin)) => (self.c + a * (self.r * cos), self.r * sin, Some(a)), + None => (self.c, self.r, None), + }; + let q = x - o; + let w = axis.map_or(q, |a| q - a * q.dot(a)); + let len = w.length(); + if len > EFF_ZERO { + o + w * (radius / len) + } else { + x + } + } + + /// The signed distance from `x` to the cone (positive outside the balls), in closed + /// form: `min_t |x - c - c' t| - r - r' t = rho sin + h cos - r`, `h` the height of + /// `x` along the centre line from `c` and `rho` its distance from the line; without + /// a moving centre, the distance to the ball. It is the distance to the balls' + /// envelope on the touch circle, and departs from it only to second order in the + /// distance from the circle along the trace. + fn distance(&self, x: Point3) -> f64 { + let p = x - self.c; + match self.axis { + Some((a, cos, sin)) => { + let h = p.dot(a); + let rho = (p - a * h).length(); + rho * sin + h * cos - self.r + } + None => p.length() - self.r, + } + } +} + +/// The rails' points on the faces at a section and their rates along the trace, with the +/// solver's offsets at zero. +/// +/// # Errors +/// +/// Those of the rails' evaluations. +fn section_rails( + solver: &mut S, + k: &Kernel, + p: &TsectPnt, +) -> Result<[(Point3, Vec3); 2]> { + let mut rails = [(Point3::ZERO, Vec3::ZERO); 2]; + for ((rail, s), slot) in SRFS.into_iter().enumerate().zip(rails.iter_mut()) { + let uv_d = p.uv_deriv(s); + let (pnt, du, dv) = solver.rail_surface_evaluate_1st_derivatives(k, rail, p.uv_pos(s))?; + *slot = (pnt, du * uv_d.x + dv * uv_d.y); + } + Ok(rails) +} + +/// A section's ball (#15256): its centre `c`, the mean distance from it to the rails' points +/// (as [`EnvelopeCone::at_section`] reads a section's radius), at the skin's parameter `at`. +fn section_ball(c: Point3, [(p1, _), (p2, _)]: [(Point3, Vec3); 2], at: f64) -> Ball { + Ball { + c, + r: 0.5 * ((p1 - c).length() + (p2 - c).length()), + at, + } +} + // ---- co-ported enums ------------------------------------------------------------------------ /// The filleting status `SmFilStatus` is unit `blend.fillet_geom_p1`'s @@ -381,7 +601,9 @@ pub trait FilletSolverOps { /// `m_pFSG->CreateSurface(*this, pCenterLine, pCurve1, pCurve2, sPnts, pSur[0], /// pUV1, pSur[1], pUV2, pFilletSurface)`: the fillet surface (the generator may - /// change the curves in place). + /// change the curves in place), and the pieces a round whose law has corners keeps + /// (the fork's `AddLawCornerPieces`), which `FlushCurve` hands to + /// [`Self::keep_law_corner_pieces`] once its stations are final. /// /// # Errors /// @@ -397,7 +619,26 @@ pub trait FilletSolverOps { points: &[TsectPnt], uv1: &mut BSplineCurve, uv2: &mut BSplineCurve, - ) -> Result>; + ) -> Result<(Option, Option)>; + + /// `rFilletSolver.AddLawCornerPieces(..)` (the fork's 7babe17): keeps the pieces of + /// the round [`Self::create_fillet_surface`] built. + /// + /// # Errors + /// + /// The solver's failure. + fn keep_law_corner_pieces(&mut self, pieces: LawCornerPieces) -> Result<()>; + + /// Whether the fillet surface is the exact touch circles of balls whose radius varies + /// along the round, skinned between the stations (#15256): a circular generator with + /// exact, unmirrored arcs, for a solver whose ball changes its radius + /// ([`FilletSolverType::ball_radius_varies`]). `FlushCurve` then holds the skin, not + /// only the rails, to the tolerance. + /// + /// # Errors + /// + /// The solver's failure. + fn skins_varying_balls(&self) -> Result; /// `pFilletGeom->SetFilletSurface(pFilletSurface)` (after deleting the old one); the /// geometry is stored in `pseudo`. @@ -614,7 +855,7 @@ impl FilletSolverOps for ConstantRadiusAssistedFs { points: &[TsectPnt], uv1: &mut BSplineCurve, uv2: &mut BSplineCurve, - ) -> Result> { + ) -> Result<(Option, Option)> { // the virtual m_pFSG->CreateSurface(*this, pCenterLine, pCurve1, pCurve2, // sPnts, pSur[0], pUV1, pSur[1], pUV2, ..): the base's generator (SM_ERR for // the base class); it reads the solver's tolerance and GetSolverType() @@ -641,7 +882,17 @@ impl FilletSolverOps for ConstantRadiusAssistedFs { [uv1, uv2], None, ) - .map(|(surface, _)| Some(surface)) + .map(|(surface, kept)| (Some(surface), kept)) + } + + fn keep_law_corner_pieces(&mut self, pieces: LawCornerPieces) -> Result<()> { + self.solver.law_corner_pieces.push(pieces); + Ok(()) + } + + fn skins_varying_balls(&self) -> Result { + // a constant radius solver's ball keeps its radius + Ok(false) } fn rail_surface_evaluate_1st_derivatives( @@ -1770,18 +2021,8 @@ impl<'s, 't, O: SolutionObject + 't, G: Clone> FilletIntersector<'s, 't, O, G> { return Ok(()); } - let uv_domains = self.base.base.uv_domains; - let curve_trace_direction = self.base.base.curve_trace_direction; - // new curve locals let mut knots: Vec = Vec::new(); - let mut ctrl_pts_3d: Vec = Vec::new(); - let mut uv_ctrl_pts: [Vec; 2] = [Vec::new(), Vec::new()]; - let mut rail_ctrl_pts_3d: [Vec; 2] = [Vec::new(), Vec::new()]; - - let mut curve_type = TsectCurveType::Crossing; - let mut max_deviation = 0.0; - let mut max_angle = 0.0; // 3. If the final span is tiny, remove it by consolidating it with // the previous span. @@ -1807,6 +2048,471 @@ impl<'s, 't, O: SolutionObject + 't, G: Clone> FilletIntersector<'s, 't, O, G> { } // 5. add knots so that each span is similiarly sized + self.equalise_spans(solver, k, &mut pnts, &mut knots)?; + + // 5c. (not upstream, #15256) where the skin is the touch circles of balls whose + // radius varies, hold the skin, not only the rails, to the tolerance: steps + // 5b to 10 build the curves and the skin, then each span's middle section is + // solved and the skin measured against it (`skin_splits`); a span whose skin + // is farther than the tolerance takes that section as a station, the spans are + // equalised again and everything is built again, at most `SKIN_ROUNDS` times. + let skin_held = Self::holds_skin(solver)?; + let station_cap = pnts.len().saturating_mul(SKIN_STATION_FACTOR); + let (deviations, curve_types) = (out.deviations.len(), out.curve_types.len()); + let mut round = 0; + let built = loop { + k.check_cancelled(OP_FLUSH)?; + out.deviations.truncate(deviations); + out.curve_types.truncate(curve_types); + let built = self.build_flush_geometry(solver, k, pseudo, &pnts, &knots, out)?; + // (a round whose law has corners, built wholly from the pieces' definitions, is + // their certified nets joined, not a skin of the stations; where some pieces are + // skins, those are measured and the definitions passed over, `skin_splits`) + let defined = built.kept.as_ref().is_some_and(|kept| { + !kept.pieces.is_empty() + && kept + .pieces + .iter() + .all(|p| matches!(p.kind(), SurfaceKind::ProceduralBlend(_))) + }); + let Some(skin) = built + .fillet_surface + .as_ref() + .filter(|_| skin_held && !defined) + else { + break built; + }; + // (the pieces of a round whose law has corners each skin their own stations: + // the joined surface averages the pieces' rows at each corner, where the session + // builds the corner from the pieces) + let skins: Vec<&Surface> = match built.kept.as_ref() { + Some(kept) => kept.pieces.iter().collect(), + None => vec![skin], + }; + let SkinCheck { + splits, + worst, + not_finite_at, + } = self.skin_splits(solver, k, &pnts, &skins)?; + if splits.is_empty() { + break built; + } + if round == SKIN_ROUNDS || pnts.len().saturating_add(splits.len()) > station_cap { + let failure = match not_finite_at { + Some(s) => BlendFailure::SkinMeasureNotFinite { s }, + None => BlendFailure::SkinPastStationCap { + asked: self.base.base.this_approx_tol_3d, + reached: worst, + stations: pnts.len(), + rounds: round, + }, + }; + return Err(SolidError::blend(OP_FLUSH, failure)); + } + // each split's section after the station it follows + let mut splits = splits.into_iter().peekable(); + let mut merged = Vec::new(); + let mut merged_knots = Vec::new(); + for (i, (p, knot)) in pnts.into_iter().zip(knots).enumerate() { + merged.push(p); + merged_knots.push(knot); + if let Some((_, mid_knot, mid)) = splits.next_if(|(j, ..)| *j == i) { + merged.push(mid); + merged_knots.push(mid_knot); + } + } + pnts = merged; + knots = merged_knots; + self.equalise_spans(solver, k, &mut pnts, &mut knots)?; + round += 1; + }; + let FlushGeometry { + fillet_geom, + center_line, + curve1, + curve2, + uv1, + uv2, + fillet_surface, + kept, + } = built; + + // the fork's `rFilletSolver.AddLawCornerPieces` (7babe17), once for the final skin + if let Some(kept) = kept { + solver.keep_law_corner_pieces(kept)?; + } + + // 11. Correct self-intersecting fillet-surface: never runs upstream + // (bTempTrySelfIntHandler is a FALSE constant). + + // 12. Save Fillet Surface and rail curve data + solver.set_fillet_surface(pseudo, &fillet_geom, fillet_surface)?; + solver.set_center_line_curve(pseudo, &fillet_geom, center_line)?; + solver.set_rail_curve(pseudo, &fillet_geom, 0, curve1)?; + solver.set_rail_mate_uv_curve(pseudo, &fillet_geom, 0, uv1)?; + solver.set_rail_curve(pseudo, &fillet_geom, 1, curve2)?; + solver.set_rail_mate_uv_curve(pseudo, &fillet_geom, 1, uv2)?; + + // restore FilletSolver offset distances in offset Surfaces stored in the FilletSolver + solver.reload_surface_offsets()?; + + // all done + Ok(()) + } + + /// Whether `FlushCurve` holds the skin to the tolerance between stations (#15256): + /// the solver's surface is the exact touch circles of balls whose radius varies + /// ([`FilletSolverOps::skins_varying_balls`]) and no smoothing handler changes the + /// curves (it edits the previous piece in place, so it runs once). + /// + /// # Errors + /// + /// The solver's. + fn holds_skin>(solver: &S) -> Result { + Ok(solver.skins_varying_balls()? + && solver.self_intersection_handler()? != Some(HandlingAlgorithmType::Smoothing)) + } + + /// The spans of the skins (built on the stations `pnts`: one skin, or the pieces of + /// a round whose law has corners, together over the stations' parameters) farther + /// than the tolerance from the balls in their middle (#15256), each with the + /// solver's section there ([`Self::solve_mid_point`], the section the span + /// equalisation adds) and that section's parameter on the skin. The parameter is + /// where the skin passes the section's touch circle (the circle's point nearest the + /// skin's middle iso-curve, projected onto the skin), so the section, added as a + /// station there, keeps the skin's own parametrisation: at the middle knot it would + /// sit where the stations' Hermite centre line puts it, up to 2e-2 along the trace + /// from where the skin does, and bend the skin through its neighbours. The skin's + /// iso-curve at that parameter is measured at [`SKIN_SHARES`] against + /// [`EnvelopeCone`], the envelope of the section's ball family to first order, by its + /// closed-form distance. + /// + /// The samples only steer (they split a span, never keep one). A span they pass is + /// kept only where [`skin_bound::span_bound`] proves the skin over the span's whole + /// rectangle within the tolerance of the interpolated ball family `R` through the solved + /// balls about it (its stations, its middle and, past a station where the round goes on + /// smoothly, the neighbouring span's middle), and split otherwise + /// (`docs/definitions-and-certificates.md` ยง7.6: the decision is on Bernstein + /// enclosures, with their rounding, not on samples). The bound is against `R`, not the + /// round's true balls: that `R` is the true family between the solved sections, which + /// are the solver's converged Newton solutions placed by converged projections, is + /// ARGUED, and the kept span is not marked certified. A peak or kink of the radius law + /// strictly inside a span, narrower than about a quarter of it, is not seen + /// ([`FilletSolverOps::is_at_radius_corner`] is asked only at stations). The certified + /// forms: the round as its definition with a certified net (#15657), interval Newton on + /// the section equations (#16446). Only + /// B-spline skins are measured: a definition's net is certified against its definition, + /// and the spans a definition piece holds are passed over; any other kind is a port + /// invariant. Leaves the solver's offsets loaded. + /// + /// Returns the splits, the largest distance measured (infinite where a span's section + /// could not be placed on the skin, so the span was split unmeasured) and where a value + /// it computed was not finite. A distance, or a cone, that is not finite splits its span + /// as a span off its balls does: it proves nothing either way, and a local failure of an + /// evaluation goes away with the station. `FlushCurve` refuses only if one is still not + /// finite at the cap. + /// + /// Where the section does not project into its span (the skin passes it more than half + /// a span from where its stations put it, or the projection does not converge), the span + /// is split at its middle knot with that section, as [`Self::equalise_spans`] places a + /// station: the span needs stations either way, so the check is total and the case + /// converges or reaches the cap. + /// + /// # Errors + /// + /// [`BlendFailure::StationDidNotConverge`] where no middle section is found from the + /// interpolated guess nor from either end station's (with the last solve's error as its + /// cause, where one failed); a cancellation or port failure of the plane solve as it is; + /// [`SolidError::PortInvariant`] for skins that do not run over the stations' parameters, + /// which they are built from, or of a kind the generator does not build; a cancellation + /// (polled for each span); [`BlendFailure::BallsNest`] from + /// [`EnvelopeCone::at_section`]; those of the rails' evaluations and the projection. + fn skin_splits>( + &self, + solver: &mut S, + k: &Kernel, + pnts: &[TsectPnt], + skins: &[&Surface], + ) -> Result { + let tol = self.base.base.this_approx_tol_3d; + let (Some(first), Some(last)) = (pnts.first(), pnts.last()) else { + solver.reload_surface_offsets()?; + return Ok(SkinCheck::default()); + }; + // the B-spline skins and their domains, which together run over the stations' + // parameters (one skin, or the pieces of a round whose law has corners) + let size = 1.0 + first.curve_parameter.abs().max(last.curve_parameter.abs()); + let near = |a: f64, b: f64| (a - b).abs() <= EFF_ZERO * size; + // (a piece that is a round's definition is its certified net: it is passed over, + // and the spans it holds with it; any other kind is not what the generator builds) + let mut nets = Vec::new(); + let mut defined = false; + for skin in skins { + match skin.kind() { + SurfaceKind::BSpline(net) => nets.push((*skin, net.natural_uv_domain())), + SurfaceKind::ProceduralBlend(_) => defined = true, + _ => { + return Err(SolidError::port_invariant( + OP_FLUSH, + "a variable round's skin is neither a B-spline nor its definition", + )); + } + } + } + let joined = nets.windows(2).all(|w| match w { + [(_, a), (_, b)] => near(a.max().x, b.min().x), + _ => true, + }); + let (Some((_, d0)), Some((_, d1))) = (nets.first(), nets.last()) else { + solver.reload_surface_offsets()?; + return Ok(SkinCheck::default()); + }; + if !defined + && (!joined + || !near(d0.min().x, first.curve_parameter) + || !near(d1.max().x, last.curve_parameter)) + { + // (the skin is built from these stations: a defect of its construction) + return Err(SolidError::port_invariant( + OP_FLUSH, + "the skin does not run over its stations' parameters", + )); + } + + // each span's middle section, with the offsets loaded + solver.reload_surface_offsets()?; + let mut mids = Vec::new(); + for (j, pair) in pnts.windows(2).enumerate() { + k.check_cancelled(OP_FLUSH)?; + let [pj, pj1] = pair else { + continue; + }; + let frac = 0.5; + let knot = (1.0 - frac) * pj.curve_parameter + frac * pj1.curve_parameter; + // the B-spline skin over the span (a span's middle is never a piece's end: the + // pieces end at stations); where a definition piece holds it, the span is passed + // over + let Some(net) = nets + .iter() + .position(|(_, d)| d.min().x < knot && knot < d.max().x) + else { + if defined { + continue; + } + return Err(SolidError::port_invariant( + OP_FLUSH, + "no skin runs over a span's middle", + )); + }; + // from the interpolated guess, then from either end station's, retried after a + // failed solve too (#15034 rule 5: a solve that does not converge is a defect, + // never "no section"); a cancellation or a port failure is not retried + let mut mid = None; + let mut failed = None; + for start in [None, Some(pj), Some(pj1)] { + match self.solve_mid_point_from(solver, k, pj, pj1, frac, start) { + Ok(Some(found)) => { + mid = Some(found); + break; + } + Ok(None) => {} + Err(e) if e.is_port_failure() || matches!(e, SolidError::Cancelled { .. }) => { + return Err(e); + } + Err(e) => failed = Some(e), + } + } + let Some(mid) = mid else { + // (the plane solve reports neither its residual, its last step nor its + // iterations, only whether it found the section) + let failure = Failure::new( + OP_FLUSH, + BlendFailure::StationDidNotConverge { + s: knot, + residual: None, + tolerance: self.base.base.this_approx_tol_3d, + step: None, + iterations: None, + }, + ); + return Err(match failed { + Some(e) => failure.caused_by(e), + None => failure, + } + .into_error()); + }; + mids.push((j, knot, net, mid)); + } + + // its rail points and derivatives on the faces, and the skin against its cone + solver.set_surfaces_to_zero_offset()?; + let mut splits = Vec::new(); + let mut worst = 0.0_f64; + let mut not_finite_at = None; + let binomials = Binomials::new(); + // the stations' balls (their rails on the faces), whether each is a corner of the + // radius law, each measured span's middle ball and the spans the samples pass + let mut station_balls: Vec> = Vec::new(); + let mut corner = Vec::new(); + for p in pnts { + let rails = section_rails(solver, k, p)?; + let ball = section_ball(p.crv_pos(), rails, p.curve_parameter); + // (the family is not carried past a corner of the radius law, nor past a station + // where the radius runs to zero, where the radius turns as `|r|`; a corner strictly + // inside a span is not seen here, #16446) + corner.push(solver.is_at_radius_corner(p) || !above(ball.r, tol)); + station_balls.push(Some(ball)); + } + let mut mid_balls: Vec> = vec![None; pnts.len()]; + let mut pending = Vec::new(); + for (j, knot, net, mid) in mids { + k.check_cancelled(OP_FLUSH)?; + let Some(&(skin, domain)) = nets.get(net) else { + return Err(SolidError::port_invariant( + OP_FLUSH, + "no skin runs over a span's middle", + )); + }; + let rails = section_rails(solver, k, &mid)?; + // (a cone that is not finite leaves the span unmeasured: it is split at its knot, + // as below, and refused only if the values stay not finite to the cap) + let cone = match EnvelopeCone::at_section(knot, mid.crv_pos(), mid.crv_deriv(), rails) { + Err(e) + if matches!( + e.blend_failure(), + Some(BlendFailure::SkinMeasureNotFinite { .. }) + ) => + { + not_finite_at = Some(knot); + splits.push((j, knot, mid)); + continue; + } + cone => cone?, + }; + // the section's parameter on the skin: where the skin passes its touch + // circle's middle, so the skin is measured there and, added as a station at + // that parameter, the section keeps the skin's own parametrisation (the + // middle knot is where the stations' centre line, not the skin, puts it) + let v_mid = 0.5 * (domain.min().y + domain.max().y); + let near_mid = skin.evaluate_point(k, Point2::new(knot, v_mid))?; + let on_circle = cone.touch_circle_point_near(near_mid); + let (lo, hi) = ( + pnts.get(j).map_or(knot, |p| p.curve_parameter), + pnts.get(j + 1).map_or(knot, |p| p.curve_parameter), + ); + let solved = skin.local_point_solve::<()>( + k, + &domain, + SolverOperation::Minimize, + on_circle, + Point2::new(knot, v_mid), + )?; + let at = solved.solution.start.param(0)?; + // (written to accept: a section off its span, or none found, splits the span + // at its middle knot unmeasured) + let in_span = solved.found && lo < at && at < hi; + if !in_span { + splits.push((j, knot, mid)); + worst = f64::INFINITY; + continue; + } + let mut held = true; + for share in SKIN_SHARES { + let v = domain.min().y + share * (domain.max().y - domain.min().y); + let off = cone + .distance(skin.evaluate_point(k, Point2::new(at, v))?) + .abs(); + // (a distance that is not finite proves nothing about the skin either way: + // the span is split, as a span off its balls is, and the round is refused + // only if a value stays not finite to the cap) + if !off.is_finite() { + not_finite_at = Some(at); + held = false; + continue; + } + worst = worst.max(off); + held &= off <= tol; + } + // the samples only steer: a span they pass is kept on its proved bound against the + // interpolated family R over the whole span (below), and split where it is over + // the tolerance or not proved + if let Some(slot) = mid_balls.get_mut(j) { + *slot = Some(section_ball(mid.crv_pos(), rails, at)); + } + if held { + let mut mid = mid; + mid.curve_parameter = at; + pending.push((j, at, mid, skin, domain)); + continue; + } + if !held { + let mut mid = mid; + mid.curve_parameter = at; + splits.push((j, at, mid)); + } + } + // each span the samples pass, against the closed-form family of balls through the + // solved ones about it (`skin_bound`): its stations, its middle and, past a station + // where the round goes on smoothly, the next span's middle + for (j, at, mid, skin, domain) in pending { + k.check_cancelled(OP_FLUSH)?; + let ball = |i: usize| station_balls.get(i).copied().flatten(); + let mut nodes = Vec::new(); + if j > 0 && !corner.get(j).copied().unwrap_or(true) { + nodes.extend(mid_balls.get(j - 1).copied().flatten()); + } + nodes.extend(ball(j)); + nodes.extend(mid_balls.get(j).copied().flatten()); + nodes.extend(ball(j + 1)); + if !corner.get(j + 1).copied().unwrap_or(true) { + nodes.extend(mid_balls.get(j + 1).copied().flatten()); + } + let (lo, hi) = ( + pnts.get(j).map_or(f64::NAN, |p| p.curve_parameter), + pnts.get(j + 1).map_or(f64::NAN, |p| p.curve_parameter), + ); + let bound = match BallFamily::through(&nodes, at, [lo, hi]) { + Some(family) => skin_bound::span_bound( + k, + skin, + &family, + [lo, hi], + [domain.min().y, domain.max().y], + tol, + &binomials, + )?, + None => f64::INFINITY, + }; + worst = worst.max(bound); + // (NaN is not within the tolerance) + if bound.is_nan() || above(bound, tol) { + splits.push((j, at, mid)); + } + } + // (in span order, as the stations are merged) + splits.sort_by_key(|(j, ..)| *j); + solver.reload_surface_offsets()?; + Ok(SkinCheck { + splits, + worst, + not_finite_at, + }) + } + + /// Step 5 of `FlushCurve`: splits every span more than `2.8` times the size of a + /// neighbour at its middle, with the solver's section there + /// ([`Self::solve_mid_point`]), until no span is or the knots have tripled. + /// + /// # Errors + /// + /// Those of [`Self::solve_mid_point`]; `InvalidInput` for more knots than points. + fn equalise_spans>( + &self, + solver: &mut S, + k: &Kernel, + pnts: &mut Vec, + knots: &mut Vec, + ) -> Result<()> { let mut done = false; let maximum_delta_factor = 2.8; let orig_num_knots = knots.len(); @@ -1869,55 +2575,125 @@ impl<'s, 't, O: SolutionObject + 't, G: Clone> FilletIntersector<'s, 't, O, G> { )) } }; - let mut mid_pnt = TsectPnt::new(); - find_guess_mid_tsect_pnt(&pj, &pj1, frac, &mut mid_pnt); - - let plane_orig = mid_pnt.crv_pos(); - let uv1 = mid_pnt.uv_pos(SrfIndex::First); - let uv2 = mid_pnt.uv_pos(SrfIndex::Second); - let plane_normal = mid_pnt.crv_deriv().unitize()?; - - // find filletPoint on given plane satisfying geometry - // requirements implemented in derived SmFilletSolver class - let found_solution = solver.point_on_plane_solve( - k, - plane_orig, - plane_normal, - &uv_domains[0], - &uv_domains[1], - uv1, - uv2, - &mut mid_pnt, - )?; - if !found_solution { - return Err(SolidError::blend_failed( - OP_FLUSH, - "no mid-point section was found", - )); - } - - // save the rail UVCurve points for the new mid-span point - let uvs = [ - mid_pnt.uv_pos(SrfIndex::First), - mid_pnt.uv_pos(SrfIndex::Second), - ]; - - // get the rail 3DCurve sample values - solver.compute_point_values( - k, - uvs, - &uv_domains[0], - &uv_domains[1], - curve_trace_direction, - &mut mid_pnt, - Some(&pj), - )?; + let mid_pnt = self.solve_mid_point(solver, k, &pj, &pj1, frac)?; // add the completed mid-span point to the sPnts array pnts.insert(j + 1, mid_pnt); j += 2; } } + Ok(()) + } + + /// Step 5a of `FlushCurve`: the solver's section at share `frac` of the span from + /// `pj` to `pj1`, on the plane through the interpolated point square to its + /// interpolated tangent, with its rail values. + /// + /// # Errors + /// + /// `SM_ERR` when the plane has no solution; those of the solver. + fn solve_mid_point>( + &self, + solver: &mut S, + k: &Kernel, + pj: &TsectPnt, + pj1: &TsectPnt, + frac: f64, + ) -> Result { + self.solve_mid_point_from(solver, k, pj, pj1, frac, None)? + .ok_or_else(|| SolidError::blend_failed(OP_FLUSH, "no mid-point section was found")) + } + + /// [`Self::solve_mid_point`], its plane solve started from `start`'s surface + /// parameters instead of the interpolated guess's (not upstream, #15256: the skin + /// check retries from each end station), and `None` where the plane has no solution. + /// + /// # Errors + /// + /// Those of the solver. + fn solve_mid_point_from>( + &self, + solver: &mut S, + k: &Kernel, + pj: &TsectPnt, + pj1: &TsectPnt, + frac: f64, + start: Option<&TsectPnt>, + ) -> Result> { + let uv_domains = self.base.base.uv_domains; + let curve_trace_direction = self.base.base.curve_trace_direction; + let mut mid_pnt = TsectPnt::new(); + find_guess_mid_tsect_pnt(pj, pj1, frac, &mut mid_pnt); + + let plane_orig = mid_pnt.crv_pos(); + let guess = start.unwrap_or(&mid_pnt); + let uv1 = guess.uv_pos(SrfIndex::First); + let uv2 = guess.uv_pos(SrfIndex::Second); + let plane_normal = mid_pnt.crv_deriv().unitize()?; + + // find filletPoint on given plane satisfying geometry + // requirements implemented in derived SmFilletSolver class + let found_solution = solver.point_on_plane_solve( + k, + plane_orig, + plane_normal, + &uv_domains[0], + &uv_domains[1], + uv1, + uv2, + &mut mid_pnt, + )?; + if !found_solution { + return Ok(None); + } + + // save the rail UVCurve points for the new mid-span point + let uvs = [ + mid_pnt.uv_pos(SrfIndex::First), + mid_pnt.uv_pos(SrfIndex::Second), + ]; + + // get the rail 3DCurve sample values + solver.compute_point_values( + k, + uvs, + &uv_domains[0], + &uv_domains[1], + curve_trace_direction, + &mut mid_pnt, + Some(pj), + )?; + + Ok(Some(mid_pnt)) + } + + /// Steps 5b to 10 of `FlushCurve` over the stations `pnts` at `knots`: the centre + /// line, the rails and their UV curves, smoothed by a smoothing self-intersection + /// handler, and the fillet surface (with the pieces a round whose law has corners + /// keeps); the curve's type and deviation are appended to `out`. Leaves the solver's + /// offsets at zero. + /// + /// # Errors + /// + /// As `FlushCurve`'s steps. + #[allow(clippy::too_many_lines)] + fn build_flush_geometry>( + &self, + solver: &mut S, + k: &Kernel, + pseudo: &mut FilletBrep, + pnts: &[TsectPnt], + knots: &[f64], + out: &mut TsectCurves, + ) -> Result> { + let uv_domains = self.base.base.uv_domains; + let mut ctrl_pts_3d: Vec = Vec::new(); + let mut uv_ctrl_pts: [Vec; 2] = [Vec::new(), Vec::new()]; + let mut rail_ctrl_pts_3d: [Vec; 2] = [Vec::new(), Vec::new()]; + + let mut curve_type = TsectCurveType::Crossing; + let mut max_deviation = 0.0; + let mut max_angle = 0.0; // 5b. SolidCraft (the fork's 6eecf04): where the fillet radius has a corner, the // center curve and rails turn. A point there carries the average of the @@ -1925,6 +2701,7 @@ impl<'s, 't, O: SolutionObject + 't, G: Clone> FilletIntersector<'s, 't, O, G> { // before the corner (`incoming`), the span that starts there those from after // it, so the curves keep the turn. let mut incoming: Vec> = Vec::new(); + let mut pnts = pnts.to_vec(); let count = pnts.len(); for (kk, slot) in pnts.iter_mut().enumerate() { let mut point_in = None; @@ -2053,11 +2830,11 @@ impl<'s, 't, O: SolutionObject + 't, G: Clone> FilletIntersector<'s, 't, O, G> { let mut surface2_uv_curves: Vec = Vec::new(); let [uv_ctrl_pts0, uv_ctrl_pts1] = &uv_ctrl_pts; let [rail_pts0, rail_pts1] = &rail_ctrl_pts_3d; - flush_crv(3, &ctrl_pts_3d, &knots, &mut curves_3d)?; - flush_crv(2, uv_ctrl_pts0, &knots, &mut surface1_uv_curves)?; - flush_crv(2, uv_ctrl_pts1, &knots, &mut surface2_uv_curves)?; - flush_crv(3, rail_pts0, &knots, &mut curves_3d)?; - flush_crv(3, rail_pts1, &knots, &mut curves_3d)?; + flush_crv(3, &ctrl_pts_3d, knots, &mut curves_3d)?; + flush_crv(2, uv_ctrl_pts0, knots, &mut surface1_uv_curves)?; + flush_crv(2, uv_ctrl_pts1, knots, &mut surface2_uv_curves)?; + flush_crv(3, rail_pts0, knots, &mut curves_3d)?; + flush_crv(3, rail_pts1, knots, &mut curves_3d)?; out.deviations.push(max_deviation); out.curve_types.push(curve_type); @@ -2107,6 +2884,7 @@ impl<'s, 't, O: SolutionObject + 't, G: Clone> FilletIntersector<'s, 't, O, G> { // 10. Generate the fillet surface from the rail curves and centerline let mut fillet_surface = None; + let mut kept = None; if solver.has_surface_generator()? { let created = solver.create_fillet_surface( k, @@ -2117,7 +2895,7 @@ impl<'s, 't, O: SolutionObject + 't, G: Clone> FilletIntersector<'s, 't, O, G> { &mut uv1, &mut uv2, ); - let Some(s) = keep_unported(created)? else { + let Some((s, pieces)) = keep_unported(created)? else { solver.set_status(FilStatus::SurfSkinningFailure)?; return Err(SolidError::blend_failed( OP_FLUSH, @@ -2125,25 +2903,20 @@ impl<'s, 't, O: SolutionObject + 't, G: Clone> FilletIntersector<'s, 't, O, G> { )); }; fillet_surface = s; + kept = pieces; } - // 11. Correct self-intersecting fillet-surface: never runs upstream - // (bTempTrySelfIntHandler is a FALSE constant). - - // 12. Save Fillet Surface and rail curve data - solver.set_fillet_surface(pseudo, &fillet_geom, fillet_surface)?; - solver.set_center_line_curve(pseudo, &fillet_geom, center_line)?; - solver.set_rail_curve(pseudo, &fillet_geom, 0, curve1)?; - solver.set_rail_mate_uv_curve(pseudo, &fillet_geom, 0, uv1)?; - solver.set_rail_curve(pseudo, &fillet_geom, 1, curve2)?; - solver.set_rail_mate_uv_curve(pseudo, &fillet_geom, 1, uv2)?; - - // restore FilletSolver offset distances in offset Surfaces stored in the FilletSolver - solver.reload_surface_offsets()?; - - // all done - Ok(()) - } + Ok(FlushGeometry { + fillet_geom, + center_line, + curve1, + curve2, + uv1, + uv2, + fillet_surface, + kept, + }) + } /// `EvaluateLawPoint`: the solver's point on the plane through `plane_origin` /// with normal `plane_normal` near `uv0`, `uv1`: its curve parameter (user double @@ -2802,8 +3575,16 @@ mod tests { _points: &[TsectPnt], _uv1: &mut BSplineCurve, _uv2: &mut BSplineCurve, - ) -> Result> { - Ok(None) + ) -> Result<(Option, Option)> { + Ok((None, None)) + } + + fn keep_law_corner_pieces(&mut self, _pieces: LawCornerPieces) -> Result<()> { + Ok(()) + } + + fn skins_varying_balls(&self) -> Result { + Ok(false) } fn set_fillet_surface( @@ -3148,4 +3929,544 @@ mod tests { assert_eq!(out.len(), 1); assert!(flush_crv(3, &poly, &[0.0, 1.0], &mut out).is_err()); } + + /// A solver for the skin check (#15256): balls centred on the x axis at `x = t`, radius + /// `r0 + rate t`, with rails at `(t, 0, r)` and `(t, r, 0)`; both surfaces' parameters + /// are `(t, v)`. Its plane solve finds no section `fail_first` times (or always), then + /// the one on the plane; `skin` is the round's surface it builds. + struct SkinMock { + r0: f64, + rate: f64, + fail_first: usize, + err_first: usize, + always_fail: bool, + calls: usize, + skin: Option, + } + + impl SkinMock { + fn new(r0: f64, rate: f64, skin: Option) -> Self { + Self { + r0, + rate, + fail_first: 0, + err_first: 0, + always_fail: false, + calls: 0, + skin, + } + } + } + + impl FilletSolverOps for SkinMock { + type FilletGeom = (); + + fn point_on_plane_solve( + &mut self, + _k: &Kernel, + plane_origin: Point3, + _plane_normal: Vec3, + _uv_domain1: &Extent2d, + _uv_domain2: &Extent2d, + _uv1: Point2, + _uv2: Point2, + point: &mut TsectPnt, + ) -> Result { + self.calls += 1; + if self.calls <= self.err_first { + return Err(SolidError::sm_err("test")); + } + if self.always_fail || self.calls <= self.fail_first { + return Ok(false); + } + *point.uv_pos_mut(SrfIndex::First) = Point2::new(plane_origin.x, 0.5); + *point.uv_pos_mut(SrfIndex::Second) = Point2::new(plane_origin.x, 0.5); + Ok(true) + } + + fn compute_point_values( + &mut self, + _k: &Kernel, + uv_values: [Point2; 2], + _uv_domain1: &Extent2d, + _uv_domain2: &Extent2d, + _curve_trace_direction: f64, + point: &mut TsectPnt, + _previous: Option<&TsectPnt>, + ) -> Result<()> { + point.point_type = IntersectionPointType::Crossing; + *point.uv_pos_mut(SrfIndex::First) = uv_values[0]; + *point.uv_pos_mut(SrfIndex::Second) = uv_values[1]; + *point.uv_deriv_mut(SrfIndex::First) = Vec2::new(1.0, 0.0); + *point.uv_deriv_mut(SrfIndex::Second) = Vec2::new(1.0, 0.0); + *point.crv_pos_mut() = Vec3::new(uv_values[0].x, 0.0, 0.0); + *point.crv_deriv_mut() = Vec3::new(1.0, 0.0, 0.0); + Ok(()) + } + + fn step_solve( + &mut self, + _k: &Kernel, + _point: &TsectPnt, + _step_size: &mut f64, + _uv_domain1: &Extent2d, + _uv_domain2: &Extent2d, + _flags: &mut StepSolve, + _next: &mut TsectPnt, + ) -> Result<()> { + Err(SolidError::sm_err("test")) + } + + fn compute_surface_values( + &mut self, + _k: &Kernel, + _uv_values: [Point2; 2], + _point: &mut TsectPnt, + ) -> Result<()> { + Ok(()) + } + + fn compute_uv_vectors(&mut self, _k: &Kernel, _point: &mut TsectPnt) -> Result<()> { + Ok(()) + } + + fn set_surfaces_to_zero_offset(&mut self) -> Result<()> { + Ok(()) + } + + fn reload_surface_offsets(&mut self) -> Result<()> { + Ok(()) + } + + fn offset_radii_can_change(&self) -> Result { + Ok(true) + } + + fn rail_surface_evaluate_1st_derivatives( + &mut self, + _k: &Kernel, + rail: usize, + uv: Point2, + ) -> Result<(Point3, Vec3, Vec3)> { + let t = uv.x; + let r = self.r0 + self.rate * t; + Ok(if rail == 0 { + ( + Vec3::new(t, 0.0, r), + Vec3::new(1.0, 0.0, self.rate), + Vec3::ZERO, + ) + } else { + ( + Vec3::new(t, r, 0.0), + Vec3::new(1.0, self.rate, 0.0), + Vec3::ZERO, + ) + }) + } + + fn set_status(&mut self, _status: FilStatus) -> Result<()> { + Ok(()) + } + + fn last_fillet_geom(&self) -> Result<()> { + Ok(()) + } + + fn self_intersection_handler(&self) -> Result> { + Ok(None) + } + + fn smooth_out_intersection( + &mut self, + _k: &Kernel, + _pseudo: &mut FilletBrep, + _geom: &(), + _curves_3d: &mut Vec, + _uv_curves1: &mut Vec, + _uv_curves2: &mut Vec, + ) -> Result<()> { + Ok(()) + } + + fn has_surface_generator(&self) -> Result { + Ok(true) + } + + fn create_fillet_surface( + &mut self, + _k: &Kernel, + _center_line: &mut BSplineCurve, + _curve1: &mut BSplineCurve, + _curve2: &mut BSplineCurve, + _points: &[TsectPnt], + _uv1: &mut BSplineCurve, + _uv2: &mut BSplineCurve, + ) -> Result<(Option, Option)> { + Ok((self.skin.clone(), None)) + } + + fn keep_law_corner_pieces(&mut self, _pieces: LawCornerPieces) -> Result<()> { + Ok(()) + } + + fn skins_varying_balls(&self) -> Result { + Ok(true) + } + + fn set_fillet_surface( + &mut self, + _pseudo: &mut FilletBrep, + _geom: &(), + _surface: Option, + ) -> Result<()> { + Ok(()) + } + + fn set_center_line_curve( + &mut self, + _pseudo: &mut FilletBrep, + _geom: &(), + _center_line: BSplineCurve, + ) -> Result<()> { + Ok(()) + } + + fn set_rail_curve( + &mut self, + _pseudo: &mut FilletBrep, + _geom: &(), + _rail: usize, + _curve: BSplineCurve, + ) -> Result<()> { + Ok(()) + } + + fn set_rail_mate_uv_curve( + &mut self, + _pseudo: &mut FilletBrep, + _geom: &(), + _rail: usize, + _uv_curve: BSplineCurve, + ) -> Result<()> { + Ok(()) + } + } + + /// The flat chord between the rails of radius `r0` balls on the x axis, from `x = x0` to + /// `x0 + 1` over the parameter `u` in [0, 1]: `r0 (1 - 1/sqrt 2)` off the balls in its + /// middle. + fn chord_skin(r0: f64, x0: f64) -> Surface { + bilinear([ + [x0, 0.0, r0], + [x0 + 1.0, 0.0, r0], + [x0, r0, 0.0], + [x0 + 1.0, r0, 0.0], + ]) + } + + /// Stations at the parameters `ts` on the mock's balls. + fn skin_stations(ts: &[f64]) -> Vec { + ts.iter() + .map(|&t| pnt([t, 0.5], [t, 0.5], [1.0, 0.0, 0.0], t)) + .collect() + } + + fn skin_check(mock: &mut SkinMock, ts: &[f64], skin: &Surface) -> Result { + let k = &Kernel::default(); + let (a, b) = surfaces(); + let d = Extent2d::from_bounds(0.0, 0.0, 1.0, 1.0); + let fi: FilletIntersector<'_, '_, NoSurfaceHandle, ()> = + FilletIntersector::new(k, &a, &d, &b, &d, None).unwrap(); + fi.skin_splits(mock, k, &skin_stations(ts), &[skin]) + } + + /// `FlushCurve` over three stations on the mock's balls, whose skin is the mock's. + fn flush_with(mock: SkinMock) -> Result<()> { + flush_over(mock, &[0.0, 0.5, 1.0]) + } + + /// `FlushCurve` over stations at `ts` on the mock's balls, whose skin is the mock's. + fn flush_over(mut mock: SkinMock, ts: &[f64]) -> Result<()> { + let k = &Kernel::default(); + let (a, b) = surfaces(); + let d = Extent2d::from_bounds(0.0, 0.0, 1.0, 1.0); + let mut fi: FilletIntersector<'_, '_, NoSurfaceHandle, ()> = + FilletIntersector::new(k, &a, &d, &b, &d, None).unwrap(); + for p in skin_stations(ts) { + let id = fi.base.base.alloc_point(p); + fi.base.base.add_point_to_curve(id).unwrap(); + } + let mut out = TsectCurves::default(); + fi.flush_curve(&mut mock, k, &mut FilletBrep::new(), &mut out) + } + + #[test] + fn the_skin_check_measures_the_worst_distance_and_splits_where_it_is_past() { + let skin = chord_skin(1.0, 0.0); + let mut mock = SkinMock::new(1.0, 0.0, None); + let SkinCheck { + splits, + worst, + not_finite_at, + } = skin_check(&mut mock, &[0.0, 1.0], &skin).unwrap(); + assert_eq!((splits.len(), not_finite_at), (1, None)); + let (j, at, _) = &splits[0]; + assert_eq!(*j, 0); + assert!((at - 0.5).abs() < 1e-9, "{at}"); + assert!( + (worst - (1.0 - core::f64::consts::FRAC_1_SQRT_2)).abs() < 1e-9, + "{worst}" + ); + } + + /// Before, a section that did not project into its span refused the round ("a span's + /// middle section is not on its skin"); now the span takes that section at its middle + /// knot, unmeasured, as the span equalisation places a station. + #[test] + fn a_section_off_its_skin_splits_the_span_at_its_knot() { + let skin = chord_skin(1.0, 5.0); + let mut mock = SkinMock::new(1.0, 0.0, None); + let SkinCheck { splits, worst, .. } = skin_check(&mut mock, &[0.0, 1.0], &skin).unwrap(); + assert_eq!(splits.len(), 1); + let (j, at, mid) = &splits[0]; + assert_eq!((*j, *at), (0, 0.5)); + assert_eq!(mid.curve_parameter, 0.5); + assert!(worst.is_infinite()); + } + + #[test] + fn balls_whose_radius_outruns_their_centres_are_refused_as_nesting() { + let skin = chord_skin(1.0, 0.0); + let mut mock = SkinMock::new(1.0, 2.0, None); + let e = skin_check(&mut mock, &[0.0, 1.0], &skin).unwrap_err(); + assert_eq!( + e.blend_failure(), + Some(&BlendFailure::BallsNest { + s: 0.5, + rate: 2.0, + speed: 1.0 + }), + "{e:?}" + ); + assert_eq!(e.kind(), crate::error::ErrorKind::BallsFold); + assert!(e.is_refusal()); + } + + /// A value that is not finite proves nothing about the skin: the span is split at its + /// knot (as before, when a NaN distance split the span), and the round is refused as a + /// defect only if it stays not finite to the cap. + #[test] + fn a_skin_measure_that_is_not_finite_splits_and_is_a_defect_at_the_cap() { + let skin = chord_skin(1.0, 0.0); + let mut mock = SkinMock::new(f64::NAN, 0.0, None); + let SkinCheck { + splits, + not_finite_at, + .. + } = skin_check(&mut mock, &[0.0, 1.0], &skin).unwrap(); + assert_eq!(not_finite_at, Some(0.5)); + assert_eq!((splits.len(), splits[0].1), (1, 0.5)); + let e = flush_with(SkinMock::new(f64::NAN, 0.0, Some(skin))).unwrap_err(); + assert!( + matches!( + e.blend_failure(), + Some(BlendFailure::SkinMeasureNotFinite { .. }) + ), + "{e:?}" + ); + assert!(e.is_defect()); + } + + #[test] + fn a_skin_that_does_not_run_over_its_stations_is_a_port_invariant() { + let skin = chord_skin(1.0, 0.0); + let mut mock = SkinMock::new(1.0, 0.0, None); + let e = skin_check(&mut mock, &[0.0, 2.0], &skin).unwrap_err(); + assert!( + matches!( + e, + SolidError::PortInvariant { + reason: "the skin does not run over its stations' parameters", + .. + } + ), + "{e:?}" + ); + } + + #[test] + fn a_middle_section_is_retried_from_both_end_stations_then_refused_as_not_converging() { + let skin = chord_skin(1.0, 0.0); + // found on the third start: the check goes on + let mut mock = SkinMock::new(1.0, 0.0, None); + mock.fail_first = 2; + let c = skin_check(&mut mock, &[0.0, 1.0], &skin).unwrap(); + assert_eq!((mock.calls, c.splits.len()), (3, 1)); + // a failed solve is retried too + let mut mock = SkinMock::new(1.0, 0.0, None); + mock.err_first = 2; + let c = skin_check(&mut mock, &[0.0, 1.0], &skin).unwrap(); + assert_eq!((mock.calls, c.splits.len()), (3, 1)); + // found from none of the three: a defect with its station + let mut mock = SkinMock::new(1.0, 0.0, None); + mock.always_fail = true; + let e = skin_check(&mut mock, &[0.0, 1.0], &skin).unwrap_err(); + assert_eq!(mock.calls, 3); + match e.blend_failure() { + Some(&BlendFailure::StationDidNotConverge { + s, + residual, + step, + iterations, + .. + }) => { + // (the plane solve reports only whether it found the section) + assert_eq!((s, residual, step, iterations), (0.5, None, None, None)); + } + other => panic!("{other:?}"), + } + assert!(e.is_defect()); + } + + /// A skin that stays off its balls whatever the stations (the mock builds the same flat + /// chord every round) reaches the cap and is refused with the numbers. + #[test] + fn a_skin_still_off_its_balls_at_the_cap_is_refused_with_its_numbers() { + let e = flush_with(SkinMock::new(1.0, 0.0, Some(chord_skin(1.0, 0.0)))).unwrap_err(); + let tol = { + let k = &Kernel::default(); + let (a, b) = surfaces(); + let d = Extent2d::from_bounds(0.0, 0.0, 1.0, 1.0); + let fi: FilletIntersector<'_, '_, NoSurfaceHandle, ()> = + FilletIntersector::new(k, &a, &d, &b, &d, None).unwrap(); + fi.base.base.this_approx_tol_3d + }; + match e.blend_failure() { + Some(&BlendFailure::SkinPastStationCap { + asked, + reached, + stations, + rounds, + }) => { + assert_eq!(asked, tol); + assert!( + (reached - (1.0 - core::f64::consts::FRAC_1_SQRT_2)).abs() < 1e-9, + "{reached}" + ); + assert_eq!(rounds, SKIN_ROUNDS, "{e}"); + assert!(stations > 3, "{e}"); + } + other => panic!("{other:?}"), + } + assert_eq!(e.kind(), crate::error::ErrorKind::NotWithinTolerance); + } + + /// The tolerance of the mock's intersector. + fn mock_tol() -> f64 { + let k = &Kernel::default(); + let (a, b) = surfaces(); + let d = Extent2d::from_bounds(0.0, 0.0, 1.0, 1.0); + let fi: FilletIntersector<'_, '_, NoSurfaceHandle, ()> = + FilletIntersector::new(k, &a, &d, &b, &d, None).unwrap(); + fi.base.base.this_approx_tol_3d + } + + /// A skin on its balls at both stations and at the span's middle, where the samples + /// measure it, but bulged twenty times the tolerance off them in between (closed form, + /// `skin_bound::tests::bulged_tube`): the samples alone kept it (no split, the largest + /// distance measured 0); the proved bound over the whole span splits it, and its bound + /// covers the bulge's peak. + #[test] + fn a_skin_off_its_balls_between_the_samples_is_split_on_its_bound() { + let tol = mock_tol(); + let peak = 20.0 * tol; + let bump = peak * 12.0 * 3.0_f64.sqrt(); + let skin = skin_bound::tests::bulged_tube(1.0, bump); + let mut mock = SkinMock::new(1.0, 0.0, None); + let SkinCheck { + splits, + worst, + not_finite_at, + } = skin_check(&mut mock, &[0.0, 1.0], &skin).unwrap(); + assert_eq!((splits.len(), not_finite_at), (1, None), "{worst}"); + let (j, at, _) = &splits[0]; + assert_eq!(*j, 0); + assert!((at - 0.5).abs() < 1e-9, "{at}"); + assert!(worst >= peak, "{worst} < {peak}"); + // the samples on the middle iso-curve see the skin on its balls + let k = &Kernel::default(); + let cone = EnvelopeCone { + c: Point3::new(0.5, 0.0, 0.0), + r: 1.0, + axis: None, + }; + for share in SKIN_SHARES { + let off = cone.distance(skin.evaluate_point(k, Point2::new(0.5, share)).unwrap()); + assert!(off.abs() < 1e-12, "{share}: {off}"); + } + } + + /// The same skin on its balls everywhere is kept: its proved bound is rounding only. + #[test] + fn a_skin_on_its_balls_is_kept_on_its_bound() { + let skin = skin_bound::tests::bulged_tube(1.0, 0.0); + let mut mock = SkinMock::new(1.0, 0.0, None); + let c = skin_check(&mut mock, &[0.0, 1.0], &skin).unwrap(); + assert!(c.splits.is_empty(), "{:?}", c.worst); + assert!(c.worst < 1e-12, "{}", c.worst); + } + + /// Through `FlushCurve`: the bulged skin (the mock builds it whatever the stations) is + /// refused at the cap; with the samples alone the round was kept after one round, off + /// its balls by twenty times the tolerance. + #[test] + fn a_skin_off_its_balls_between_the_samples_is_refused_at_the_cap() { + let tol = mock_tol(); + let bump = 20.0 * tol * 12.0 * 3.0_f64.sqrt(); + let skin = skin_bound::tests::bulged_tube(1.0, bump); + let e = flush_over(SkinMock::new(1.0, 0.0, Some(skin)), &[0.0, 1.0]).unwrap_err(); + match e.blend_failure() { + Some(&BlendFailure::SkinPastStationCap { asked, reached, .. }) => { + assert_eq!(asked, tol); + assert!(reached > tol, "{reached}"); + } + other => panic!("{other:?}"), + } + } + + /// A cancellation reaches the skin check's rounds. + #[test] + fn the_skin_check_polls_cancellation() { + let skin = chord_skin(1.0, 0.0); + let token = crate::kernel::CancelToken::new(); + token.cancel(); + let mut k = Kernel::default(); + k.set_cancel_token(token); + let k = &k; + let (a, b) = surfaces(); + let d = Extent2d::from_bounds(0.0, 0.0, 1.0, 1.0); + let fi: FilletIntersector<'_, '_, NoSurfaceHandle, ()> = + FilletIntersector::new(k, &a, &d, &b, &d, None).unwrap(); + let mut mock = SkinMock::new(1.0, 0.0, None); + let e = fi + .skin_splits(&mut mock, k, &skin_stations(&[0.0, 1.0]), &[&skin]) + .unwrap_err(); + assert!(matches!(e, SolidError::Cancelled { .. }), "{e:?}"); + } + + /// A skin of a kind the generator does not build is a port invariant, not a pass. + #[test] + fn a_skin_neither_b_spline_nor_definition_is_a_port_invariant() { + let plane = Surface::from(crate::surface::plane::Plane::new( + Point3::ZERO, + Vec3::new(1.0, 0.0, 0.0), + Vec3::new(0.0, 1.0, 0.0), + Vec2::new(1.0, 1.0), + &Extent2d::from_bounds(0.0, 0.0, 1.0, 1.0), + )); + let mut mock = SkinMock::new(1.0, 0.0, None); + let e = skin_check(&mut mock, &[0.0, 1.0], &plane).unwrap_err(); + assert!(matches!(e, SolidError::PortInvariant { .. }), "{e:?}"); + } } diff --git a/solidcore/crates/solidcore/src/blend/fillet_intersector/skin_bound.rs b/solidcore/crates/solidcore/src/blend/fillet_intersector/skin_bound.rs new file mode 100644 index 00000000000..c974d345b6d --- /dev/null +++ b/solidcore/crates/solidcore/src/blend/fillet_intersector/skin_bound.rs @@ -0,0 +1,1102 @@ +//! A proved bound, over a whole span, of a variable round's skin's distance from the +//! interpolated ball family `R` through the solved sections about the span (#15256): not +//! from the round's true balls, and not a certificate of the round. +//! +//! Upstream: none (not in SMLib or SolidCraft). +//! +//! | Rust | Upstream | +//! |--------------------------|----------| +//! | [`BallFamily`] | (none) | +//! | [`BallFamily::through`] | (none) | +//! | [`span_bound`] | (none) | +//! +//! **What is bounded.** `FlushCurve` solves sections of the round exactly (to the solver's +//! convergence): the stations and the section in each span's middle, each a ball `(c, r)` +//! placed at the skin's own parameter where the skin passes the ball's touch circle. +//! [`BallFamily`] is the closed-form family `R` of balls through the solved balls about one +//! span: its two stations, its middle and, past a station where the round goes on smoothly +//! (not a corner of the radius law, not a radius of zero), the neighbouring span's middle. +//! Its centre and radius are their Lagrange interpolants (degree at most four) in the +//! centres' chord length `tau`, scaled to the span, over the nodes' range. The radius of a +//! ball is `|r(tau)|`; where the radius runs through zero, the nodes' radii take the signs +//! that make the law smoothest. The quantity bounded is `phi(x) = min_tau psi(tau; x)`, +//! `psi = |x - c(tau)| - |r(tau)|`, the signed distance from `x` to the union of `R`'s balls +//! (to their envelope where the nearest ball is inside the range), for every point +//! `x = S(u, v)` of the skin over the span `u in [t_a, t_b]` and its whole `v` range. +//! [`span_bound`] returns `B` with `|phi(S(u, v))| <= B` over that whole rectangle: no point +//! is sampled, every bound carries its rounding. +//! +//! **How.** With `F(tau; x) = |x - c|^2 - r^2 = psi (psi + 2 |r|)`: +//! - In the skin's homogeneous form about the middle ball's centre, `x = X / W` with `X`, `W` +//! Bernstein polynomials on each Bรฉzier piece (`crate::query::distance_bound`'s pieces, +//! with the error they carry), and a correspondence `tau(s, v)` bilinear on the piece +//! (through each corner's nearest ball, found by Newton's method; any correspondence +//! serves: the bounds below hold for every `tau` in the range), +//! `F W^2 = |X|^2 - 2 W X.c + W^2 (|c|^2 - r^2)` and `F_tau W^2` are polynomials in the +//! piece's parameters, written in Bernstein form by products of Bernstein polynomials. +//! - The family's second derivative `F_tautau = 2 |c'|^2 - 2 (x - c).c'' - 2 r'^2 - 2 r r''` +//! is enclosed in `[m, M]` over the whole range and the piece's box of points, on +//! [`F2_CELLS`] cells: the part in `tau` alone as one Bernstein polynomial, `(x - c).c''` +//! by intervals, widened for rounding. A piece with `m <= 0` is not proved (infinite). +//! - Lower side: for every `tau` in the range, `F(tau) >= F(u) + F_tau(u) (tau - u) + +//! m (tau - u)^2 / 2 >= F(u) - F_tau(u)^2 / (2 m)` (`u` the correspondence), so +//! `min_tau F >= (F W^2 . W^2 - (F_tau W^2)^2 / (2 m)) / W^4`, whose numerator is one +//! polynomial: the least quotient of its Bernstein coefficients by `W^4`'s (in one +//! degree, each with its error) bounds `min_tau F` from below on the piece (the rational +//! convex hull property: the quotient is a mean of the coefficients' quotients with weights +//! `w_i B_i >= 0`). Where that is negative, as `psi = sqrt(r^2 + F) - |r|` rises with `F` +//! and, for `F < 0`, with `|r|`, `psi >= sqrt(r_lo^2 + F_min) - r_lo` (or +//! `-sqrt(-F_min)` where `r_lo^2 + F_min < 0`), `r_lo` the least `|r|` over the `tau` +//! where `F` can be negative (within `(|F_tau| + sqrt(F_tau^2 + 2 m |F|)) / m` of `u`). +//! - Upper side: with `tau* = u - F_tau(u) / M` inside the range, +//! `F(tau*) <= F(u) - F_tau(u)^2 / (2 M)` (Taylor with `F_tautau <= M`), the same +//! numerator with `M`; its largest coefficient bounds `F` at a ball of the family, and +//! `psi <= sqrt(r_lo^2 + F) - r_lo` there (`psi` falls with `|r|` for `F > 0`); `F(u)` +//! itself is the other candidate. At the correspondence also `psi <= max(F / (2 |r|), 0)` +//! (for `F >= 0`, `|x - c| >= |r|`), as a quotient of polynomials where `r` is proved +//! positive. +//! - A piece whose bound exceeds the tolerance is quartered (de Casteljau, with its error), +//! or halved in `u` where the radius comes within the bound of zero on it (the skin closes +//! to a point there), at most [`MAX_PIECES`] pieces per span. Every piece's bound is a +//! bound, so the largest over the pieces left is returned, whatever stopped the +//! subdivision. +//! +//! **The coefficients' error** (Higham, *Accuracy and Stability of Numerical Algorithms*, 2nd +//! ed., section 3.1, `gamma_n = n u / (1 - n u)`), one absolute bound per polynomial: +//! - the skin's pieces: their own, from `pieces_about` (the form's, the extraction's and the +//! translation's), and each quartering's; +//! - the family's polynomials written on a piece or a cell: Horner's rule on Bernstein +//! polynomials, each step a product and a sum as below; +//! - a product of Bernstein polynomials: each coefficient is a sum of at most +//! `N = (min du + 1)(min dv + 1)` terms, each two coefficients scaled by four exact +//! binomials, multiplied, and divided by a product of two, so within `gamma_(N + 8)` of the +//! product of the two largest coefficients (the binomial weights sum to one, Vandermonde); +//! the inputs' errors `ea`, `eb` add `ea |b| + |a| eb + ea eb`; +//! - a degree elevation is a product with ones; a sum `a + x b`, `gamma_2 (|a| + |x| |b|)`; +//! - the final quotients and roots, `gamma_8` of the bound. +//! +//! **What is not bounded** (ARGUED, said where it is used): that `R` is the true family of the +//! round's balls between its solved sections (it is their interpolant, exact at them), and +//! that the nearest true ball of each skin point lies inside the range. So a span kept on +//! this bound is not marked certified. A peak or kink of the radius law strictly inside a +//! span, narrower than about a quarter of it, is not in `R` (radius corners are found only +//! at stations). Enclosing the true family, by interval Newton on the section equations, is +//! #16446; the round as its certified definition is #15657. The interpolant's +//! coefficients define `R`: their own rounding is no error of the bound. +//! +//! Deviations: not upstream. No recursion: the pieces wait on a work list, at most +//! [`MAX_PIECES`] per span. + +use crate::geom::certified::above; +use crate::geom::extent2d::Extent2d; +use crate::kernel::Kernel; +use crate::math::{Point3, EFF_ZERO}; +use crate::nurbs::math::gamma; +use crate::offset::construction::bernstein::{Bernstein2, Binomials}; +use crate::query::distance_bound::{pieces_about, Piece}; +use crate::surface::surface::Surface; +use crate::{Result, SolidError}; + +const OP: &str = "blend::fillet_intersector::skin_bound::span_bound"; + +/// The cells of the family's range on which its second derivative is enclosed. +const F2_CELLS: usize = 8; + +/// The most pieces one span's bound subdivides its skin into. +pub(super) const MAX_PIECES: usize = 256; + +/// A solved ball of the round: its centre, its radius and the skin's parameter where the +/// skin passes its touch circle. +#[derive(Debug, Clone, Copy)] +pub(super) struct Ball { + /// The centre. + pub(super) c: Point3, + /// The radius. + pub(super) r: f64, + /// The skin's parameter. + pub(super) at: f64, +} + +/// A polynomial in `tau`, by its monomial coefficients (lowest first). +type Mono = Vec; + +/// The closed-form family of balls through the solved balls about a span (its stations, its +/// middle and the neighbouring spans' middles where the round goes on smoothly past a +/// station): centre (about the middle ball's centre) and radius their Lagrange interpolants +/// in `tau = (t - t_m) / h` (degree at most four), over the nodes' range. The balls' radius +/// is `|r(tau)|` (`F` holds only `r^2`). +#[derive(Debug, Clone)] +pub(super) struct BallFamily { + origin: Point3, + /// Each node's skin parameter and family parameter, increasing: the start of the + /// correspondence (piecewise linear between them). + knots: Vec<(f64, f64)>, + c: [Mono; 3], + r: Mono, + range: [f64; 2], +} + +/// The Hermite interpolant through `(tau_i, y_i)` with slope `y'_i` where given (Newton's +/// divided differences on repeated nodes), in monomial form. It defines the family: its +/// rounding is not an error of anything. +fn hermite(data: &[(f64, f64, Option)]) -> Mono { + let mut z = Vec::new(); + let mut y = Vec::new(); + let mut slope_at = Vec::new(); + for &(t, v, d) in data { + z.push(t); + y.push(v); + slope_at.push(None); + if let Some(d) = d { + z.push(t); + y.push(v); + slope_at.push(Some(d)); + } + } + // the divided-difference table, column by column, keeping each column's head + let mut heads = Vec::new(); + let mut column = y; + let mut order = 0; + while let Some(&head) = column.first() { + heads.push(head); + order += 1; + let mut next = Vec::new(); + for (i, w) in column.windows(2).enumerate() { + let (Some(&zi), Some(&zj)) = (z.get(i), z.get(i + order)) else { + continue; + }; + let [a, b] = [ + w.first().copied().unwrap_or(0.0), + w.get(1).copied().unwrap_or(0.0), + ]; + next.push(if zj == zi { + slope_at.get(i + 1).copied().flatten().unwrap_or(0.0) + } else { + (b - a) / (zj - zi) + }); + } + column = next; + } + // Newton form to monomials: p = h0 + (t - z0)(h1 + (t - z1)(h2 + ...)) + let mut mono: Mono = Vec::new(); + for (k, &h) in heads.iter().enumerate().rev() { + // mono = mono * (t - z_k) + h + let zk = z.get(k).copied().unwrap_or(0.0); + let mut next = vec![0.0; mono.len() + 1]; + for (i, &m) in mono.iter().enumerate() { + if let Some(slot) = next.get_mut(i + 1) { + *slot += m; + } + if let Some(slot) = next.get_mut(i) { + *slot -= m * zk; + } + } + if let Some(slot) = next.first_mut() { + *slot += h; + } + mono = next; + } + mono +} + +/// The signs of the nodes' radii (the first positive) whose second divided differences have +/// the least sum of squares: `|r|` folds where the law runs through zero, and the family is +/// fitted to the unfolded law. It only chooses the family, which the bounds do not trust. +fn smooth_signs(nodes: &[Ball]) -> Vec { + let n = nodes.len(); + let mut best = (f64::INFINITY, vec![1.0; n]); + if !(3..=8).contains(&n) { + return best.1; + } + for mask in 0..(1_usize << (n - 1)) { + let signs: Vec = (0..n) + .map(|i| { + if i > 0 && mask & (1 << (i - 1)) != 0 { + -1.0 + } else { + 1.0 + } + }) + .collect(); + let mut cost = 0.0; + for (w, s) in nodes.windows(3).zip(signs.windows(3)) { + if let ([a, b, c], [sa, sb, sc]) = (w, s) { + let d1 = (sb * b.r - sa * a.r) / (b.at - a.at); + let d2 = (sc * c.r - sb * b.r) / (c.at - b.at); + let dd = (d2 - d1) / (c.at - a.at); + cost += dd * dd; + } + } + if cost < best.0 { + best = (cost, signs); + } + } + best.1 +} + +/// The value at the skin parameter `t` of the piecewise linear map through `(nodes[i].at, +/// values[i])` (extended by its end pieces). +fn interpolate(nodes: &[Ball], values: &[f64], t: f64) -> f64 { + let pairs: Vec<(f64, f64)> = nodes + .iter() + .map(|q| q.at) + .zip(values.iter().copied()) + .collect(); + linear_through(&pairs, t) +} + +/// The piecewise linear map through `pairs` (increasing in their first) at `t`, extended +/// by its end pieces. +fn linear_through(pairs: &[(f64, f64)], t: f64) -> f64 { + let n = pairs.len(); + let i = pairs + .iter() + .position(|&(x, _)| x > t) + .unwrap_or(n) + .clamp(1, n.saturating_sub(1).max(1)); + match (pairs.get(i - 1), pairs.get(i)) { + (Some(&(x0, y0)), Some(&(x1, y1))) if x1 > x0 => y0 + (t - x0) * (y1 - y0) / (x1 - x0), + (Some(&(_, y0)), _) => y0, + _ => f64::NAN, + } +} + +/// The value of `p` at `t` (Horner). +fn eval(p: &[f64], t: f64) -> f64 { + p.iter().rev().fold(0.0, |acc, &a| acc * t + a) +} + +/// The derivative of `p`. +fn deriv(p: &[f64]) -> Mono { + p.iter() + .enumerate() + .skip(1) + .map(|(i, &a)| { + #[allow(clippy::cast_precision_loss)] + let k = i as f64; + k * a + }) + .collect() +} + +/// The least `|x|` for `x` in `[lo, hi]` (NaN for a range that is not one). +fn least_size((lo, hi): (f64, f64)) -> f64 { + if lo <= 0.0 && hi >= 0.0 { + 0.0 + } else if lo > 0.0 { + lo + } else if hi < 0.0 { + -hi + } else { + f64::NAN + } +} + +/// The range of `a b` for `a`, `b` in their ranges. +fn product_range((a0, a1): (f64, f64), (b0, b1): (f64, f64)) -> (f64, f64) { + let p = [a0 * b0, a0 * b1, a1 * b0, a1 * b1]; + ( + p.iter().copied().fold(f64::INFINITY, f64::min), + p.iter().copied().fold(f64::NEG_INFINITY, f64::max), + ) +} + +/// A Bernstein polynomial and a bound on each coefficient's error. +#[derive(Debug, Clone)] +struct Poly { + p: Bernstein2, + e: f64, +} + +impl Poly { + fn largest(&self) -> f64 { + self.p.max_abs_coefficient() + } + + fn lo(&self) -> f64 { + self.p.min_coefficient() - self.e + } + + fn hi(&self) -> f64 { + self.p.max_coefficient() + self.e + } + + fn mul(&self, o: &Self, bi: &Binomials) -> Result { + let ((au, av), (bu, bv)) = (self.p.degrees(), o.p.degrees()); + let terms = (au.min(bu) + 1) * (av.min(bv) + 1); + let (ma, mb) = (self.largest(), o.largest()); + let e = gamma(terms + 8) * ma * mb + self.e * mb + ma * o.e + self.e * o.e; + Ok(Self { + p: self.p.mul(&o.p, bi)?, + e, + }) + } + + fn elevate(&self, du: usize, dv: usize, bi: &Binomials) -> Result { + let (su, sv) = self.p.degrees(); + if (su, sv) == (du, dv) { + return Ok(self.clone()); + } + let terms = (su.min(du.saturating_sub(su)) + 1) * (sv.min(dv.saturating_sub(sv)) + 1); + Ok(Self { + p: self.p.elevate(du, dv, bi)?, + e: self.e + gamma(terms + 8) * self.largest(), + }) + } + + /// `self + x o`. + fn add_scaled(&self, o: &Self, x: f64, bi: &Binomials) -> Result { + let ((au, av), (bu, bv)) = (self.p.degrees(), o.p.degrees()); + let (du, dv) = (au.max(bu), av.max(bv)); + let a = self.elevate(du, dv, bi)?; + let b = o.elevate(du, dv, bi)?; + let e = a.e + x.abs() * b.e + gamma(2) * (a.largest() + x.abs() * b.largest()); + Ok(Self { + p: a.p.add_scaled(&b.p, x, bi)?, + e, + }) + } +} + +/// The polynomial `p` of the correspondence `tau` (a polynomial on the piece), by Horner's +/// rule on Bernstein polynomials, with its error. +fn mono_of(p: &[f64], tau: &Poly, bi: &Binomials) -> Result { + let constant = |x: f64| Poly { + p: Bernstein2::constant(x), + e: 0.0, + }; + let mut acc = constant(0.0); + for &a in p.iter().rev() { + acc = constant(a).add_scaled(&acc.mul(tau, bi)?, 1.0, bi)?; + } + Ok(acc) +} + +/// The range of `p` over `[lo, hi]`: the hull of its Bernstein coefficients there, with +/// their error (`None` where not finite). +fn mono_range(p: &[f64], lo: f64, hi: f64, bi: &Binomials) -> Result> { + let tau = Poly { + p: Bernstein2::new(1, 0, vec![lo, hi])?, + e: 0.0, + }; + let q = mono_of(p, &tau, bi)?; + let (a, b) = (q.lo(), q.hi()); + Ok((a.is_finite() && b.is_finite()).then_some((a, b))) +} + +/// The range of the quotient `n / d` of two polynomials over the square, `d` positive: with +/// both written in one degree, `n / d = sum n_i B_i / sum d_i B_i` is a mean of the +/// coefficients' quotients `n_i / d_i` weighted by `d_i B_i >= 0` (the rational convex hull +/// property), each taken with its coefficients' errors and rounded outward; `None` where a +/// coefficient of `d` is not proved positive. +fn quotient_range(n: &Poly, d: &Poly, bi: &Binomials) -> Result> { + let ((nu, nv), (du, dv)) = (n.p.degrees(), d.p.degrees()); + let (u, v) = (nu.max(du), nv.max(dv)); + let (n, d) = (n.elevate(u, v, bi)?, d.elevate(u, v, bi)?); + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for (&a, &b) in n.p.coefficients().iter().zip(d.p.coefficients()) { + let (b_lo, b_hi) = (b - d.e, b + d.e); + if !(b_lo > 0.0 && b_hi.is_finite()) { + return Ok(None); + } + let (a_lo, a_hi) = (a - n.e, a + n.e); + // (`min`/`max` drop a NaN: a coefficient that is not finite proves nothing) + if !(a_lo.is_finite() && a_hi.is_finite()) { + return Ok(None); + } + let q_lo = if a_lo >= 0.0 { + a_lo / b_hi + } else { + a_lo / b_lo + }; + let q_hi = if a_hi >= 0.0 { + a_hi / b_lo + } else { + a_hi / b_hi + }; + lo = lo.min(q_lo - gamma(1) * q_lo.abs()); + hi = hi.max(q_hi + gamma(1) * q_hi.abs()); + } + Ok((lo.is_finite() && hi.is_finite()).then_some((lo, hi))) +} + +impl BallFamily { + /// The family through `nodes` (distinct skin parameters, increasing), about the span + /// `span` whose middle ball is at `t_m`, over the nodes' range; `None` for fewer than + /// three nodes, nodes not finite or not increasing, or a span the range does not hold. + pub(super) fn through(nodes: &[Ball], t_m: f64, span: [f64; 2]) -> Option { + let [a, b] = span; + let h = b - a; + let finite = nodes.iter().all(|q| { + q.c.x.is_finite() + && q.c.y.is_finite() + && q.c.z.is_finite() + && q.r.is_finite() + && q.at.is_finite() + }); + let increasing = nodes.windows(2).all(|w| match w { + [p, q] => p.at < q.at, + _ => true, + }); + let middle = nodes.iter().find(|q| q.at == t_m)?; + let (first, last) = (nodes.first()?, nodes.last()?); + if !(nodes.len() >= 3 + && finite + && increasing + && h > 0.0 + && h.is_finite() + && first.at <= a + && b <= last.at) + { + return None; + } + let o = middle.c; + // the family's parameter: the centres' chord length, so that the centre moves at + // about one speed and F is convex in it (the skin's parameter runs unevenly along + // the centres); the skin's parameter where the centres do not move apart + let mut sigma = Vec::with_capacity(nodes.len()); + let mut run = 0.0; + for (i, q) in nodes.iter().enumerate() { + if let Some(p) = i.checked_sub(1).and_then(|p| nodes.get(p)) { + run += (q.c - p.c).length(); + } + sigma.push(run); + } + let at_of = |t: f64| { + nodes + .iter() + .zip(&sigma) + .find(|(q, _)| q.at == t) + .map(|(_, s)| *s) + }; + let (sa, sb, sm) = ( + interpolate(nodes, &sigma, a), + interpolate(nodes, &sigma, b), + at_of(t_m)?, + ); + let chord = sb - sa; + let by_chord = chord > EFF_ZERO * (1.0 + run) + && sigma.windows(2).all(|w| match w { + [p, q] => p < q, + _ => true, + }); + let tau_of: Vec = if by_chord { + sigma.iter().map(|s| (s - sm) / chord).collect() + } else { + nodes.iter().map(|q| (q.at - t_m) / h).collect() + }; + let fit = |pick: &dyn Fn(&Ball) -> f64| { + let data: Vec<(f64, f64, Option)> = nodes + .iter() + .zip(&tau_of) + .map(|(q, t)| (*t, pick(q), None)) + .collect(); + hermite(&data) + }; + let c = [ + fit(&|q| q.c.x - o.x), + fit(&|q| q.c.y - o.y), + fit(&|q| q.c.z - o.z), + ]; + // (the balls' radius is |r|: where it runs through zero between the nodes, the + // signs that make the radii's divided differences smoothest give the smooth law) + let signs = smooth_signs(nodes); + let signed: Vec<(f64, f64, Option)> = nodes + .iter() + .zip(&signs) + .zip(&tau_of) + .map(|((q, s), t)| (*t, s * q.r, None)) + .collect(); + let r = hermite(&signed); + let coefficients_finite = c.iter().chain([&r]).flatten().all(|g| g.is_finite()); + let (Some(&lo), Some(&hi)) = (tau_of.first(), tau_of.last()) else { + return None; + }; + // (every `clamp(lo, hi)` below relies on this: neither NaN nor crossed) + if !above(hi, lo) { + return None; + } + coefficients_finite.then_some(Self { + origin: o, + knots: nodes + .iter() + .map(|q| q.at) + .zip(tau_of.iter().copied()) + .collect(), + c, + r, + range: [lo, hi], + }) + } + + /// The range `[m, M]` of `F_tautau = 2 |c'|^2 - 2 (x - c).c'' - 2 r'^2 - 2 r r''` over + /// `tau` in `[lo, hi]` and the box of points `[box_lo, box_hi]` (about the origin), on + /// [`F2_CELLS`] cells of the range: on each, the part of `tau` alone as one Bernstein + /// polynomial with its error, and `(x - c).c''` by intervals, widened for their rounding. + /// `(-inf, inf)` where a range is not finite. + fn second_derivative( + &self, + [lo, hi]: [f64; 2], + box_lo: [f64; 3], + box_hi: [f64; 3], + bi: &Binomials, + ) -> Result<(f64, f64)> { + let (mut m, mut big_m) = (f64::INFINITY, f64::NEG_INFINITY); + let unknown = Ok((f64::NEG_INFINITY, f64::INFINITY)); + #[allow(clippy::cast_precision_loss)] + let cells = F2_CELLS as f64; + for i in 0..F2_CELLS { + #[allow(clippy::cast_precision_loss)] + let (a, b) = ( + lo + (hi - lo) * (i as f64 / cells), + // (the last cell ends at `hi` itself, not a rounding short of it) + if i + 1 == F2_CELLS { + hi + } else { + lo + (hi - lo) * ((i + 1) as f64 / cells) + }, + ); + let tau = Poly { + p: Bernstein2::new(1, 0, vec![a, b])?, + e: 0.0, + }; + let dr = deriv(&self.r); + let r = mono_of(&self.r, &tau, bi)?; + let rs = mono_of(&dr, &tau, bi)?; + let rss = mono_of(&deriv(&dr), &tau, bi)?; + let mut g = rs.mul(&rs, bi)?.add_scaled(&r.mul(&rss, bi)?, 1.0, bi)?; + g = Poly { + p: g.p.scale(-2.0), + e: 2.0 * g.e, + }; + let (mut dot_lo, mut dot_hi, mut mag) = (0.0_f64, 0.0_f64, 0.0_f64); + for ((c, xl), xh) in self.c.iter().zip(box_lo).zip(box_hi) { + let d = deriv(c); + let cs = mono_of(&d, &tau, bi)?; + g = g.add_scaled(&cs.mul(&cs, bi)?, 2.0, bi)?; + let (Some((cl, ch)), Some(curve)) = + (mono_range(c, a, b, bi)?, mono_range(&deriv(&d), a, b, bi)?) + else { + return unknown; + }; + let off = product_range((xl - ch, xh - cl), curve); + dot_lo += off.0; + dot_hi += off.1; + mag += off.0.abs().max(off.1.abs()); + } + let slack = gamma(8) * 2.0 * (mag + g.largest()); + m = m.min(g.lo() - 2.0 * dot_hi - slack); + big_m = big_m.max(g.hi() - 2.0 * dot_lo + slack); + } + if m.is_nan() || big_m.is_nan() { + return unknown; + } + Ok((m, big_m)) + } + + /// Whether the family's radius comes within `bound` of zero over the piece (by the start + /// of its correspondence): it only steers how the piece is cut. + fn radius_vanishes_on(&self, piece: &Piece, bound: f64, bi: &Binomials) -> Result { + let [lo, hi] = self.range; + let [u0, u1, _, _] = piece.uv; + let (a, b) = ( + self.start_at(u0).clamp(lo, hi), + self.start_at(u1).clamp(lo, hi), + ); + Ok(mono_range(&self.r, a.min(b), a.max(b), bi)? + .is_some_and(|range| !above(least_size(range), bound))) + } + + /// The family parameter the correspondence starts from at the skin parameter `u`. + fn start_at(&self, u: f64) -> f64 { + linear_through(&self.knots, u) + } + + /// The family's parameter nearest the point `p` (about the origin) by `F`: Newton's + /// method on `F_tau = 0` from `start`, kept inside the range; `start` where it does not + /// settle. It only chooses the correspondence, which the bounds do not trust. + fn nearest(&self, p: [f64; 3], start: f64) -> f64 { + let [lo, hi] = self.range; + let dc: Vec = self.c.iter().map(|g| deriv(g)).collect(); + let ddc: Vec = dc.iter().map(|g| deriv(g)).collect(); + let (dr, ddr) = (deriv(&self.r), deriv(&deriv(&self.r))); + let mut t = start; + for _ in 0..12 { + let (mut f1, mut f2) = (0.0, 0.0); + for (((g, d), dd), x) in self.c.iter().zip(&dc).zip(&ddc).zip(p) { + let off = x - eval(g, t); + let slope = eval(d, t); + f1 -= 2.0 * off * slope; + f2 += 2.0 * (slope * slope - off * eval(dd, t)); + } + let (r, rs, rss) = (eval(&self.r, t), eval(&dr, t), eval(&ddr, t)); + f1 -= 2.0 * r * rs; + f2 -= 2.0 * (rs * rs + r * rss); + let next = (t - f1 / f2).clamp(lo, hi); + if !next.is_finite() || !above(f2, 0.0) { + return start; + } + t = next; + } + t + } + + /// The bound of `|phi|` over one piece of the skin (module docs); infinite where it is + /// not proved (a second derivative not proved positive, weights not proved positive, a + /// radius not proved positive where it is used, or a value that is not finite). + #[allow(clippy::too_many_lines)] + fn piece_bound(&self, piece: &Piece, bi: &Binomials) -> Result { + let [lo, hi] = self.range; + let [x, y, z, w] = &piece.h; + // the correspondence: bilinear in the piece's parameters through each corner's + // nearest ball of the family (found by Newton's method, which only steers: any + // correspondence inside the range serves, the bounds hold for every tau in it) + let [u0, u1, _, _] = piece.uv; + let corner_u = [u0, u0, u1, u1]; + let mut corners = [0.0; 4]; + let (du, dv) = w.degrees(); + let at = |p: &Bernstein2, i: usize, j: usize| { + p.coefficients() + .get(i * (dv + 1) + j) + .copied() + .unwrap_or(f64::NAN) + }; + for ((slot, (i, j)), u) in corners + .iter_mut() + .zip([(0, 0), (0, dv), (du, 0), (du, dv)]) + .zip(corner_u) + { + let wc = at(w, i, j); + let p = [at(x, i, j) / wc, at(y, i, j) / wc, at(z, i, j) / wc]; + *slot = self.nearest(p, self.start_at(u).clamp(lo, hi)); + } + let [t00, t01, t10, t11] = corners; + let tau = Poly { + p: Bernstein2::new(1, 1, vec![t00, t01, t10, t11])?, + e: 0.0, + }; + let (tau0, tau1) = ( + corners.iter().copied().fold(f64::INFINITY, f64::min), + corners.iter().copied().fold(f64::NEG_INFINITY, f64::max), + ); + let homog = |p: &Bernstein2| Poly { + p: p.clone(), + e: piece.err, + }; + let (xs, w) = ([homog(x), homog(y), homog(z)], homog(w)); + if !(w.lo() > 0.0 && w.hi().is_finite()) { + return Ok(f64::INFINITY); + } + + // F W^2 and F_tau W^2 along the piece + let [cx, cy, cz] = &self.c; + let (dcx, dcy, dcz) = (deriv(cx), deriv(cy), deriv(cz)); + let cs = [ + mono_of(cx, &tau, bi)?, + mono_of(cy, &tau, bi)?, + mono_of(cz, &tau, bi)?, + ]; + let ds = [ + mono_of(&dcx, &tau, bi)?, + mono_of(&dcy, &tau, bi)?, + mono_of(&dcz, &tau, bi)?, + ]; + let rr = mono_of(&self.r, &tau, bi)?; + let dr = mono_of(&deriv(&self.r), &tau, bi)?; + // (scaling by -1 and -2 is exact) + let r2 = rr.mul(&rr, bi)?; + let mut q = Poly { + p: r2.p.scale(-1.0), + e: r2.e, + }; + let rdr = rr.mul(&dr, bi)?; + let mut dq = Poly { + p: rdr.p.scale(-2.0), + e: 2.0 * rdr.e, + }; + let mut a = Poly { + p: Bernstein2::constant(0.0), + e: 0.0, + }; + let mut wx_c = a.clone(); + let mut wx_d = a.clone(); + for ((xk, ck), dk) in xs.iter().zip(&cs).zip(&ds) { + a = a.add_scaled(&xk.mul(xk, bi)?, 1.0, bi)?; + q = q.add_scaled(&ck.mul(ck, bi)?, 1.0, bi)?; + dq = dq.add_scaled(&ck.mul(dk, bi)?, 2.0, bi)?; + let b = w.mul(xk, bi)?; + wx_c = wx_c.add_scaled(&b.mul(ck, bi)?, 1.0, bi)?; + wx_d = wx_d.add_scaled(&b.mul(dk, bi)?, 1.0, bi)?; + } + let c2 = w.mul(&w, bi)?; + let fw = a + .add_scaled(&wx_c, -2.0, bi)? + .add_scaled(&c2.mul(&q, bi)?, 1.0, bi)?; + let ftw = c2.mul(&dq, bi)?.add_scaled(&wx_d, -2.0, bi)?; + + // F and |F_tau| at the correspondence + let w4 = c2.mul(&c2, bi)?; + let (Some((f_lo, f_hi)), Some((ft_lo, ft_hi))) = ( + quotient_range(&fw, &c2, bi)?, + quotient_range(&ftw, &c2, bi)?, + ) else { + return Ok(f64::INFINITY); + }; + let ft_abs = ft_lo.abs().max(ft_hi.abs()); + let f_abs = f_lo.abs().max(f_hi.abs()); + + // F_tautau over the range and the piece's box of points: `G = 2 |c'|^2 - 2 r'^2 - + // 2 r r''` (of tau alone) as one Bernstein polynomial and `2 (x - c).c''` as an + // interval, on each of `F2_CELLS` cells of the range + let (box_lo, box_hi) = piece.widened_box()?; + let (m, big_m) = self.second_derivative([lo, hi], box_lo, box_hi, bi)?; + if !(m > 0.0 && big_m.is_finite()) { + return Ok(f64::INFINITY); + } + + // (F W^2) W^2 - (F_tau W^2)^2 x, for x = 1 / (2 kappa) + let p1 = fw.mul(&c2, bi)?; + let p2 = ftw.mul(&ftw, bi)?; + // (rounded so that the kappa it stands for is at most m, at least M) + let x_lo = (1.0 / (2.0 * m)) * (1.0 + gamma(3)); + let x_hi = (1.0 / (2.0 * big_m)) * (1.0 - gamma(3)); + let n_lo = p1.add_scaled(&p2, -x_lo, bi)?; + let n_hi = p1.add_scaled(&p2, -x_hi, bi)?; + + // the lower side: min over the range of F, then of psi + let Some((g_lo, _)) = quotient_range(&n_lo, &w4, bi)? else { + return Ok(f64::INFINITY); + }; + let phi_lo = if g_lo >= 0.0 { + 0.0 + } else { + // (where F can be negative: within reach of the correspondence) + let reach = + (ft_abs + (ft_abs * ft_abs + 2.0 * m * f_abs).sqrt()) / m * (1.0 + gamma(8)); + let span = ((tau0 - reach).max(lo), (tau1 + reach).min(hi)); + let r_lo = mono_range(&self.r, span.0, span.1, bi)?.map_or(f64::NAN, least_size); + // psi = sqrt(r^2 + F) - r rises with F and, for F < 0, with r + let d = r_lo * r_lo + g_lo; + if d >= 0.0 { + g_lo / (d.sqrt() + r_lo) + } else { + -(-g_lo).sqrt() + } + }; + + // the upper side: F at the correspondence, or at the Taylor step where it fits + let step = ft_abs / big_m * (1.0 + gamma(4)); + let fits = tau0 - step >= lo && tau1 + step <= hi; + let (f_up, r_span) = if fits { + let Some((_, g_hi)) = quotient_range(&n_hi, &w4, bi)? else { + return Ok(f64::INFINITY); + }; + (f_hi.min(g_hi), (tau0 - step, tau1 + step)) + } else { + (f_hi, (tau0, tau1)) + }; + let phi_hi = if f_up <= 0.0 { + 0.0 + } else { + let r_lo = mono_range(&self.r, r_span.0, r_span.1, bi)?.map_or(f64::NAN, least_size); + // psi = sqrt(r^2 + F) - r rises with F and, for F > 0, falls with r + let by_root = f_up / ((r_lo * r_lo + f_up).sqrt() + r_lo); + // and at the correspondence, psi = F / (rho + r) <= F / (2 r) where F >= 0 (so + // rho >= r), psi < 0 elsewhere: max(F / (2 r), 0) bounds it, as a quotient of + // polynomials where r is proved positive (where the radius runs to zero) + let den = rr.mul(&c2, bi)?; + let den = Poly { + p: den.p.scale(2.0), + e: 2.0 * den.e, + }; + // (each candidate is a bound by itself; one that is NaN proves nothing, and + // `min` must not let it stand in for the other) + let by_root = not_proved(by_root); + match quotient_range(&fw, &den, bi)? { + Some((_, q)) => by_root.min(not_proved(q.max(0.0))), + None => by_root, + } + }; + + Ok(combine(phi_lo, phi_hi)) + } +} + +/// `x`, or infinity for a NaN (a bound that is not proved). +fn not_proved(x: f64) -> f64 { + if x.is_nan() { + f64::INFINITY + } else { + x + } +} + +/// The bound of `|phi|` from its lower side `phi_lo` and upper side `phi_hi`, widened for +/// the final quotients and roots: infinite where either side is NaN or infinite (`f64::max` +/// would drop a NaN side and bound the piece by the other alone). +fn combine(phi_lo: f64, phi_hi: f64) -> f64 { + let bound = not_proved(-phi_lo).max(not_proved(phi_hi)).max(0.0) * (1.0 + gamma(8)); + if bound.is_finite() { + bound + } else { + f64::INFINITY + } +} + +/// The proved bound of `|phi|` (module docs) over the skin `skin` on the rectangle `u` x `v` +/// of its parameters, against the family `family`: every piece is bounded, and a piece over +/// `tol` is quartered while fewer than [`MAX_PIECES`] are made; the largest bound over the +/// pieces left. Infinite where a piece is not proved, or the skin has no Bรฉzier pieces with +/// positive weights. +/// +/// # Errors +/// +/// A cancellation; those of the pieces' construction other than their being unsupported. +pub(super) fn span_bound( + k: &Kernel, + skin: &Surface, + family: &BallFamily, + u: [f64; 2], + v: [f64; 2], + tol: f64, + bi: &Binomials, +) -> Result { + let [u0, u1] = u; + let [v0, v1] = v; + let rect = Extent2d::from_bounds(u0, v0, u1, v1); + let (mut work, slack) = match pieces_about(k, skin, Some(&rect), family.origin) { + Ok(found) => found, + Err(SolidError::Unsupported { .. }) => return Ok(f64::INFINITY), + Err(e) => return Err(e), + }; + if work.is_empty() { + return Ok(f64::INFINITY); + } + let mut made = work.len(); + let mut worst = 0.0_f64; + while let Some(piece) = work.pop() { + k.check_cancelled(OP)?; + let bound = match family.piece_bound(&piece, bi) { + Ok(b) => b, + Err(SolidError::Unsupported { .. }) => f64::INFINITY, + Err(e) => return Err(e), + }; + if bound <= tol || made + 4 > MAX_PIECES { + // (NaN is not below anything: an unproved piece counts as infinite) + worst = if bound <= f64::MAX { + worst.max(bound) + } else { + f64::INFINITY + }; + continue; + } + // (where the radius runs to zero on the piece the skin closes to a point along its + // v, and only its length in u brings the bound down: halved in u; else quartered) + if family.radius_vanishes_on(&piece, bound, bi)? { + made += 2; + work.extend(halves_in_u(&piece)); + } else { + made += 4; + work.extend(piece.quarters()?); + } + } + Ok(worst + slack) +} + +/// The two halves of a piece in its first parameter (de Casteljau at one half), each with the +/// error of one split level, as [`Piece::quarters`] charges it. +fn halves_in_u(piece: &Piece) -> [Piece; 2] { + let largest = piece + .h + .iter() + .map(Bernstein2::max_abs_coefficient) + .fold(0.0_f64, f64::max); + let [x, y, z, w] = &piece.h; + let (du, dv) = w.degrees(); + let err = piece.err + gamma(2 * (du + dv) + 4) * (largest + piece.err); + let ((xl, xr), (yl, yr), (zl, zr), (wl, wr)) = ( + x.split_u(0.5), + y.split_u(0.5), + z.split_u(0.5), + w.split_u(0.5), + ); + let [u0, u1, v0, v1] = piece.uv; + let um = 0.5 * (u0 + u1); + let half = |h: [Bernstein2; 4], uv: [f64; 4]| Piece { + h, + err, + lower: 0.0, + depth: piece.depth + 1, + uv, + }; + [ + half([xl, yl, zl, wl], [u0, um, v0, v1]), + half([xr, yr, zr, wr], [um, u1, v0, v1]), + ] +} + +#[cfg(test)] +pub(super) mod tests { + use super::*; + use crate::nurbs::b_spline_curve::KnotType; + use crate::nurbs::b_spline_surface::{ + BSplineSurface, BSplineSurfaceForm, CanonicalSurfaceData, + }; + + /// A quarter of the tube about the x axis from `x = 0` to `x = 1`, over `u` in [0, 1] + /// along x and `v` in [0, 1] from `(x, 0, rho)` to `(x, rho, 0)`, whose distance from the + /// axis is `rho(u) = r0 + bump u (u - 1/2) (u - 1)`, in exact rational form: on balls of + /// radius `r0` along the axis at `u = 0`, `1/2` and `1`, off them in between, most + /// (`bump / (12 sqrt 3)`) at `u = 1/2 -+ 1/(2 sqrt 3)`. + pub(in crate::blend) fn bulged_tube(r0: f64, bump: f64) -> Surface { + // u (u - 1/2) (u - 1) in cubic Bernstein form: 0, 1/6, -1/6, 0 + let rho = [r0, r0 + bump / 6.0, r0 - bump / 6.0, r0]; + let xs = [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]; + let mut points = Vec::new(); + let mut weights = Vec::new(); + for (x, r) in xs.into_iter().zip(rho) { + for (p, w) in [ + (Point3::new(x, 0.0, r), 1.0), + (Point3::new(x, r, r), core::f64::consts::FRAC_1_SQRT_2), + (Point3::new(x, r, 0.0), 1.0), + ] { + points.push(p); + weights.push(w); + } + } + Surface::from( + BSplineSurface::create_canonical(&CanonicalSurfaceData { + u_degree: 3, + v_degree: 2, + control_points: &points, + form: BSplineSurfaceForm::Unspecified, + u_multiplicities: &[4, 4], + v_multiplicities: &[3, 3], + u_knots: &[0.0, 1.0], + v_knots: &[0.0, 1.0], + knot_type: KnotType::Unspecified, + weights: Some(&weights), + uv_domain: None, + }) + .unwrap(), + ) + } + + fn ball(x: f64, r: f64) -> Ball { + Ball { + c: Point3::new(x, 0.0, 0.0), + r, + at: x, + } + } + + /// The family through balls of radius `r(x)` at `xs`, about the span `[0, 1]`. + fn family(xs: &[f64], r: impl Fn(f64) -> f64) -> BallFamily { + let nodes: Vec = xs.iter().map(|&x| ball(x, r(x))).collect(); + BallFamily::through(&nodes, 0.5, [0.0, 1.0]).unwrap() + } + + fn bound_of(skin: &Surface, family: &BallFamily, tol: f64) -> f64 { + let k = &Kernel::default(); + span_bound( + k, + skin, + family, + [0.0, 1.0], + [0.0, 1.0], + tol, + &Binomials::new(), + ) + .unwrap() + } + + /// A tube of radius `r0 + delta` about balls of radius `r0` is `delta` outside their + /// envelope everywhere (closed form); one of `r0 - delta`, `delta` inside. The bound + /// holds and is tight. + #[test] + fn the_bound_of_a_tube_off_its_balls_is_its_offset() { + let r0 = 2.0; + let family = family(&[0.0, 0.5, 1.0], |_| r0); + for delta in [3e-5, -3e-5, 1e-3, -1e-3] { + let skin = bulged_tube(r0 + delta, 0.0); + let b = bound_of(&skin, &family, 4e-5); + assert!(b >= delta.abs(), "{delta}: {b}"); + assert!(b <= delta.abs() * (1.0 + 1e-6) + 1e-12, "{delta}: {b}"); + } + // on its balls: only rounding + let b = bound_of(&bulged_tube(r0, 0.0), &family, 4e-5); + assert!(b < 1e-12, "{b}"); + } + + /// A tube bulged between the three balls it passes through: the bound holds over the + /// whole span against the closed form `|rho(u) - r0|` (largest `bump / (12 sqrt 3)`), + /// and is tight enough to tell a bulge under the tolerance from one over it. + #[test] + fn the_bound_of_a_bulge_between_the_balls_covers_its_peak() { + let r0 = 2.0; + let family = family(&[-0.25, 0.0, 0.5, 1.0, 1.25], |_| r0); + let peak = |bump: f64| bump.abs() / (12.0 * 3.0_f64.sqrt()); + for bump in [1e-4, -1e-4, 2e-3, 0.1] { + let b = bound_of(&bulged_tube(r0, bump), &family, 4e-5); + assert!(b >= peak(bump), "{bump}: {b} < {}", peak(bump)); + // (pieces are quartered only while over the tolerance) + assert!( + b <= (1.5 * peak(bump)).max(4e-5), + "{bump}: {b} vs {}", + peak(bump) + ); + } + } + + /// Balls whose radius outruns their centres (`|r'| >= |c'|`) have no envelope: the + /// family's second derivative is not positive, and nothing is proved. + #[test] + fn nesting_balls_prove_nothing() { + let family = family(&[0.0, 0.5, 1.0], |x| 1.0 + 2.0 * x); + assert_eq!( + bound_of(&bulged_tube(2.0, 0.0), &family, 4e-5), + f64::INFINITY + ); + } + + /// A side that is NaN proves nothing: the piece's bound is infinite, not the other + /// side's alone (`f64::max` drops a NaN). + #[test] + fn a_side_that_is_nan_leaves_the_piece_unproved() { + assert_eq!(combine(-1e-6, f64::NAN), f64::INFINITY); + assert_eq!(combine(f64::NAN, 1e-6), f64::INFINITY); + assert_eq!(combine(f64::NEG_INFINITY, 0.0), f64::INFINITY); + let b = combine(-1e-6, 2e-6); + assert!((2e-6..=2e-6 * (1.0 + 1e-12)).contains(&b), "{b}"); + } + + /// A coefficient that is not finite proves nothing: no range (`min`/`max` would drop a + /// NaN quotient and range the others alone). + #[test] + fn a_quotient_with_a_coefficient_that_is_not_finite_has_no_range() { + let bi = &Binomials::new(); + let poly = |c: Vec| Poly { + p: Bernstein2::new(1, 0, c).unwrap(), + e: 0.0, + }; + let ones = poly(vec![1.0, 1.0]); + assert!(quotient_range(&poly(vec![1.0, 2.0]), &ones, bi) + .unwrap() + .is_some()); + for bad in [f64::NAN, f64::INFINITY] { + assert!(quotient_range(&poly(vec![1.0, bad]), &ones, bi) + .unwrap() + .is_none()); + } + } + + #[test] + fn a_family_needs_three_finite_balls_in_increasing_parameter_over_its_span() { + let through = |nodes: &[Ball]| BallFamily::through(nodes, 0.5, [0.0, 1.0]); + assert!(through(&[ball(0.0, 1.0), ball(0.5, 1.0), ball(1.0, 1.0)]).is_some()); + assert!(through(&[ball(0.0, 1.0), ball(1.0, 1.0), ball(0.5, 1.0)]).is_none()); + assert!(through(&[ball(0.0, 1.0), ball(0.5, f64::NAN), ball(1.0, 1.0)]).is_none()); + assert!(through(&[ball(0.0, 1.0), ball(0.5, 1.0)]).is_none()); + assert!(through(&[ball(0.0, 1.0), ball(0.5, 1.0), ball(0.9, 1.0)]).is_none()); + } +} diff --git a/solidcore/crates/solidcore/src/blend/fillet_solver/p1.rs b/solidcore/crates/solidcore/src/blend/fillet_solver/p1.rs index 180d9cb73e0..9803e375d9c 100644 --- a/solidcore/crates/solidcore/src/blend/fillet_solver/p1.rs +++ b/solidcore/crates/solidcore/src/blend/fillet_solver/p1.rs @@ -215,6 +215,17 @@ pub enum FilletSolverType { ConstRadiusAssisted = 6, } +impl FilletSolverType { + /// Whether the solver's ball changes its radius along the round (a radius law, or a + /// constant chord between faces whose angle changes), so a circular section is the + /// circle along which the balls' envelope touches the ball rather than its great + /// circle (the fork's `SmGnSectionFSG::CircleSurface`, WR-685, f2ec002). + #[must_use] + pub const fn ball_radius_varies(self) -> bool { + matches!(self, Self::VariableRadius | Self::ConstDist) + } +} + /// `SmFilletSurfaceGeneratorType`; discriminants are the upstream values. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum FilletSurfaceGeneratorType { @@ -3521,6 +3532,26 @@ pub use rails::{compute_support_edge, split_rail, RailOwnership, RetainedRailOwn mod tests { use super::*; + /// The solvers whose ball changes its radius along the round, so that + /// `skins_varying_balls` holds their exact-circle skin to its balls (#15256): a + /// variable radius and a constant distance (its radius follows the faces' angle), + /// not a constant radius or the constant-radius-assisted solver. + #[test] + fn variable_radius_and_constant_distance_balls_vary() { + use FilletSolverType as T; + assert!(T::VariableRadius.ball_radius_varies()); + assert!(T::ConstDist.ball_radius_varies()); + for t in [ + T::Unknown, + T::SurfSurf, + T::ConstRadius, + T::CurveBased, + T::ConstRadiusAssisted, + ] { + assert!(!t.ball_radius_varies(), "{t:?}"); + } + } + #[test] fn audit_483_edge_domain_is_no_trimmed_curve_after_a_failed_trim() { let k = Kernel::default(); diff --git a/solidcore/crates/solidcore/src/blend/fillet_solver/p4.rs b/solidcore/crates/solidcore/src/blend/fillet_solver/p4.rs index 2a677839ef6..af121e4be53 100644 --- a/solidcore/crates/solidcore/src/blend/fillet_solver/p4.rs +++ b/solidcore/crates/solidcore/src/blend/fillet_solver/p4.rs @@ -4808,7 +4808,10 @@ impl crate::blend::fillet_intersector::FilletSolverOps for IntersectorSolver<'_> points: &[TsectPnt], uv1: &mut BSplineCurve, uv2: &mut BSplineCurve, - ) -> Result> { + ) -> Result<( + Option, + Option, + )> { // the virtual m_pFSG->CreateSurface(*this, pCenterLine, pCurve1, pCurve2, // sPnts, pSur[0], pUV1, pSur[1], pUV2, ..) with pSur[i] = GetSurface(i) let solver_type = self.ops.solver_type()?; @@ -4872,11 +4875,27 @@ impl crate::blend::fillet_intersector::FilletSolverOps for IntersectorSolver<'_> [uv1, uv2], Some(&ball), )?; + // (the fork's `rFilletSolver.AddLawCornerPieces`, 7babe17, is `FlushCurve`'s, once + // its stations are final: `keep_law_corner_pieces`) + Ok((Some(surface), kept)) + } + + fn keep_law_corner_pieces( + &mut self, + pieces: crate::blend::law_corners::LawCornerPieces, + ) -> Result<()> { // the fork's `rFilletSolver.AddLawCornerPieces` (7babe17) - if let Some(kept) = kept { - self.ops.solver_mut().law_corner_pieces.push(kept); - } - Ok(Some(surface)) + self.ops.solver_mut().law_corner_pieces.push(pieces); + Ok(()) + } + + fn skins_varying_balls(&self) -> Result { + let exact_circles = matches!( + self.ops.solver().fillet_surface_generator(), + Some(crate::blend::fillet_solver::p1::FilletSurfaceGenerator::Circular(g)) + if !g.approximate_arcs && !g.mirror + ); + Ok(exact_circles && self.ops.solver_type()?.ball_radius_varies()) } fn set_fillet_surface( diff --git a/solidcore/crates/solidcore/src/blend/fillet_standard_solver/p2.rs b/solidcore/crates/solidcore/src/blend/fillet_standard_solver/p2.rs index 5d9b6e6b541..2142f414cec 100644 --- a/solidcore/crates/solidcore/src/blend/fillet_standard_solver/p2.rs +++ b/solidcore/crates/solidcore/src/blend/fillet_standard_solver/p2.rs @@ -2551,10 +2551,7 @@ impl CircularCrossSectionFsg { // ball changes its radius along the round (a radius law, or a constant chord // between faces whose angle changes); the others' balls touch the round along // their great circles. - let ball_radius_varies = matches!( - solver_type, - FilletSolverType::VariableRadius | FilletSolverType::ConstDist - ); + let ball_radius_varies = solver_type.ball_radius_varies(); // the centre line is a plain SmBSplineCurve here, so its virtuals are the // B-spline ones let mut cl = Curve::from(core::mem::take(center_line)); diff --git a/solidcore/crates/solidcore/src/error/blend.rs b/solidcore/crates/solidcore/src/error/blend.rs index 4bcc5b88636..4f55dcb7688 100644 --- a/solidcore/crates/solidcore/src/error/blend.rs +++ b/solidcore/crates/solidcore/src/error/blend.rs @@ -17,7 +17,9 @@ //! | [`BlendFailure::NoRoom`] | the reason's ([`no_room_class`]), 101 to 124 or 128 | //! | [`BlendFailure::StationDidNotConverge`]| [`ErrorKind::StationDidNotConverge`] (125) | //! | [`BlendFailure::TrimLoopOpen`], [`BlendFailure::TrimLoopDoesNotSeparate`] | [`ErrorKind::TrimLeaks`] (126) | -//! | [`BlendFailure::StageFailed`] | [`ErrorKind::StageFailed`] (127) | +//! | [`BlendFailure::StageFailed`], [`BlendFailure::SkinMeasureNotFinite`] | [`ErrorKind::StageFailed`] (127) | +//! | [`BlendFailure::SkinPastStationCap`] | [`ErrorKind::NotWithinTolerance`] (9) | +//! | [`BlendFailure::BallsNest`] | [`ErrorKind::BallsFold`] (105) | //! | the phrase causes ([`BlendFailure::Failed`], [`BlendFailure::Missing`], ...) | their status's kind, as before the record; neither defect nor refusal | //! //! **Statuses.** Each failure also records, for difftest and the goldens only, the status @@ -27,7 +29,7 @@ //! //! | Rust | Status difftest compares | //! |----------------------------------------|-----------------------------------| -//! | [`BlendFailure::NoRoom`], [`BlendFailure::StationDidNotConverge`], [`BlendFailure::TrimLoopOpen`], [`BlendFailure::TrimLoopDoesNotSeparate`], [`BlendFailure::StageFailed`] | `SM_ERR` | +//! | [`BlendFailure::NoRoom`], [`BlendFailure::StationDidNotConverge`], [`BlendFailure::TrimLoopOpen`], [`BlendFailure::TrimLoopDoesNotSeparate`], [`BlendFailure::StageFailed`], [`BlendFailure::SkinPastStationCap`], [`BlendFailure::SkinMeasureNotFinite`], [`BlendFailure::BallsNest`] | `SM_ERR` | //! | [`BlendFailure::Failed`] | `SM_ERR` | //! | [`BlendFailure::Missing`] | `SM_ERR_NULL_POINTER` | //! | [`BlendFailure::InvalidValue`] | `SM_ERR_INVALID_INPUT` | @@ -77,14 +79,14 @@ pub enum BlendFailure { StationDidNotConverge { /// The station: the blend's parameter along its spine. s: f64, - /// The residual the solve stopped at. - residual: f64, + /// The residual the solve stopped at (`None` where the solve does not report it). + residual: Option, /// The tolerance it had to reach. tolerance: f64, - /// The last step it took. - step: f64, - /// The iterations it took. - iterations: u32, + /// The last step it took (`None` where the solve does not report it). + step: Option, + /// The iterations it took (`None` where the solve does not report them). + iterations: Option, }, /// The boundary loop of the faces the rails enclose is open: the failure's site vertex /// is where. A defect ([`ErrorKind::TrimLeaks`]). @@ -96,6 +98,43 @@ pub enum BlendFailure { /// holds the operation, the status (for the goldens only) and where in solidcore's source /// it was built ([`Failure::origin`]). StageFailed, + /// A variable round's skin of balls' touch circles was still measured farther than + /// `asked` from its balls when its refinement reached its most rounds or stations + /// (#15256): the worst distance measured was `reached` (infinite where a span's section + /// could not be placed on the skin to be measured), with `stations` stations after + /// `rounds` rounds. Not within the tolerance ([`ErrorKind::NotWithinTolerance`]): no + /// tolerance is loosened and the skin is not kept. + SkinPastStationCap { + /// The tolerance asked: the solver's approximation tolerance. + asked: f64, + /// The largest distance measured from the skin to its balls at the cap. + reached: f64, + /// The stations the skin had at the cap. + stations: usize, + /// The refinement rounds run. + rounds: usize, + }, + /// A quantity a variable round's skin check computes (a distance from the skin to its + /// balls, or the balls' radius rate and centre speed at a section) was still not a finite + /// number, last at the section at `s` along the trace, when the refinement reached its + /// most rounds or stations (#15256): a defect ([`ErrorKind::StageFailed`]). A value that + /// is not finite before the cap splits its span instead. + SkinMeasureNotFinite { + /// The section's parameter along the trace. + s: f64, + }, + /// At the section at `s` along the trace a variable round's balls change their radius at + /// least as fast as their centres move (`|r'| = rate >= |c'| = speed`): each ball holds + /// the next, so no rolling-ball surface exists there (#15256). A refusal + /// ([`ErrorKind::BallsFold`]). + BallsNest { + /// The section's parameter along the trace. + s: f64, + /// `|r'|`: how fast the balls' radius changes along the trace. + rate: f64, + /// `|c'|`: how fast the balls' centres move along the trace. + speed: f64, + }, /// The routine could not continue, as the phrase says (for example "the fillet's law /// has no value at the base"). Upstream `return SE(SM_ERR)`. A phrase cause /// ([`BlendFailure::is_phrase`]). @@ -194,6 +233,9 @@ impl BlendFailure { | Self::TrimLoopOpen | Self::TrimLoopDoesNotSeparate | Self::StageFailed + | Self::SkinPastStationCap { .. } + | Self::SkinMeasureNotFinite { .. } + | Self::BallsNest { .. } | Self::Failed(_) => SM_ERR, Self::Missing(_) => SM_ERR_NULL_POINTER, Self::InvalidValue(_) => SM_ERR_INVALID_INPUT, @@ -209,7 +251,10 @@ impl BlendFailure { /// The failure's class, its stable [`ErrorKind`], derived from the cause: the reason's /// class for [`BlendFailure::NoRoom`] ([`no_room_class`]), /// [`ErrorKind::StationDidNotConverge`], [`ErrorKind::TrimLeaks`] for an open or leaking - /// trim loop, and [`ErrorKind::StageFailed`] for [`BlendFailure::StageFailed`]. A phrase + /// trim loop, [`ErrorKind::StageFailed`] for [`BlendFailure::StageFailed`] and + /// [`BlendFailure::SkinMeasureNotFinite`], [`ErrorKind::NotWithinTolerance`] for + /// [`BlendFailure::SkinPastStationCap`] and [`ErrorKind::BallsFold`] for + /// [`BlendFailure::BallsNest`]. A phrase /// cause keeps the kind of its status ([`ErrorKind::Failed`], [`ErrorKind::Missing`], /// [`ErrorKind::InvalidInput`], ...), as before the record ([`BlendFailure::is_phrase`]). #[must_use] @@ -218,7 +263,9 @@ impl BlendFailure { Self::NoRoom(reason) => no_room_class(*reason), Self::StationDidNotConverge { .. } => ErrorKind::StationDidNotConverge, Self::TrimLoopOpen | Self::TrimLoopDoesNotSeparate => ErrorKind::TrimLeaks, - Self::StageFailed => ErrorKind::StageFailed, + Self::StageFailed | Self::SkinMeasureNotFinite { .. } => ErrorKind::StageFailed, + Self::SkinPastStationCap { .. } => ErrorKind::NotWithinTolerance, + Self::BallsNest { .. } => ErrorKind::BallsFold, Self::Failed(_) | Self::Missing(_) | Self::InvalidValue(_) @@ -243,7 +290,10 @@ impl BlendFailure { | Self::StationDidNotConverge { .. } | Self::TrimLoopOpen | Self::TrimLoopDoesNotSeparate - | Self::StageFailed => false, + | Self::StageFailed + | Self::SkinPastStationCap { .. } + | Self::SkinMeasureNotFinite { .. } + | Self::BallsNest { .. } => false, Self::Failed(_) | Self::Missing(_) | Self::InvalidValue(_) @@ -269,6 +319,9 @@ impl BlendFailure { | Self::TrimLoopOpen | Self::TrimLoopDoesNotSeparate | Self::StageFailed + | Self::SkinPastStationCap { .. } + | Self::SkinMeasureNotFinite { .. } + | Self::BallsNest { .. } | Self::Failed(_) | Self::Missing(_) | Self::InvalidValue(_) @@ -293,16 +346,42 @@ impl core::fmt::Display for BlendFailure { tolerance, step, iterations, - } => write!( - f, - "{}: the station at s = {s} did not converge: residual {residual} > {tolerance} after {iterations} iterations (last step {step})", - self.class() - ), + } => { + let shown = |x: Option| x.unwrap_or_else(|| "unreported".into()); + write!( + f, + "{}: the station at s = {s} did not converge: residual {} > {tolerance} after {} iterations (last step {})", + self.class(), + shown(residual.map(|r| r.to_string())), + shown(iterations.map(|n| n.to_string())), + shown(step.map(|d| d.to_string())), + ) + } Self::TrimLoopOpen => write!(f, "{}: the trim loop is open", self.class()), Self::TrimLoopDoesNotSeparate => { write!(f, "{}: the trim loop does not separate", self.class()) } Self::StageFailed => write!(f, "{}", self.class()), + Self::SkinPastStationCap { + asked, + reached, + stations, + rounds, + } => write!( + f, + "{}: the round's skin is {reached} from its balls, past {asked}, with {stations} stations after {rounds} rounds", + self.class() + ), + Self::SkinMeasureNotFinite { s } => write!( + f, + "{}: the skin check computed a value that is not finite at s = {s}", + self.class() + ), + Self::BallsNest { s, rate, speed } => write!( + f, + "{}: at s = {s} the balls' radius changes at {rate}, as fast as their centres move ({speed}): no rolling-ball surface exists there", + self.class() + ), Self::Failed(what) | Self::InvalidValue(what) | Self::BadIntersections(what) @@ -650,10 +729,10 @@ mod tests { ( BlendFailure::StationDidNotConverge { s: 0.42, - residual: 3e-6, + residual: Some(3e-6), tolerance: 1e-9, - step: 1e-4, - iterations: 50, + step: Some(1e-4), + iterations: Some(50), }, ErrorKind::StationDidNotConverge, ), @@ -711,16 +790,31 @@ mod tests { "blend::op", BlendFailure::StationDidNotConverge { s: 0.42, - residual: 3e-6, + residual: Some(3e-6), tolerance: 1e-9, - step: 0.0001, - iterations: 50, + step: Some(0.0001), + iterations: Some(50), }, ); assert_eq!( station.to_string(), "blend::op: station_did_not_converge: the station at s = 0.42 did not converge: residual 0.000003 > 0.000000001 after 50 iterations (last step 0.0001)" ); + // a solve that reports only whether it converged (#15256's skin check) + let unreported = SolidError::blend( + "blend::op", + BlendFailure::StationDidNotConverge { + s: 0.5, + residual: None, + tolerance: 1e-9, + step: None, + iterations: None, + }, + ); + assert_eq!( + unreported.to_string(), + "blend::op: station_did_not_converge: the station at s = 0.5 did not converge: residual unreported > 0.000000001 after unreported iterations (last step unreported)" + ); assert_eq!( SolidError::blend("blend::op", BlendFailure::NoRoom(R::OverflowWithRollover)) .to_string(), @@ -900,7 +994,10 @@ mod tests { | BlendFailure::StationDidNotConverge { .. } | BlendFailure::TrimLoopOpen | BlendFailure::TrimLoopDoesNotSeparate - | BlendFailure::StageFailed => None, + | BlendFailure::StageFailed + | BlendFailure::SkinPastStationCap { .. } + | BlendFailure::SkinMeasureNotFinite { .. } + | BlendFailure::BallsNest { .. } => None, BlendFailure::Failed(_) => Some("BlendFailure::Failed("), BlendFailure::Missing(_) => Some("BlendFailure::Missing("), BlendFailure::InvalidValue(_) => Some("BlendFailure::InvalidValue("), @@ -926,10 +1023,22 @@ mod tests { BlendFailure::NoRoom(R::BallDoesNotFit), BlendFailure::StationDidNotConverge { s: 0.0, - residual: 0.0, + residual: Some(0.0), tolerance: 0.0, - step: 0.0, - iterations: 0, + step: Some(0.0), + iterations: Some(0), + }, + BlendFailure::SkinPastStationCap { + asked: 0.0, + reached: 0.0, + stations: 0, + rounds: 0, + }, + BlendFailure::SkinMeasureNotFinite { s: 0.0 }, + BlendFailure::BallsNest { + s: 0.0, + rate: 0.0, + speed: 0.0, }, BlendFailure::TrimLoopOpen, BlendFailure::TrimLoopDoesNotSeparate, diff --git a/solidcore/crates/solidcore/tests/fork_ea59e9c_section_orders.rs b/solidcore/crates/solidcore/tests/fork_ea59e9c_section_orders.rs index 15e7cb6d2cc..903aeb0fac1 100644 --- a/solidcore/crates/solidcore/tests/fork_ea59e9c_section_orders.rs +++ b/solidcore/crates/solidcore/tests/fork_ea59e9c_section_orders.rs @@ -1314,6 +1314,293 @@ fn wr711_exact_circles_of_one_arc_count_keep_the_progressive_round_on_its_balls( ); } +/// The largest distance from a variable round's skin to the union of its balls, sampled +/// on a 400 x 33 grid of the round's face where the edge runs (`y` in [2, 18], clear of the +/// ends, where the surface runs on past the balls of `s` in [0, 1]), and the solver's +/// approximation tolerance there (4 x the edge's tolerance, `TOL_FACTOR`). The round's +/// faces and the points measured are counted, so a result with no round, or with every point +/// filtered away, fails rather than measuring nothing. +fn skin_off_balls(law: [f64; 5]) -> (f64, f64) { + let mut k = solidcraft_kernel(); + let mut b = box_10_20_30(&mut k).unwrap(); + let e = pick(&k, &b, [10.0, 10.0, 30.0]); + let tol = 4.0 * edge::tolerance(&b, e).unwrap(); + spline_round(&mut k, &mut b, e, law).unwrap(); + let curve = greville_cubic_curve(law); + let planes = box_planes(10.0, 20.0, 30.0); + let ids: Vec = b.faces().ids().collect(); + let mut off: f64 = 0.0; + let (mut rounds, mut measured) = (0usize, 0usize); + for f in ids { + let srf = face::surface(&b, f).unwrap().unwrap().clone(); + if planes.iter().any(|&q| on_face(&k, &srf, q)) { + continue; + } + rounds += 1; + let dom = face::uv_domain(&b, f).unwrap(); + for a in 0..=400 { + for c in 0..=32 { + let uv = Point2::new( + dom.min().x + (dom.max().x - dom.min().x) * f64::from(a) / 400.0, + dom.min().y + (dom.max().y - dom.min().y) * f64::from(c) / 32.0, + ); + let x = srf.evaluate_point(&k, uv).unwrap(); + if (2.0..=18.0).contains(&x.y) { + off = off.max(distance_to_balls_union(&curve, x)); + measured += 1; + } + } + } + } + // one round face, and the edge's middle 16 of 20 is most of its 401 x 33 grid + assert_eq!(rounds, 1, "law {law:?}: {rounds} round faces"); + assert!( + measured > 401 * 33 / 2, + "law {law:?}: {measured} points measured" + ); + (off, tol) +} + +/// #15256: a variable round's skin, not only its rails, lies within the solver's +/// approximation tolerance of its balls between the trace's stations. Before, the stations +/// were accepted on the rails alone and the skin between them was unbounded: the +/// progressive law 8.7e-5 off (2.2 times the 4e-5 tolerance), `[2, 4, 2, 4, 2]` 4.1e-4 +/// (10.2 times) and `[3, 3, 3, 3, 1]` 3.2e-4 (7.9 times). +#[test] +fn a_variable_round_s_skin_lies_within_its_tolerance_of_its_balls() { + for law in [ + HOLDS_LAW, + [2.0, 2.0, 6.0, 3.0, 1.0], + [1.0, 3.0, 5.0, 3.0, 1.0], + [2.0, 4.0, 2.0, 4.0, 2.0], + [3.0, 3.0, 3.0, 3.0, 1.0], + ] { + let (off, tol) = skin_off_balls(law); + println!("law {law:?}: skin {off:.3e} off its balls, tolerance {tol:e}"); + assert!( + off <= tol, + "law {law:?}: skin {off:e} off its balls, past {tol:e}" + ); + } +} + +/// A variable round pinched to zero radius at one end (#15257 review; the shape of the rig's +/// `ladder/07-fillets/006-variable-r5-to-zero`): the linear law 4 -> 0 and 0 -> 4 along the +/// box's top edge (the cubic law with Greville values `[4, 3, 2, 1, 0]` is exactly linear). +/// Built with SolidCraft's fixes, as the app builds it (the round as its definition +/// declines a round whose rails meet at an end, so this one is a B-spline skin the check +/// measures): it builds, refused by none of the check's refusals, and the skin lies within +/// the solver's tolerance of its balls (sampled, clear of the ends). +#[test] +fn a_variable_round_pinched_to_zero_keeps_its_skin_on_its_balls() { + for law in [[4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0]] { + let (off, tol) = skin_off_balls(law); + println!("law {law:?}: skin {off:.3e} off its balls, tolerance {tol:e}"); + assert!( + off <= tol, + "law {law:?}: skin {off:e} off its balls, past {tol:e}" + ); + } +} + +/// A constant-distance round whose ball varies (#15257 review): a solid cylinder of radius +/// `R` = 10 cut by a plane tilted `tilt` degrees about the y axis through (0, 0, 20). Along +/// the elliptical edge the angle between the faces changes, so a ball whose feet are a +/// constant chord `l` apart changes its radius. At the angle `phi` around the axis, with `u` +/// the radial direction and `n` the plane's outward normal, the ball touching both faces from +/// inside has its centre `R - r` from the axis and `r` below the plane, and its feet `r u` +/// and `r n` from its centre, so `l = r |u - n|`: `r(phi) = l / sqrt(2 - 2 n.u)`. Returns the +/// largest distance from the round faces to that family's envelope (a 1-D search over +/// `phi` per point), the solver's tolerance (4 x the edge's), and the radius range. +fn constant_distance_round_on_an_oblique_cylinder(tilt: f64, l: f64) -> (f64, f64, f64, f64) { + use solidcore::boolean::api_brep::boolean_intersection; + use solidcore::topology::proto_topology::p1::api_transform::{api_rotate, TransformObject}; + const R: f64 = 10.0; + let mut k = Kernel::default(); + let cylinder = create_cylinder(&mut k, Point3::new(0.0, 0.0, 0.0), R, 40.0).unwrap(); + let mut slab = + create_box(&mut k, Point3::new(-50.0, -50.0, -60.0), 100.0, 100.0, 80.0).unwrap(); + let p0 = Point3::new(0.0, 0.0, 20.0); + api_rotate( + &mut k, + Some(TransformObject::Brep(&mut slab)), + p0, + Vec3::new(0.0, 1.0, 0.0), + tilt, + ) + .unwrap(); + let mut b = boolean_intersection(&mut k, cylinder, slab).unwrap(); + // the elliptical edge (the bottom circle is at z = 0) + let top: Vec = b + .edges() + .ids() + .filter(|&e| { + let ivl = edge::interval(&b, e).unwrap(); + let c = edge::curve(&b, e).unwrap().unwrap(); + let x = c.evaluate_point(&k, ivl.evaluate(0.25)).unwrap(); + let y = c.evaluate_point(&k, ivl.evaluate(0.75)).unwrap(); + // (not the bottom circle, and not the cylinder's vertical seam) + x.z > 5.0 && (x.x - y.x).hypot(x.y - y.y) > 1e-6 + }) + .collect(); + assert!(!top.is_empty(), "no top edge"); + // the rotated top's normal: its x sign is the one the edge lies on + let a = tilt.to_radians(); + let x_far = { + let e = top[0]; + let c = edge::curve(&b, e).unwrap().unwrap(); + let ivl = edge::interval(&b, e).unwrap(); + (0..=64) + .map(|i| { + c.evaluate_point(&k, ivl.evaluate(f64::from(i) / 64.0)) + .unwrap() + }) + .fold(p0, |m, x| if x.x.abs() > m.x.abs() { x } else { m }) + }; + let n = [1.0, -1.0] + .into_iter() + .map(|sx| Vec3::new(sx * a.sin(), 0.0, a.cos())) + .min_by(|p, q| { + (x_far - p0) + .dot(*p) + .abs() + .total_cmp(&(x_far - p0).dot(*q).abs()) + }) + .unwrap(); + let on_plane = |x: Point3| (x - p0).dot(n); + for &e in &top { + let ivl = edge::interval(&b, e).unwrap(); + let c = edge::curve(&b, e).unwrap().unwrap(); + for f in [0.1, 0.5, 0.9] { + let x = c.evaluate_point(&k, ivl.evaluate(f)).unwrap(); + assert!( + on_plane(x).abs() < 1e-7, + "the edge is off the tilted plane: {}", + on_plane(x) + ); + assert!( + ((x.x * x.x + x.y * x.y).sqrt() - R).abs() < 1e-7, + "the edge is off the cylinder" + ); + } + } + let tol = 4.0 + * top + .iter() + .map(|&e| edge::tolerance(&b, e).unwrap()) + .fold(0.0, f64::max); + let mut session = FilletSession::new(&mut k, &mut b).unwrap(); + session + .prepare_per_edge_constant_distance( + &mut k, + &top, + &[l], + &[FilletSurfaceGeneratorType::Circular], + 2, + 0.0, + ) + .unwrap(); + session.do_fillet(&mut k).unwrap(); + drop(session); + let lines = check_brep(&mut k, &mut b, CheckLevel::Level2) + .unwrap() + .lines(); + assert!( + lines.is_empty(), + "the result fails {} validity tests", + lines.len() + ); + // the closed-form balls + let ball = |phi: f64| { + let u = Vec3::new(phi.cos(), phi.sin(), 0.0); + let r = l / (2.0 - 2.0 * n.dot(u)).sqrt(); + // `n.c = n.p0 - r`, `c = (R - r) u + z e_z` + let z = (n.dot(p0) - r - (R - r) * n.dot(u)) / n.z; + (u * (R - r) + Vec3::new(0.0, 0.0, z), r) + }; + let off_balls = |x: Point3| { + let signed = |phi: f64| { + let (c, r) = ball(phi); + x.distance(c) - r + }; + let m = 4096; + let step = 2.0 * PI / f64::from(m); + let (mut best, mut bd) = (0.0, f64::INFINITY); + for i in 0..m { + let phi = f64::from(i) * step; + let d = signed(phi); + if d < bd { + (best, bd) = (phi, d); + } + } + let (mut lo, mut hi) = (best - step, best + step); + let g = (5f64.sqrt() - 1.0) / 2.0; + for _ in 0..80 { + let (s1, s2) = (hi - g * (hi - lo), lo + g * (hi - lo)); + if signed(s1) < signed(s2) { + hi = s2; + } else { + lo = s1; + } + } + signed(0.5 * (lo + hi)).abs() + }; + // the round faces: neither the cylinder, the bottom nor the tilted plane + let (mut off, mut rounds, mut measured) = (0.0_f64, 0usize, 0usize); + let ids: Vec = b.faces().ids().collect(); + for f in ids { + let srf = face::surface(&b, f).unwrap().unwrap().clone(); + let dom = face::uv_domain(&b, f).unwrap(); + let at = |a: f64, c: f64| { + let uv = Point2::new( + dom.min().x + (dom.max().x - dom.min().x) * a, + dom.min().y + (dom.max().y - dom.min().y) * c, + ); + srf.evaluate_point(&k, uv).unwrap() + }; + let probes = [at(0.3, 0.4), at(0.6, 0.7), at(0.5, 0.5)]; + let original = probes + .iter() + .all(|x| ((x.x * x.x + x.y * x.y).sqrt() - R).abs() < 1e-9) + || probes.iter().all(|x| x.z.abs() < 1e-9) + || probes.iter().all(|&x| on_plane(x).abs() < 1e-9); + if original { + continue; + } + rounds += 1; + for i in 0..=400 { + for j in 0..=32 { + off = off.max(off_balls(at(f64::from(i) / 400.0, f64::from(j) / 32.0))); + measured += 1; + } + } + } + assert!(rounds >= 1, "no round face"); + assert_eq!(measured, rounds * 401 * 33, "every point measured"); + let (r_lo, r_hi) = ( + l / (2.0 + 2.0 * a.sin()).sqrt(), + l / (2.0 - 2.0 * a.sin()).sqrt(), + ); + (off, tol, r_lo, r_hi) +} + +/// #15257 review: `ball_radius_varies` turns the skin check on for a constant-distance round +/// too. Here its ball really varies (from 1.22 to 1.74 at 20 degrees with a 2 mm chord): the +/// round builds, valid, and its skin lies within the solver's tolerance of the balls' closed-form +/// envelope (sampled, 401 x 33 points per round face). +#[test] +fn a_constant_distance_round_whose_ball_varies_keeps_its_skin_on_its_balls() { + for tilt in [20.0, 35.0] { + let (off, tol, r_lo, r_hi) = constant_distance_round_on_an_oblique_cylinder(tilt, 2.0); + println!("tilt {tilt}: radius {r_lo:.4} to {r_hi:.4}; skin {off:.3e} off its balls, tolerance {tol:e}"); + assert!(r_hi - r_lo > 0.3, "the ball does not vary"); + assert!( + off <= tol, + "tilt {tilt}: skin {off:e} off its balls, past {tol:e}" + ); + } +} + /// `cf1c08b` + `0389af2`: the folded cubic law `[2, 2, 40, 3, 2]` is refused (the great /// circles built it folded, far off the union of its balls, before the G^n section's flag was /// retired). diff --git a/solidcore/crates/solidcore/tests/wr646_variable_round_follows_law.rs b/solidcore/crates/solidcore/tests/wr646_variable_round_follows_law.rs index a976de905e2..58f549386a7 100644 --- a/solidcore/crates/solidcore/tests/wr646_variable_round_follows_law.rs +++ b/solidcore/crates/solidcore/tests/wr646_variable_round_follows_law.rs @@ -30,12 +30,14 @@ use solidcore::math::{Point3, Vec3}; use solidcore::nurbs::b_spline_curve::p1::{ BSplineCurve, BSplineCurveForm, CanonicalData, KnotType, }; +use solidcore::nurbs::math::gamma; use solidcore::primitive::api_primitives::create_box; use solidcore::query::api_queries::surface_closest_point; use solidcore::surface::surface::SurfaceKind; use solidcore::topology::face::p2 as face; use solidcore::topology::{edge, EdgeId}; use solidcore::{Brep, Kernel}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; fn volume(k: &Kernel, b: &mut Brep) -> f64 { let store = AttributeStore::default(); @@ -184,13 +186,1779 @@ fn variable_round_on_planes_removes_the_laws_volume() { assert!(off < 3e-4, "{off}"); } -/// Without the fix the rails stray between the traced points: the surface is 8.0e-4 off the -/// balls' touch circles, against 2.0e-4 with it. (The union of the balls removes about the -/// same volume either way, within 3e-5 of the envelope's: before the round was the union of -/// its balls, the great circles' volume showed the stray rails too.) +/// Without the span fix the rails stray between the traced points, but the round's skin no +/// longer follows them: it is held to its balls between stations (#15256). So the default +/// kernel's surface is within T = 4 x the edge tolerance (1e-5 mm) of the balls' touch +/// circles (sampled here, at the law's sections). A skin within T of the envelope moves +/// the removed volume by at most about T x the envelope's area (A = 110.7 mm^2 here, +/// 4.43e-3 mm^3), to first order: a necessary condition, which the result before #15256 +/// failed (6.1e-4 off the circles, 6.2e-3 mm^3 off the volume). The volume and the area are +/// the balls' closed-form quadratures ([`envelope_removed`], [`envelope_area`]). This test +/// asserted that defect (`off > 5e-4`). #[test] -fn variable_round_on_planes_strays_off_its_balls_without_the_fix() { +fn variable_round_on_planes_holds_its_balls_without_the_span_fix() { + let reference = envelope_removed(&law_6611, 20.0, 6.0, 24); + let bound = 4e-5 * envelope_area(&law_6611, 20.0, 24); let (v, off) = rounded_cube(false); - eprintln!("upstream: {v} off {off}"); - assert!(off > 5e-4, "{off}"); + let removed = 8000.0 - v; + eprintln!( + "default: removed {removed} reference {reference} diff {} bound {bound} off {off}", + removed - reference + ); + assert!( + (removed - reference).abs() <= bound, + "{removed} vs {reference}" + ); + assert!(off < 4e-5, "{off}"); +} + +// ---- Closed-form ball references for #15256 ---------------------------------------- +// +// The round of a straight edge between two perpendicular planes, from its balls alone: +// the ball at edge position `s` has radius `r(s)` and centre `e(s) + r(s) w`, `w` the sum +// of the planes' inward normals. The radius law is a one-span Bezier polynomial in closed +// form. Past the edge's ends it is the same polynomial: upstream's +// `SmBSplineFilletLaw::Evaluate` (`SmFilletExecutive.cpp`) continues a law past its curve's +// domain by its end span, and for a one-span law that is the polynomial itself; the +// skin's stations past the ends are balls of that continued law. + +/// The Bezier polynomial with control values `c` and its derivative at `u`. +fn bezier(c: &[f64], u: f64) -> (f64, f64) { + let n = c.len() - 1; + let mut b = c.to_vec(); + for k in (1..=n).rev() { + for i in 0..k { + b[i] = (1.0 - u) * b[i] + u * b[i + 1]; + } + } + let mut d: Vec = c.windows(2).map(|w| n as f64 * (w[1] - w[0])).collect(); + for k in (1..n).rev() { + for i in 0..k { + d[i] = (1.0 - u) * d[i] + u * d[i + 1]; + } + } + (b[0], d.first().copied().unwrap_or(0.0)) +} + +/// The monomial coefficients `a` (`p(u) = sum a_j u^j`) of the Bezier polynomial with +/// control values `c`, degree at most 3. +fn monomial(c: &[f64]) -> [f64; 4] { + match *c { + [c0] => [c0, 0.0, 0.0, 0.0], + [c0, c1] => [c0, c1 - c0, 0.0, 0.0], + [c0, c1, c2] => [c0, 2.0 * (c1 - c0), c0 - 2.0 * c1 + c2, 0.0], + [c0, c1, c2, c3] => [ + c0, + 3.0 * (c1 - c0), + 3.0 * (c0 - 2.0 * c1 + c2), + c3 - 3.0 * c2 + 3.0 * c1 - c0, + ], + _ => panic!("degree above 3"), + } +} + +/// The exact range of `p` (monomial, degree at most 3) over `[a, b]`: its values at the +/// ends and at the real roots of `p'` inside. +fn poly_range(p: [f64; 4], a: f64, b: f64) -> (f64, f64) { + let at = |u: f64| p[0] + u * (p[1] + u * (p[2] + u * p[3])); + let mut xs = vec![a, b]; + let (qa, qb, qc) = (3.0 * p[3], 2.0 * p[2], p[1]); + if qa.abs() > 0.0 { + let disc = qb * qb - 4.0 * qa * qc; + if disc >= 0.0 { + xs.push((-qb + disc.sqrt()) / (2.0 * qa)); + xs.push((-qb - disc.sqrt()) / (2.0 * qa)); + } + } else if qb.abs() > 0.0 { + xs.push(-qc / qb); + } + xs.into_iter() + .filter(|x| *x >= a && *x <= b) + .map(at) + .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| { + (lo.min(v), hi.max(v)) + }) +} + +/// `p'` of a monomial `p`. +fn derivative(p: [f64; 4]) -> [f64; 4] { + [p[1], 2.0 * p[2], 3.0 * p[3], 0.0] +} + +/// Gauss-Legendre nodes and weights on `[-1, 1]` (Newton on `P_n`). +fn gauss_legendre(n: usize) -> Vec<(f64, f64)> { + (0..n) + .map(|i| { + let mut x = (std::f64::consts::PI * (i as f64 + 0.75) / (n as f64 + 0.5)).cos(); + let mut dp = 0.0; + for _ in 0..100 { + let (mut p0, mut p1) = (1.0, x); + for k in 2..=n { + let p2 = ((2 * k - 1) as f64 * x * p1 - (k - 1) as f64 * p0) / k as f64; + p0 = p1; + p1 = p2; + } + dp = n as f64 * (x * p1 - p0) / (x * x - 1.0); + let dx = p1 / dp; + x -= dx; + if dx.abs() < 1e-15 { + break; + } + } + (x, 2.0 / ((1.0 - x * x) * dp * dp)) + }) + .collect() +} + +/// `int_a^b f`, Gauss-Legendre with 16 points in each of `panels` panels. +fn integrate(a: f64, b: f64, panels: usize, f: &mut dyn FnMut(f64) -> f64) -> f64 { + let g = gauss_legendre(16); + let h = (b - a) / panels as f64; + let mut sum = 0.0; + for p in 0..panels { + let mid = a + h * (p as f64 + 0.5); + for &(x, w) in &g { + sum += w * 0.5 * h * f(mid + 0.5 * h * x); + } + } + sum +} + +/// How a section's area is integrated across it. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Across { + /// Smooth: in `u`, `a = r(s) u^2` (the union's lowest point leaves each plane like + /// `sqrt(a)`). + Smooth, + /// Plain Gauss-Legendre in `a`, as `ENVELOPE_REMOVED`'s quadrature was. + Plain, +} + +/// The lowest point of the union of the balls `r` on the line at distance `a` from one +/// plane in the section `s`: `min_t r_t - sqrt(r_t^2 - (t - s)^2 - (a - r_t)^2)` over the +/// balls `t` within `1.05 r_max` of `s` (`samples` samples, then golden section). +fn union_low(r: &dyn Fn(f64) -> (f64, f64), r_max: f64, samples: u32, s: f64, a: f64) -> f64 { + let g = |t: f64| { + let rt = r(t).0; + let q = rt * rt - (t - s) * (t - s) - (a - rt) * (a - rt); + if q >= 0.0 { + rt - q.sqrt() + } else { + f64::INFINITY + } + }; + let (t0, t1) = (s - 1.05 * r_max, s + 1.05 * r_max); + let h = (t1 - t0) / f64::from(samples); + let (mut bi, mut bv) = (0, f64::INFINITY); + for i in 0..=samples { + let v = g(t0 + h * f64::from(i)); + if v < bv { + (bi, bv) = (i, v); + } + } + let c = t0 + h * f64::from(bi); + let (mut lo, mut hi) = (c - h, c + h); + let phi = 0.5 * (5.0_f64.sqrt() - 1.0); + for _ in 0..60 { + let (m1, m2) = (hi - phi * (hi - lo), lo + phi * (hi - lo)); + if g(m1) < g(m2) { + hi = m2; + } else { + lo = m1; + } + } + bv.min(g(0.5 * (lo + hi))) +} + +/// The volume the union of the balls `r` (radius and slope at an edge position) takes +/// off the edge `[0, len]`: the integral along the edge of the area each section `s` +/// cuts between the rails (both distances from the planes below `r(s)`: a ball touches +/// each plane at its own foot) above the union of the balls' discs ([`union_low`]). +/// Gauss-Legendre, 16 points in each of `panels` panels along the edge and `panels / 4` +/// across (or `across_panels` for [`Across::Plain`]). +fn envelope_removed_with( + r: &dyn Fn(f64) -> (f64, f64), + len: f64, + r_max: f64, + panels: usize, + samples: u32, + across: Across, +) -> f64 { + integrate(0.0, len, panels, &mut |s| { + let rs = r(s).0; + match across { + Across::Smooth => integrate(0.0, 1.0, (panels / 4).max(1), &mut |u| { + 2.0 * rs * u * union_low(r, r_max, samples, s, rs * u * u).clamp(0.0, rs) + }), + Across::Plain => integrate(0.0, rs, 8, &mut |a| { + union_low(r, r_max, samples, s, a).clamp(0.0, rs) + }), + } + }) +} + +/// [`envelope_removed_with`], smooth across, 600 samples per minimisation. +fn envelope_removed(r: &dyn Fn(f64) -> (f64, f64), len: f64, r_max: f64, panels: usize) -> f64 { + envelope_removed_with(r, len, r_max, panels, 600, Across::Smooth) +} + +/// The arc of the ball at `t` between its feet on the planes with inward normals `na` +/// and `nb`, at the fraction `sigma` of the way: the point and its derivative in +/// `sigma`. The ball touches the balls' envelope along the circle where +/// `

= -r r'` (centre `c - (r r'/|c'|^2) c'`, radius +/// `r sqrt(1 - r'^2/|c'|^2)`); its feet `c - r na`, `c - r nb` lie on that circle, and +/// the round is the arc between them on the edge's side. +fn touch_arc( + r: &dyn Fn(f64) -> (f64, f64), + origin: Vec3, + e: Vec3, + na: Vec3, + nb: Vec3, + t: f64, + sigma: f64, +) -> (Vec3, Vec3) { + let w = na + nb; + let (rt, dr) = r(t); + let c = origin + e * t + w * rt; + let cd = e + w * dr; + let n2 = cd.dot(cd); + let m = c - cd * (rt * dr / n2); + let radius = rt * (1.0 - dr * dr / n2).sqrt(); + let (fa, fb) = (c - na * rt - m, c - nb * rt - m); + let u1 = fa * (1.0 / fa.length()); + let v = fb - u1 * fb.dot(u1); + let u2 = v * (1.0 / v.length()); + let phi = (fb.dot(u1) / fb.length()).clamp(-1.0, 1.0).acos(); + let a = sigma * phi; + ( + m + (u1 * a.cos() + u2 * a.sin()) * radius, + (u2 * a.cos() - u1 * a.sin()) * (radius * phi), + ) +} + +/// The area of the balls' envelope over the edge `[0, len]` ([`touch_arc`]), as +/// `|E_t x E_s|` (`E_t` by central differences), Gauss-Legendre with 16 points in each of +/// `panels` panels both ways. +fn envelope_area(r: &dyn Fn(f64) -> (f64, f64), len: f64, panels: usize) -> f64 { + let (e, na, nb) = ( + Vec3::new(1.0, 0.0, 0.0), + Vec3::new(0.0, 1.0, 0.0), + Vec3::new(0.0, 0.0, 1.0), + ); + integrate(0.0, len, panels, &mut |t| { + let h = 1e-6 * len; + integrate(0.0, 1.0, panels, &mut |sigma| { + let et = (touch_arc(r, Vec3::ZERO, e, na, nb, t + h, sigma).0 + - touch_arc(r, Vec3::ZERO, e, na, nb, t - h, sigma).0) + * (0.5 / h); + let es = touch_arc(r, Vec3::ZERO, e, na, nb, t, sigma).1; + cross(et, es).length() + }) + }) +} + +fn cross(a: Vec3, b: Vec3) -> Vec3 { + Vec3::new( + a.y * b.z - a.z * b.y, + a.z * b.x - a.x * b.z, + a.x * b.y - a.y * b.x, + ) +} + +/// The law 6, 6, 1, 1 along the 20 mm edge: radius and slope at `s`. +fn law_6611(s: f64) -> (f64, f64) { + let (r, dr) = bezier(&[6.0, 6.0, 1.0, 1.0], s / 20.0); + (r, dr / 20.0) +} + +/// The balls of a linear law `r = r0 + b s` fill a solid cone about their centres' line +/// (`|b| < |c'|`): a point at distance `rho` from that line and `tau` along it (from the +/// centre of `s = 0`, in the direction of `c' = e + b w`) is in it iff +/// `rho sqrt(1 - beta^2) <= r0 + beta tau`, `beta = b / |c'|`. The union's lowest point on +/// the line at distance `a` from one plane in the section `s` is where that holds with +/// equality: a quadratic in the other distance. The edge runs along x, the planes are +/// y = 0 and z = 0. +fn cone_low(r0: f64, b: f64, s: f64, a: f64) -> f64 { + let cd = Vec3::new(1.0, b, b); + let n = cd.length(); + let d = cd * (1.0 / n); + let beta = b / n; + let k = (1.0 - beta * beta).sqrt(); + let origin = Vec3::new(0.0, r0, r0); + // X(z) = (s, a, z): rho^2 k^2 = (r0 + beta tau)^2 with tau = (X - origin).d + let f = |z: f64| { + let x = Vec3::new(s, a, z) - origin; + let tau = x.dot(d); + let rho2 = x.dot(x) - tau * tau; + (rho2 * k * k, r0 + beta * tau) + }; + // quadratic in z: A z^2 + B z + C = 0 from three samples (exact for a quadratic) + let g = |z: f64| { + let (p, q) = f(z); + p - q * q + }; + let (g0, g1, g2) = (g(0.0), g(1.0), g(-1.0)); + let qa = 0.5 * (g1 + g2) - g0; + let qb = 0.5 * (g1 - g2); + let disc = qb * qb - 4.0 * qa * g0; + if disc < 0.0 { + return f64::INFINITY; + } + let roots = [ + (-qb - disc.sqrt()) / (2.0 * qa), + (-qb + disc.sqrt()) / (2.0 * qa), + ]; + // the lower intersection with the cone's nappe that holds the balls (r0 + beta tau > 0) + roots + .into_iter() + .filter(|z| f(*z).1 > 0.0) + .fold(f64::INFINITY, f64::min) +} + +/// The closed-form quadrature: exact for a constant radius (the corner less a quarter +/// disc, `(1 - pi/4) r^2 len`, and the quarter cylinder's area `pi/2 r len`), its ball +/// search exact for a varying radius (the union of a linear law's balls is a cone, whose +/// lowest point on each line is a quadratic's root, [`cone_low`]), converged for the law +/// 6, 6, 1, 1 (24 panels and 600 samples against 48 and 1200), and near +/// [`ENVELOPE_REMOVED`]. That constant (mm^3) is a quadrature over 20001 discrete balls, +/// converged in the number of balls to 1.1e-6, but with 8 plain Gauss-Legendre panels +/// across a section, where the union's lowest point leaves each plane like `sqrt(a)`: +/// that scheme, run here with the exact ball search, reproduces the constant to 1.3e-6, +/// so the constant's gap to this quadrature (4.53e-4 mm^3) is that scheme's, and on a +/// cylinder of radius 6, whose volume is exact, the same scheme is 1.03e-3 mm^3 low. +#[test] +fn the_balls_quadrature_is_exact_for_a_cylinder_and_a_cone_and_converges() { + let r = 3.0; + let cylinder = |_: f64| (r, 0.0); + let v = envelope_removed(&cylinder, 20.0, r, 8); + let exact = (1.0 - std::f64::consts::FRAC_PI_4) * r * r * 20.0; + assert!((v - exact).abs() < 1e-9 * exact, "{v} vs {exact}"); + let a = envelope_area(&cylinder, 20.0, 8); + let exact = std::f64::consts::FRAC_PI_2 * r * 20.0; + assert!((a - exact).abs() < 1e-9 * exact, "{a} vs {exact}"); + + // the ball search against the cone's closed form, over sections and lines + let (r0, b) = (1.0, 0.15); + let linear = |s: f64| (r0 + b * s, b); + for i in 0..=20 { + let s = f64::from(i); + let rs = r0 + b * s; + for j in 1..20 { + let a = rs * f64::from(j) / 20.0; + let searched = union_low(&linear, r0 + b * 25.0, 600, s, a); + let closed = cone_low(r0, b, s, a); + assert!( + (searched - closed).abs() < 1e-10, + "s {s} a {a}: {searched} vs {closed}" + ); + } + } + + let v = envelope_removed_with(&law_6611, 20.0, 6.0, 24, 600, Across::Smooth); + let fine = envelope_removed_with(&law_6611, 20.0, 6.0, 48, 1200, Across::Smooth); + eprintln!("removed {v} (48 panels, 1200 samples: {fine}) against {ENVELOPE_REMOVED}"); + assert!((v - fine).abs() < 1e-7, "{v} vs {fine}"); + + // ENVELOPE_REMOVED's scheme: 40 panels along, 8 plain panels across + let old = envelope_removed_with(&law_6611, 20.0, 6.0, 40, 1200, Across::Plain); + let old_cylinder = envelope_removed_with(&|_| (6.0, 0.0), 20.0, 6.0, 40, 1200, Across::Plain); + let exact_cylinder = (1.0 - std::f64::consts::FRAC_PI_4) * 36.0 * 20.0; + eprintln!( + "old scheme: law {old} (constant {ENVELOPE_REMOVED}, smooth {v}); cylinder r 6 {old_cylinder} (exact {exact_cylinder})" + ); + assert!( + (old - ENVELOPE_REMOVED).abs() < 2e-6, + "{old} vs {ENVELOPE_REMOVED}" + ); + assert!((v - old - 4.534e-4).abs() < 1e-6, "{v} - {old}"); + assert!( + (exact_cylinder - old_cylinder - 1.0335e-3).abs() < 1e-6, + "{old_cylinder} vs {exact_cylinder}" + ); +} + +/// A `blend.fillet_executive_p3` law case (the goldens fixture +/// `bspline_radius_law.json`): the box, the edge's index, the law's control radii and +/// edge map, and the solver's continuity. +struct LawCase { + name: &'static str, + dims: [f64; 3], + radius: f64, + radii: &'static [f64], + edge_map: [f64; 2], + edge: usize, + continuity: u32, +} + +/// The six rows #15256 moves. +const MOVED_ROWS: [LawCase; 6] = [ + LawCase { + name: "law-cube20-e0-deg2-smooth-4-2-4", + dims: [20.0; 3], + radius: 4.0, + radii: &[4.0, 2.0, 4.0], + edge_map: [0.0, 1.0], + edge: 0, + continuity: 1, + }, + LawCase { + name: "law-cube20-e0-deg2-smooth-g2", + dims: [20.0; 3], + radius: 4.0, + radii: &[4.0, 2.0, 4.0], + edge_map: [0.0, 1.0], + edge: 0, + continuity: 2, + }, + LawCase { + name: "law-cube20-e0-deg3-asymmetric", + dims: [20.0; 3], + radius: 2.0, + radii: &[2.0, 3.0, 5.0, 3.0], + edge_map: [0.0, 1.0], + edge: 0, + continuity: 1, + }, + LawCase { + name: "law-cube20-e7-deg3-asymmetric", + dims: [20.0; 3], + radius: 2.0, + radii: &[2.0, 3.0, 5.0, 3.0], + edge_map: [0.0, 1.0], + edge: 7, + continuity: 1, + }, + LawCase { + name: "law-box10x20x30-e0-deg2-edge-map-sub-range", + dims: [10.0, 20.0, 30.0], + radius: 0.5, + radii: &[0.5, 3.0, 1.0], + edge_map: [0.2, 0.8], + edge: 0, + continuity: 1, + }, + // `SmExtent1d(0.8, 0.2)` swaps its ends (`SmExtent1d.cpp`): the same law as the sub-range + LawCase { + name: "law-box10x20x30-e0-deg2-edge-map-reversed", + dims: [10.0, 20.0, 30.0], + radius: 0.5, + radii: &[0.5, 3.0, 1.0], + edge_map: [0.8, 0.2], + edge: 0, + continuity: 1, + }, +]; + +/// The Bezier law of `c` as the session takes it. +fn bezier_law(c: &LawCase) -> FilletLaw { + let control: Vec = c.radii.iter().map(|r| Vec3::new(*r, 0.0, 0.0)).collect(); + let n = c.radii.len(); + let curve = BSplineCurve::create_canonical(&CanonicalData { + dim: 3, + degree: n - 1, + control_points: &control, + form: BSplineCurveForm::default(), + knot_multiplicities: &[n, n], + knots: &[0.0, 1.0], + knot_type: KnotType::default(), + weights: None, + trim: None, + }) + .unwrap(); + FilletLaw::bspline(curve, &Extent1d::from_min_max(c.edge_map[0], c.edge_map[1])) +} + +/// A moved row built as the goldens runner builds it, with its edge's frame and law. +struct BuiltRow { + k: Kernel, + body: Brep, + tol: f64, + origin: Vec3, + e: Vec3, + na: Vec3, + nb: Vec3, + len: f64, + /// The law's monomial coefficients in its own parameter `u`, and the map + /// `u = m0 + k s` (`k = (m1 - m0) / len`) from the edge position `s`. + poly: [f64; 4], + m0: f64, + slope: f64, + radii: &'static [f64], +} + +impl BuiltRow { + /// The law's radius and slope at edge position `s`, running from the edge's start + /// (`reverse` false) or end. The session builds the solver with + /// `bReverseOrientation = FALSE` (`SetFilletParameters`, `SmFilletExecutive.cpp`: `new + /// SmVariableRadiusFS(.., *pOptVarRadLaw, FALSE)`), and `SmBSplineFilletLaw::Evaluate` + /// maps a parameter `t` of the edge interval to `dT = (t - min) / (max - min)` and the + /// law parameter `m_vEdgeMap.Evaluate(dT)`: the law runs from the edge's start vertex + /// (its interval's minimum) towards its end. + fn law(&self, reverse: bool) -> impl Fn(f64) -> (f64, f64) + Copy + Send + Sync + 'static { + let (len, radii, m0, slope) = (self.len, self.radii, self.m0, self.slope); + move |s: f64| { + let f = if reverse { len - s } else { s }; + let (r, dr) = bezier(radii, m0 + slope * f); + (r, if reverse { -dr * slope } else { dr * slope }) + } + } + + /// The edge's frame: its start, direction and the two faces' inward normals. + fn frame(&self) -> Frame { + Frame { + origin: self.origin, + e: self.e, + na: self.na, + nb: self.nb, + } + } +} + +/// A box edge's frame: its start, unit direction and the two faces' inward normals. The +/// ball at edge position `s` is centred at `origin + s e + r(s) (na + nb)`. +#[derive(Clone, Copy)] +struct Frame { + origin: Vec3, + e: Vec3, + na: Vec3, + nb: Vec3, +} + +fn build_row(c: &LawCase) -> BuiltRow { + let mut k = Kernel::default(); + let [x, y, z] = c.dims; + let mut b = create_box(&mut k, Vec3::ZERO, x, y, z).unwrap(); + let e = solidcore::topology::brep::p1::edges(&b, None).unwrap()[c.edge]; + let tol = edge::tolerance(&b, e).unwrap(); + let ivl = edge::interval(&b, e).unwrap(); + let curve = edge::curve(&b, e).unwrap().unwrap(); + let (p0, p1) = ( + curve.evaluate_point(&k, ivl.min()).unwrap(), + curve.evaluate_point(&k, ivl.max()).unwrap(), + ); + let len = p0.distance(p1); + let mut inward = Vec::new(); + for (i, d) in c.dims.iter().enumerate() { + let (a, q) = ([p0.x, p0.y, p0.z][i], [p1.x, p1.y, p1.z][i]); + if (a - q).abs() < 1e-12 { + let mut n = [0.0; 3]; + n[i] = if a.abs() < 1e-12 { + 1.0 + } else { + assert!((a - d).abs() < 1e-12); + -1.0 + }; + inward.push(Vec3::new(n[0], n[1], n[2])); + } + } + { + let mut session = FilletSession::new(&mut k, &mut b).unwrap(); + session + .prepare_variable_radius_edges(&mut k, &[e], c.radius, bezier_law(c), 1, c.continuity) + .unwrap(); + session.do_fillet(&mut k).unwrap(); + } + let (m0, m1) = ( + c.edge_map[0].min(c.edge_map[1]), + c.edge_map[0].max(c.edge_map[1]), + ); + BuiltRow { + k, + body: b, + tol, + origin: Vec3::new(p0.x, p0.y, p0.z), + e: (Vec3::new(p1.x, p1.y, p1.z) - Vec3::new(p0.x, p0.y, p0.z)) * (1.0 / len), + na: inward[0], + nb: inward[1], + len, + poly: monomial(c.radii), + m0, + slope: (m1 - m0) / len, + radii: c.radii, + } +} + +/// Each moved row's round removes its balls' volume to within T x the envelope's area +/// (T = 4 x the edge tolerance). A first-order consistency check: a skin within T of the +/// envelope moves the volume by at most about that, so a row outside it would be off its +/// balls, but a row inside it is not shown to be within T (that is +/// [`certify_the_moved_rows_skins_within_t`]). The reference volume and area come from +/// the balls in closed form ([`envelope_removed`], [`envelope_area`]); the law runs from +/// each edge's start ([`BuiltRow::law`]). +#[test] +fn the_moved_law_rounds_remove_their_balls_volume() { + for c in &MOVED_ROWS { + let mut row = build_row(c); + let removed = c.dims.iter().product::() - volume(&row.k, &mut row.body); + let (len, tol) = (row.len, row.tol); + let r = row.law(false); + let r_max = (0..=200) + .map(|i| r(-0.25 * len + 1.5 * len * f64::from(i) / 200.0).0) + .fold(0.0_f64, f64::max); + let reference = envelope_removed(&r, len, r_max, 24); + let area = envelope_area(&r, len, 24); + let bound = 4.0 * tol * area; + eprintln!( + "{}: removed {removed:.7} reference {reference:.7} diff {:.3e} bound T x A = {:.0e} x {area:.4} = {bound:.3e}", + c.name, + removed - reference, + 4.0 * tol + ); + assert!((removed - reference).abs() <= bound, "{}", c.name); + } +} + +/// Per moved row, the reference volume at twice the panels and twice the ball samples. +#[test] +#[ignore = "proof run for #15257 (about a minute): the quadrature's convergence per row"] +fn the_moved_rows_reference_volumes_converge() { + for c in &MOVED_ROWS { + let row = build_row(c); + let len = row.len; + let r = row.law(false); + let r_max = (0..=200) + .map(|i| r(-0.25 * len + 1.5 * len * f64::from(i) / 200.0).0) + .fold(0.0_f64, f64::max); + let v = envelope_removed_with(&r, len, r_max, 24, 600, Across::Smooth); + let fine = envelope_removed_with(&r, len, r_max, 48, 1200, Across::Smooth); + eprintln!( + "{}: reference {v:.10} (48 panels, 1200 samples: {fine:.10}) spread {:.2e}", + c.name, + fine - v + ); + assert!((fine - v).abs() < 1e-7, "{}", c.name); + } +} + +/// The skin's B-spline data on one knot-span patch, bounding its first and second +/// derivatives there. +struct PatchBounds { + /// `max |S_u|`, `max |S_uu|`, `max |S_v|`, `max |S_vv|` over the patch. + su: f64, + suu: f64, + sv: f64, + svv: f64, +} + +/// The full knot vector from distinct knots and multiplicities. +fn full_knots(knots: &[f64], mults: &[usize]) -> Vec { + knots + .iter() + .zip(mults) + .flat_map(|(k, m)| std::iter::repeat_n(*k, *m)) + .collect() +} + +/// Bounds of a rational B-spline surface's derivatives on the patch of spans `i` (u) and +/// `j` (v): with `S = A / w` (`A` the weighted points, translated to a point of the patch +/// so `|S - R|` is small), the derivative surfaces of `A` and `w` are B-splines whose +/// control values are scaled differences of the patch's control values, and lie in their +/// convex hull on the patch (non-negative basis summing to 1). Then +/// `S_u = (A_u - (S - R) w_u) / w` and `S_uu = (A_uu - 2 S_u w_u - (S - R) w_uu) / w`, with +/// `w >= ` the patch's least weight and `|S - R| <=` its control points' farthest from `R`. +fn patch_bounds( + net: &[[f64; 4]], + nv: usize, + knots: [&[f64]; 2], + degrees: [usize; 2], + span: [usize; 2], +) -> PatchBounds { + let [ku, kv] = knots; + let [p, q] = degrees; + let [i, j] = span; + let at = |a: usize, b: usize| net[a * nv + b]; + let rows: Vec = (i - p..=i).collect(); + let cols: Vec = (j - q..=j).collect(); + let pt = |c: [f64; 4]| Vec3::new(c[0] / c[3], c[1] / c[3], c[2] / c[3]); + let reference = pt(at(i - p, j - q)); + // translated homogeneous points: (w (x - R), w) + let hom = |a: usize, b: usize| { + let c = at(a, b); + let x = pt(c) - reference; + [x.x * c[3], x.y * c[3], x.z * c[3], c[3]] + }; + let mut w_min = f64::INFINITY; + let mut far = 0.0_f64; + for &a in &rows { + for &b in &cols { + let c = at(a, b); + w_min = w_min.min(c[3]); + far = far.max((pt(c) - reference).length()); + } + } + assert!(w_min > 0.0, "a non-positive weight"); + let diff = |x: [f64; 4], y: [f64; 4], f: f64| { + [ + (x[0] - y[0]) * f, + (x[1] - y[1]) * f, + (x[2] - y[2]) * f, + (x[3] - y[3]) * f, + ] + }; + let norm3 = |x: [f64; 4]| (x[0] * x[0] + x[1] * x[1] + x[2] * x[2]).sqrt(); + // one direction's first and second derivative control values' bounds + let bound = |along_u: bool| -> (f64, f64, f64, f64) { + let (deg, kn, idx) = if along_u { (p, ku, i) } else { (q, kv, j) }; + let others: &[usize] = if along_u { &cols } else { &rows }; + let mut a1 = 0.0_f64; + let mut w1 = 0.0_f64; + let mut a2 = 0.0_f64; + let mut w2 = 0.0_f64; + for &o in others { + let h = |m: usize| if along_u { hom(m, o) } else { hom(o, m) }; + let first: Vec<[f64; 4]> = (idx - deg..idx) + .map(|m| { + let den = kn[m + deg + 1] - kn[m + 1]; + if den > 0.0 { + diff(h(m + 1), h(m), deg as f64 / den) + } else { + [0.0; 4] + } + }) + .collect(); + for d in &first { + a1 = a1.max(norm3(*d)); + w1 = w1.max(d[3].abs()); + } + if deg >= 2 { + for (n, m) in (idx - deg..idx - 1).enumerate() { + let den = kn[m + deg + 1] - kn[m + 2]; + let d = if den > 0.0 { + diff(first[n + 1], first[n], (deg - 1) as f64 / den) + } else { + [0.0; 4] + }; + a2 = a2.max(norm3(d)); + w2 = w2.max(d[3].abs()); + } + } + } + (a1, w1, a2, w2) + }; + let derivs = |along_u: bool| { + let (a1, w1, a2, w2) = bound(along_u); + let s1 = (a1 + far * w1) / w_min; + let s2 = (a2 + 2.0 * s1 * w1 + far * w2) / w_min; + (s1, s2) + }; + let (su, suu) = derivs(true); + let (sv, svv) = derivs(false); + PatchBounds { su, suu, sv, svv } +} + +/// A row's law over the balls' positions (`s` in the range): exact ranges of `r`, `|r'|` +/// and `|r''|` from its polynomial, widened by their rounding, and the size that scales +/// the rounding of `psi`. +#[derive(Clone, Copy)] +struct LawBounds { + r_lo: f64, + r_hi: f64, + r1: f64, + r2: f64, + /// `|o|_inf + max |s| + 3 r_hi + 1`: with `|p|_inf`, the magnitudes `psi` is formed from. + scale: f64, +} + +impl LawBounds { + /// `|c'| <= sqrt(1 + 2 r'^2)` (`c' = e + r' w`, `e` normal to `w`, `|w| = sqrt 2`). + fn c1(&self) -> f64 { + (1.0 + 2.0 * self.r1 * self.r1).sqrt() * (1.0 + gamma(8)) + } + + /// A bound on the rounding of a computed `psi(s) = |p - c(s)| - r(s)` (and of `rho`): + /// each coordinate of `c(s) = o + s e + r(s) w` is at most 16 rounded operations from the + /// data (the Bezier law's de Casteljau included), the difference, the three squares, + /// their sum, the root and the subtraction 8 more; by the standard model each is within + /// `gamma(64)` relative of the sum of the magnitudes it is formed from, at most + /// `4 (|p|_inf + scale)` per coordinate. + fn psi_err(&self, p: Vec3) -> f64 { + gamma(64) * 4.0 * (p.x.abs().max(p.y.abs()).max(p.z.abs()) + self.scale) + } + + /// `|psi''| <= |c'|^2 / rho + |r''| (1 + |w|)` where `rho >= rho_lo > 0`. + fn psi_ss(&self, rho_lo: f64) -> f64 { + if rho_lo <= 0.0 { + return f64::INFINITY; + } + (self.c1() * self.c1() / rho_lo + (1.0 + 2.0_f64.sqrt()) * self.r2) * (1.0 + gamma(8)) + } +} + +/// A ball sample of the distance search: `(s, psi(s), rho(s))`. +type Sample = (f64, f64, f64); + +/// What a node's certificate gives: `|phi|` at the node is at most `abs`, and the nearest +/// ball is `t0`. +struct NodeCert { + lo: f64, + hi: f64, + t0: f64, +} + +/// Bounds of the signed distance `phi(p) = min_s psi(s)`, `psi(s) = |p - c(s)| - r(s)`, from +/// `p` to the balls' envelope over the balls at `s` in `range`, by branch and bound, with no +/// assumption on `phi` itself. On an interval `[a, b]`, +/// `psi >= min(psi(a), psi(b)) - m (b - a)^2 / 8` when `|psi''| <= m` there, and +/// `|psi''| <= |c'|^2 / rho + |r''| (1 + |w|)` with `rho = |p - c(s)|`, which is +/// `|c'|`-Lipschitz in `s`, so `rho >= (rho(a) + rho(b)) / 2 - |c'| (b - a) / 2` on the +/// interval: `m` comes from the interval's own ends. An interval whose bound is at least the +/// best value found less `EPS` cannot hold a lower minimum and is dropped; the others are +/// halved. Every computed `psi` is within [`LawBounds::psi_err`] of the true one, which the +/// bounds carry. Returns `lo <= phi(p) <= hi` and the best ball `t0`, which must be inside +/// the range when `interior` (asserted: the balls past the range are not part of the family). +/// +/// With `cell = Some(d)`, also certifies that for every point `p'` within `d` of `p` the +/// nearest ball is unique and nondegenerate, so `phi` is twice differentiable there with +/// the Hessian bound [`certify_the_moved_rows_skins_within_t`] uses: +/// - outside `I0 = [t0 - delta, t0 + delta]`, `psi(s; p) > hi + 2 d` (the same branch and bound +/// over the outside, to that threshold). Since `psi` is 1-Lipschitz in `p`, +/// `psi(s; p') >= psi(s; p) - d > hi + d >= psi(t0; p') >= phi(p')`: the nearest ball of +/// every `p'` is in `I0`; +/// - on `I0`, for every `p'`, `psi_ss = (|c'|^2 - (u.c')^2) / rho - r'' (1 + u.w) > 0`, with +/// `u.c' = -psi_s - r'`, `|psi_s(s; p')| <= |psi_s(t0; p)| + M_ss delta + (|c'| / rho) d =: P`, +/// so `|c'|^2 - (u.c')^2 >= 1 + 2 r'^2 - (P + |r'|)^2 >= 1 - 2 P^2`: `psi(.; p')` is +/// strictly convex on `I0`, its minimum there unique and nondegenerate. +/// +/// Within the envelope's reach `phi` is the signed distance to the envelope on both sides: +/// outside the union it is the distance to the union, and inside, the envelope of the balls +/// shrunk by `d` is the envelope's inner offset at `d` (a canal surface's offsets are the +/// canal surfaces of its spine with the radii moved). +fn node_certificate( + row: &Frame, + r: &dyn Fn(f64) -> (f64, f64), + p: Vec3, + range: (f64, f64), + lb: &LawBounds, + interior: bool, + cell: Option, +) -> Result { + const EPS: f64 = 1e-9; + let w = row.na + row.nb; + let err = lb.psi_err(p); + let c1 = lb.c1(); + // (psi, rho) at s + let at = |s: f64| { + let (rs, _) = r(s); + let rho = (p - (row.origin + row.e * s + w * rs)).length(); + (rho - rs, rho) + }; + // the interval's `m`, from its ends' `rho` + let m_of = |a: Sample, b: Sample| { + let rho_lo = 0.5 * (a.2 + b.2) - c1 * (b.0 - a.0) / 2.0 - 2.0 * err; + lb.psi_ss(rho_lo) + }; + let drop_below = |a: Sample, b: Sample, level: f64| { + let h = b.0 - a.0; + let bound = a.1.min(b.1) - err - m_of(a, b) * h * h / 8.0 * (1.0 + gamma(8)); + bound >= level + }; + let n = 64; + let h = (range.1 - range.0) / f64::from(n); + let samples: Vec = (0..=n) + .map(|i| { + let s = if i == n { + range.1 + } else { + range.0 + h * f64::from(i) + }; + let (f, rho) = at(s); + (s, f, rho) + }) + .collect(); + let (mut t0, mut best) = samples + .iter() + .fold((range.0, f64::INFINITY), |acc, &(s, v, _)| { + if v < acc.1 { + (s, v) + } else { + acc + } + }); + let mut stack: Vec<(Sample, Sample)> = samples.windows(2).map(|x| (x[0], x[1])).collect(); + let mut evaluations = 0usize; + while let Some((a, b)) = stack.pop() { + if drop_below(a, b, best - EPS - err) { + continue; + } + let c = 0.5 * (a.0 + b.0); + let (fc, rho_c) = at(c); + evaluations += 1; + if evaluations > 200_000 || b.0 - a.0 < 1e-12 { + return Err("uncertified: the distance search did not close".into()); + } + if fc < best { + (t0, best) = (c, fc); + } + stack.push((a, (c, fc, rho_c))); + stack.push(((c, fc, rho_c), b)); + } + if interior && !(t0 > range.0 + h && t0 < range.1 - h) { + return Err("the nearest ball is at the range's end".into()); + } + let (lo, hi) = (best - EPS - 2.0 * err, best + err); + let Some(d) = cell else { + return Ok(NodeCert { lo, hi, t0 }); + }; + + // the nearest ball of every point within `d` lies in `I0` + let rho0 = best + r(t0).0; + let delta = (8.0 * rho0 * (2.0 * d + 1e-9)).sqrt(); + let (ia, ib) = (t0 - delta, t0 + delta); + if !(ia > range.0 && ib < range.1) { + return Err("the nearest ball's neighbourhood leaves the range".into()); + } + let threshold = hi + 2.0 * d + err; + let mut outside: Vec = samples + .iter() + .copied() + .filter(|x| x.0 < ia || x.0 > ib) + .collect(); + for s in [ia, ib] { + let (f, rho) = at(s); + outside.push((s, f, rho)); + } + outside.sort_by(|x, y| x.0.total_cmp(&y.0)); + let mut stack: Vec<(Sample, Sample)> = outside + .windows(2) + .filter(|x| !(x[0].0 < ib && x[1].0 > ia)) + .map(|x| (x[0], x[1])) + .collect(); + while let Some((a, b)) = stack.pop() { + if drop_below(a, b, threshold) { + continue; + } + let c = 0.5 * (a.0 + b.0); + let (fc, rho_c) = at(c); + evaluations += 1; + if evaluations > 400_000 || b.0 - a.0 < 1e-9 { + return Err("uncertified: a second ball is as near".into()); + } + stack.push((a, (c, fc, rho_c))); + stack.push(((c, fc, rho_c), b)); + } + + // strict convexity on `I0` for every point within `d` + let (rt, drt) = r(t0); + let cpt = row.origin + row.e * t0 + w * rt; + let cd = row.e + w * drt; + let u = (p - cpt) * (1.0 / rho0); + let psi_s0 = -u.dot(cd) - drt; + let rho_min = rho0 - c1 * delta - d - 2.0 * err; + let rho_max = rho0 + c1 * delta + d + 2.0 * err; + if rho_min <= 0.0 { + return Err("uncertified: a ball's centre too near".into()); + } + // `psi_s0`'s rounding: `u` is `p - c(t0)` (each coordinate within `err`) over `rho0` + // (within `2 err`), so `|u - u_true| <= 4 err / rho0` (`|u| <= 1 + that`), times `|c'| <= c1` + // in the dot product; the dot product and the sum add `gamma(32) (c1 + |r'| + 1)` + let psi_s0_err = 4.0 * err / rho_min * c1 + gamma(32) * (c1 + lb.r1 + 1.0); + let big_p = (psi_s0.abs() + psi_s0_err) + lb.psi_ss(rho_min) * delta + c1 / rho_min * d; + let convex = ((1.0 - 2.0 * big_p * big_p) / rho_max - (1.0 + 2.0_f64.sqrt()) * lb.r2) + * (1.0 - gamma(16)); + if convex <= 0.0 { + return Err(format!("uncertified: psi_ss lower bound {convex}")); + } + Ok(NodeCert { lo, hi, t0 }) +} + +/// A knot-span patch of the skin's control net, evaluated without the kernel +/// (Cox-de Boor on the span's nonzero basis functions). +struct Patch { + span: [usize; 2], + degrees: [usize; 2], + /// The span's `(p + 1) x (q + 1)` homogeneous control points. + hom: Vec<[f64; 4]>, +} + +impl Patch { + fn new(net: &[[f64; 4]], nv: usize, degrees: [usize; 2], span: [usize; 2]) -> Self { + let [p, q] = degrees; + let [i, j] = span; + let mut hom = Vec::new(); + for a in i - p..=i { + for b in j - q..=j { + // (the net's points are stored weighted: `(w x, w y, w z, w)`) + hom.push(net[a * nv + b]); + } + } + Self { span, degrees, hom } + } + + /// The `deg + 1` basis functions nonzero on span `i` at `x` (The NURBS Book, A2.2). + fn basis(kn: &[f64], i: usize, deg: usize, x: f64) -> Vec { + let mut n = vec![0.0_f64; deg + 1]; + let mut left = vec![0.0_f64; deg + 1]; + let mut right = vec![0.0_f64; deg + 1]; + n[0] = 1.0; + for j in 1..=deg { + left[j] = x - kn[i + 1 - j]; + right[j] = kn[i + j] - x; + let mut saved = 0.0; + for r in 0..j { + let temp = n[r] / (right[r + 1] + left[j - r]); + n[r] = saved + right[r + 1] * temp; + saved = left[j - r] * temp; + } + n[j] = saved; + } + n + } + + fn eval(&self, knots: [&[f64]; 2], u: f64, v: f64) -> Vec3 { + let [p, q] = self.degrees; + let bu = Self::basis(knots[0], self.span[0], p, u); + let bv = Self::basis(knots[1], self.span[1], q, v); + let mut acc = [0.0_f64; 4]; + for (a, nu) in bu.iter().enumerate() { + for (b, nv) in bv.iter().enumerate() { + let c = self.hom[a * (q + 1) + b]; + for (x, y) in acc.iter_mut().zip(c) { + *x += nu * nv * y; + } + } + } + Vec3::new(acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3]) + } +} + +/// A patch of the certification and its cells: `(start, end, count)` each way, its +/// derivative bounds and the rounding of its evaluation. +struct Work { + patch: Patch, + u: (f64, f64, usize), + v: (f64, f64, usize), + /// `max |S_u|`, `max |S_uu|`, `max |S_v|`, `max |S_vv|` on the patch, rounding included. + derivs: [f64; 4], + /// The rounding of the patch's evaluation. + eps_s: f64, +} + +/// Past this many cells a row is uncertified (its run would take hours). +const CELL_CAP: usize = 600_000_000; + +/// The rail offset's certified supremum is the best value found plus this. +const W_EPS: f64 = 1e-9; + +/// Certifies that each moved row's round face lies within T of its balls' envelope (G2), +/// and computes the bound an argument gives for the other direction (G3, argued, not +/// certified). +/// +/// G2. The deviation is `f = phi o S`, `S` the face's surface and `phi` the signed distance +/// to the envelope ([`node_certificate`]). On a cell `[u0, u0 + h_u] x [v0, v0 + h_v]`, +/// `|f| <= max |f(corners)| + h_u^2 / 8 max |f_uu| + h_v^2 / 8 max |f_vv|` (the bilinear +/// interpolant's remainder), with `|f_uu| <= |S_uu| + K |S_u|^2` (`|grad phi| = 1`, +/// `|hess phi| <= K`). `S_u`, `S_uu` are bounded per knot-span patch from the control net +/// ([`patch_bounds`]). Each node's certificate shows that every point within the cell's +/// reach `d` (its diameter plus the node's evaluation error) has a unique, nondegenerate +/// nearest ball, so `phi` is twice differentiable on the cell. `K` comes from the law in +/// closed form: at the nearest ball `t*`, `hess phi = hess_p psi - m m^T / psi_tt` +/// (`psi = |p - c(t)| - r(t)`, `m = d/dt grad_p psi`), `|hess_p psi| = 1 / rho`, +/// `|m|^2 = (1 + r'^2) / rho^2` and `psi_tt >= 1 / rho_max - |r''| (1 + sqrt 2) > 0`, with +/// `rho` bounded per cell a priori from `|phi| <= min |phi(corners)| + d` (1-Lipschitz), +/// never from the result. The ranges of `r`, `r'`, `r''` over the balls' positions come from +/// the law's polynomial ([`poly_range`]). Every bound carries its rounding +/// ([`LawBounds::psi_err`], the patch evaluation's `eps_s`, and `gamma` factors). Every +/// cell of the face's whole uv box is covered (its boundary and rails too, no point +/// classified away). The skin is evaluated from its control net ([`Patch`], checked against +/// the kernel at each patch's middle). The cells are sized from a coarse estimate of the +/// largest distance, a third of the margin to T each way; past 600M cells the row is +/// uncertified and fails. +/// +/// The smooth-g2 and reversed rows build the same face, control net, knots and uv domain as +/// the smooth-4-2-4 and sub-range rows (asserted), so four rows are certified. +/// The face's u runs along the edge and v across it (asserted). The law runs from the +/// edge's start. For the rows whose law is not symmetric the reversed law is far off +/// (asserted); the smooth-4-2-4 law is symmetric, so its orientation cannot be told apart. +/// +/// Also certified: how far the rails lie off their planes (`h_rail`, from the rail +/// columns' control points), and how far they lie off the law's contact lines (`w`, by a +/// 1-D branch and bound; reported, #15600). +/// +/// G3, argued given premises P1 to P3, not certified: the bound on the distance from the true +/// round to the body that the argument in the code gives (see the comment there, which also +/// names a step that does not hold in general). P1 is asserted at the nodes only, P2 is not +/// checked, and P3 rests on the measured column: the distance from the true round (the touch +/// arcs between the feet inside the box) to the body's boundary by closest points. +#[test] +#[ignore = "proof run for #15257 (about 47 minutes on 8 threads): the certified skin-to-envelope bound"] +fn certify_the_moved_rows_skins_within_t() { + use solidcore::geom::vector2d::Point2; + use solidcore::nurbs::b_spline_surface::p1::SurfParamType; + // the smooth-g2 and reversed rows build the same round face as the rows certified + let net_of = |c: &LawCase| { + let row = build_row(c); + let rounds: Vec<_> = row + .body + .faces() + .ids() + .filter(|&f| { + face::surface(&row.body, f) + .unwrap() + .is_some_and(|s| !matches!(s.kind(), SurfaceKind::Plane(_))) + }) + .collect(); + assert_eq!(rounds.len(), 1, "{}: one round face", c.name); + let srf = face::surface(&row.body, rounds[0]) + .unwrap() + .unwrap() + .clone(); + let dom = face::uv_domain(&row.body, rounds[0]).unwrap(); + let SurfaceKind::BSpline(bs) = srf.kind() else { + panic!("{}: the round is not a B-spline", c.name) + }; + let (nu, nv, pts) = bs.control_points().unwrap(); + let pts: Vec<[f64; 4]> = pts.iter().map(|p| [p.x, p.y, p.z, p.w]).collect(); + ( + nu, + nv, + pts, + bs.knots(SurfParamType::U, None).unwrap(), + bs.knots(SurfParamType::V, None).unwrap(), + [dom.min().x, dom.min().y, dom.max().x, dom.max().y], + ) + }; + for (a, b) in [(1, 0), (5, 4)] { + assert!( + net_of(&MOVED_ROWS[a]) == net_of(&MOVED_ROWS[b]), + "{} differs from {}", + MOVED_ROWS[a].name, + MOVED_ROWS[b].name + ); + } + for c in MOVED_ROWS + .iter() + .filter(|c| !c.name.ends_with("smooth-g2") && !c.name.ends_with("reversed")) + { + let row = build_row(c); + let t = 4.0 * row.tol; + let r = row.law(false); + let range = (-0.25 * row.len, 1.25 * row.len); + // the law's exact ranges over the balls' positions + let ua = row.m0 + row.slope * range.0; + let ub = row.m0 + row.slope * range.1; + let (ua, ub) = (ua.min(ub), ua.max(ub)); + let (r_lo, r_hi) = poly_range(row.poly, ua, ub); + let d1 = poly_range(derivative(row.poly), ua, ub); + let d2 = poly_range(derivative(derivative(row.poly)), ua, ub); + let r1 = d1.0.abs().max(d1.1.abs()) * row.slope.abs(); + let r2 = d2.0.abs().max(d2.1.abs()) * row.slope * row.slope; + // (the ranges come from the polynomial's coefficients and roots in a few dozen + // rounded operations: widened by gamma(64) of the magnitudes) + let widen = gamma(64) * (r_hi.abs() + 10.0); + let lb = LawBounds { + r_lo: r_lo - widen, + r_hi: r_hi + widen, + r1: r1 * (1.0 + gamma(64)) + widen, + r2: r2 * (1.0 + gamma(64)) + widen, + scale: row + .origin + .x + .abs() + .max(row.origin.y.abs()) + .max(row.origin.z.abs()) + + range.0.abs().max(range.1.abs()) + + 3.0 * (r_hi + widen) + + 1.0, + }; + let (r_lo, r_hi, r1, r2) = (lb.r_lo, lb.r_hi, lb.r1, lb.r2); + // `K`, the bound on `|hess phi|`, for a cell where `|phi| <= big_phi` (a-priori, from the + // cell's corners): at the nearest ball `t*`, `hess phi = hess_p psi - m m^T / psi_tt`, + // `|hess_p psi| = 1 / rho`, `|m|^2 = (1 + r'^2) / rho^2`, + // `psi_tt = (1 + r'^2) / rho - r'' (1 + u.w) >= 1 / rho_max - |r''| (1 + sqrt 2)`, with + // `rho = phi + r(t*)` in `[r_lo - big_phi, r_hi + big_phi]` + let k_of = |big_phi: f64| -> Option { + let (rho_lo, rho_hi) = (r_lo - big_phi, r_hi + big_phi); + let psi_tt = 1.0 / rho_hi - r2 * (1.0 + 2.0_f64.sqrt()); + (rho_lo > 0.0 && psi_tt > 0.0).then(|| { + (1.0 / rho_lo + (1.0 + r1 * r1) / (rho_lo * rho_lo * psi_tt)) * (1.0 + gamma(16)) + }) + }; + // (for sizing the cells only) + let kk = k_of(1e-3).unwrap(); + + let rounds: Vec<_> = row + .body + .faces() + .ids() + .filter(|&f| { + face::surface(&row.body, f) + .unwrap() + .is_some_and(|s| !matches!(s.kind(), SurfaceKind::Plane(_))) + }) + .collect(); + assert_eq!(rounds.len(), 1, "{}: one round face", c.name); + let face = rounds[0]; + let srf = face::surface(&row.body, face).unwrap().unwrap().clone(); + let SurfaceKind::BSpline(bs) = srf.kind() else { + panic!("{}: the round is not a B-spline", c.name) + }; + let dom = face::uv_domain(&row.body, face).unwrap(); + let (u0, u1, v0, v1) = (dom.min().x, dom.max().x, dom.min().y, dom.max().y); + let k = &row.k; + let eval = |u: f64, v: f64| { + let p = srf.evaluate_point(k, Point2::new(u, v)).unwrap(); + Vec3::new(p.x, p.y, p.z) + }; + // u runs along the edge, v across it + let vm = 0.5 * (v0 + v1); + let um = 0.5 * (u0 + u1); + let along_u = (eval(u1, vm) - eval(u0, vm)).dot(row.e).abs(); + let along_v = (eval(um, v1) - eval(um, v0)).dot(row.e).abs(); + assert!( + along_u > 10.0 * along_v, + "{}: u does not run along the edge", + c.name + ); + + // the control net, its layout checked against the kernel's evaluation + let (nu, nv, pts) = bs.control_points().unwrap(); + let net: Vec<[f64; 4]> = pts + .iter() + .map(|p| { + if p.w == solidcore::nurbs::math::NOW { + [p.x, p.y, p.z, 1.0] + } else { + [p.x, p.y, p.z, p.w] + } + }) + .collect(); + let (pu, pv) = (bs.degree(SurfParamType::U), bs.degree(SurfParamType::V)); + let (kud, kum) = bs.knots(SurfParamType::U, None).unwrap(); + let (kvd, kvm) = bs.knots(SurfParamType::V, None).unwrap(); + let (ku, kv) = (full_knots(&kud, &kum), full_knots(&kvd, &kvm)); + assert_eq!(ku.len(), nu + pu + 1); + assert_eq!(kv.len(), nv + pv + 1); + let de_boor = |u: f64, v: f64| { + let basis = |kn: &[f64], deg: usize, n: usize, x: f64| -> Vec { + // Cox-de Boor, all n functions at x (the last span closed) + let m = kn.len() - 1; + let mut nb: Vec = (0..m) + .map(|i| { + let last = x >= kn[m] && kn[i] < kn[i + 1] && kn[i + 1] >= kn[m]; + if (kn[i] <= x && x < kn[i + 1]) || last { + 1.0 + } else { + 0.0 + } + }) + .collect(); + for d in 1..=deg { + for i in 0..m - d { + let a = if kn[i + d] > kn[i] { + (x - kn[i]) / (kn[i + d] - kn[i]) * nb[i] + } else { + 0.0 + }; + let b = if kn[i + d + 1] > kn[i + 1] { + (kn[i + d + 1] - x) / (kn[i + d + 1] - kn[i + 1]) * nb[i + 1] + } else { + 0.0 + }; + nb[i] = a + b; + } + } + nb.truncate(n); + nb + }; + let (bu, bv) = (basis(&ku, pu, nu, u), basis(&kv, pv, nv, v)); + let mut acc = [0.0; 4]; + for a in 0..nu { + for b in 0..nv { + let wgt = bu[a] * bv[b]; + for (x, y) in acc.iter_mut().zip(net[a * nv + b]) { + *x += wgt * y; + } + } + } + Vec3::new(acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3]) + }; + for (fu, fv) in [(0.1, 0.2), (0.5, 0.5), (0.9, 0.7), (0.33, 0.95)] { + let (u, v) = (u0 + fu * (u1 - u0), v0 + fv * (v1 - v0)); + let off = (de_boor(u, v) - eval(u, v)).length(); + assert!(off < 1e-9, "{}: control net layout ({off})", c.name); + } + + let frame = row.frame(); + let distance = |p: Vec3| { + let n = node_certificate(&frame, &r, p, range, &lb, true, None) + .unwrap_or_else(|e| panic!("{}: {e}", c.name)); + n.lo.abs().max(n.hi.abs()) + }; + + // the cells' size: a third of the margin to T each way, from a coarse estimate of + // the largest distance (this sizes the cells only; the bound is the certificate's) + let mut estimate = 0.0_f64; + for a in 0..=80 { + for b in 0..=10 { + let p = eval( + u0 + (u1 - u0) * f64::from(a) / 80.0, + v0 + (v1 - v0) * f64::from(b) / 10.0, + ); + estimate = estimate.max(distance(p)); + } + } + let budget = (t - 1.05 * estimate) / 3.0; + assert!( + budget > 0.0, + "{}: uncertified: estimated distance {estimate} leaves no margin to T {t}", + c.name + ); + + // the patches over the face's uv box, each checked against the kernel's evaluation + let spans = |kn: &[f64], deg: usize, lo: f64, hi: f64| -> Vec<(usize, f64, f64)> { + (deg..kn.len() - deg - 1) + .filter(|&i| kn[i + 1] > kn[i] && kn[i + 1] > lo && kn[i] < hi) + .map(|i| (i, kn[i].max(lo), kn[i + 1].min(hi))) + .collect() + }; + let mut work = Vec::new(); + let mut total = 0usize; + for &(i, ua_, ub_) in &spans(&ku, pu, u0, u1) { + for &(j, va_, vb_) in &spans(&kv, pv, v0, v1) { + let pb = patch_bounds(&net, nv, [&ku, &kv], [pu, pv], [i, j]); + let muu = pb.suu + kk * pb.su * pb.su; + let mvv = pb.svv + kk * pb.sv * pb.sv; + let n_u = (((ub_ - ua_) * (muu / (8.0 * budget)).sqrt()).ceil() as usize).max(1); + let n_v = (((vb_ - va_) * (mvv / (8.0 * budget)).sqrt()).ceil() as usize).max(1); + let patch = Patch::new(&net, nv, [pu, pv], [i, j]); + let (um_, vm_) = (0.5 * (ua_ + ub_), 0.5 * (va_ + vb_)); + let off = (patch.eval([&ku, &kv], um_, vm_) - eval(um_, vm_)).length(); + assert!(off < 1e-9, "{}: patch evaluation ({off})", c.name); + total = total.saturating_add(n_u.saturating_mul(n_v)); + // the patch's evaluation error (the span's basis functions by A2.2, a weighted + // sum of (p + 1) (q + 1) terms and a division: within gamma(4 (p + q) + 32) + // of `|P|_inf w_max / w_min` per coordinate) and its derivative bounds widened by + // their rounding (a few dozen operations each) + let (mut w_min, mut w_max, mut big) = (f64::INFINITY, 0.0_f64, 0.0_f64); + for h in &patch.hom { + w_min = w_min.min(h[3]); + w_max = w_max.max(h[3]); + big = big + .max((h[0] / h[3]).abs()) + .max((h[1] / h[3]).abs()) + .max((h[2] / h[3]).abs()); + } + let eps_s = gamma(4 * (pu + pv) + 32) * 4.0 * big * (w_max / w_min); + let up = 1.0 + gamma(64); + work.push(Work { + patch, + u: (ua_, ub_, n_u), + v: (va_, vb_, n_v), + derivs: [pb.su * up, pb.suu * up, pb.sv * up, pb.svv * up], + eps_s, + }); + } + } + eprintln!( + "CELLS {}: {} patches, {total} cells, budget {budget:.2e} each way (estimate {estimate:.3e})", + c.name, + work.len() + ); + assert!( + total <= CELL_CAP, + "{}: uncertified: budget exceeded ({total} cells > {CELL_CAP})", + c.name + ); + + // every node's distance, the patches shared among 8 threads + let next = AtomicUsize::new(0); + let done = AtomicUsize::new(0); + let running = AtomicU64::new(0); // the certified bound so far (non-negative f64 bits) + let (knots_u, knots_v) = (&ku[..], &kv[..]); + let results: Vec<(f64, f64, usize, usize, f64)> = std::thread::scope(|scope| { + let handles: Vec<_> = (0..8) + .map(|_| { + scope.spawn(|| { + let (mut node_max, mut certified, mut nodes, mut cells) = + (0.0_f64, 0.0_f64, 0usize, 0usize); + let mut front_max = f64::NEG_INFINITY; + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(wk) = work.get(i) else { break }; + let ((ua_, ub_, n_u), (va_, vb_, n_v)) = (wk.u, wk.v); + let (hu, hv) = ((ub_ - ua_) / n_u as f64, (vb_ - va_) / n_v as f64); + let [su, suu, sv, svv] = wk.derivs; + // a cell's reach from its computed node: `|S(u, v) - S(u0, v0)| <= + // |S_u| h_u + |S_v| h_v`, plus the node's evaluation error `eps_s` + // (the computed node is within `eps_s` of `S(u0, v0)`) + let d = (su * hu + sv * hv) * (1.0 + gamma(8)) + wk.eps_s; + // `|phi|` at a node, the evaluation's rounding added (`phi` is + // 1-Lipschitz); each node is the first corner of its cell, so its + // certificate covers every point within `d` + // (and on which side of its ball the point lies: past either foot when + // `max(u.na, u.nb) > 0`, `u` from the nearest ball's centre) + let node = |u: f64, v: f64| -> (f64, f64) { + let p = wk.patch.eval([knots_u, knots_v], u, v); + let n = node_certificate(&frame, &r, p, range, &lb, true, Some(d)) + .unwrap_or_else(|e| panic!("{}: node ({u}, {v}): {e}", c.name)); + let (rt, _) = r(n.t0); + let centre = frame.origin + frame.e * n.t0 + (frame.na + frame.nb) * rt; + let dir = (p - centre) * (1.0 / (p - centre).length()); + (n.lo.abs().max(n.hi.abs()) + wk.eps_s, dir.dot(frame.na).max(dir.dot(frame.nb))) + }; + let mut prev = vec![0.0_f64; n_v + 1]; + let mut cur = vec![0.0_f64; n_v + 1]; + let mut patch_max = 0.0_f64; + for a in 0..=n_u { + let u = if a == n_u { ub_ } else { ua_ + hu * a as f64 }; + for (b, slot) in cur.iter_mut().enumerate() { + let v = if b == n_v { vb_ } else { va_ + hv * b as f64 }; + let (value, side) = node(u, v); + *slot = value; + node_max = node_max.max(value); + front_max = front_max.max(side); + } + nodes += n_v + 1; + if a > 0 { + for b in 0..n_v { + let corners = [prev[b], prev[b + 1], cur[b], cur[b + 1]]; + let corner = corners.iter().copied().fold(0.0_f64, f64::max); + // a-priori: `|phi| <= |phi(corner)| + d` on the cell + let big_phi = corners.iter().copied().fold(f64::INFINITY, f64::min) + d; + let kc = k_of(big_phi).unwrap_or_else(|| { + panic!("{}: uncertified: no Hessian bound at |phi| <= {big_phi}", c.name) + }); + let rem = (hu * hu / 8.0 * (suu + kc * su * su) + + hv * hv / 8.0 * (svv + kc * sv * sv)) + * (1.0 + gamma(16)); + patch_max = patch_max.max((corner + rem) * (1.0 + gamma(4))); + } + cells += n_v; + } + std::mem::swap(&mut prev, &mut cur); + } + certified = certified.max(patch_max); + running.fetch_max(patch_max.to_bits(), Ordering::Relaxed); + done.fetch_add(1, Ordering::Relaxed); + } + (node_max, certified, nodes, cells, front_max) + }) + }) + .collect(); + // progress at least every 30 s, so a slow run is told from a stuck one + let start = std::time::Instant::now(); + let mut last = start; + while done.load(Ordering::Relaxed) < work.len() { + std::thread::sleep(std::time::Duration::from_millis(500)); + if last.elapsed().as_secs() >= 30 { + last = std::time::Instant::now(); + eprintln!( + "PROGRESS {}: {}/{} patches, running certified max {:.3e}, {} s", + c.name, + done.load(Ordering::Relaxed), + work.len(), + f64::from_bits(running.load(Ordering::Relaxed)), + start.elapsed().as_secs() + ); + } + } + handles.into_iter().map(|h| h.join().unwrap()).collect() + }); + let node_max = results.iter().map(|x| x.0).fold(0.0_f64, f64::max); + let certified = results.iter().map(|x| x.1).fold(0.0_f64, f64::max); + let nodes: usize = results.iter().map(|x| x.2).sum(); + let cells: usize = results.iter().map(|x| x.3).sum(); + let front_max = results + .iter() + .map(|x| x.4) + .fold(f64::NEG_INFINITY, f64::max); + assert_eq!(cells, total, "{}: every cell evaluated", c.name); + + // the reversed law, on a coarse grid + let reversed = row.law(true); + let mut reversed_max = 0.0_f64; + for a in 0..=60 { + for b in 0..=12 { + let p = eval( + u0 + (u1 - u0) * f64::from(a) / 60.0, + v0 + (v1 - v0) * f64::from(b) / 12.0, + ); + let n = node_certificate(&frame, &reversed, p, range, &lb, false, None) + .unwrap_or_else(|e| panic!("{}: reversed: {e}", c.name)); + reversed_max = reversed_max.max(n.lo.abs().max(n.hi.abs())); + } + } + + // The other way, true round to body (measured, not certified): each point of the + // touch arcs between the feet inside the box is within T of the body's boundary, the + // round face or a plane face. A plane face holds a point's projection when the + // projection is beyond the round face's rail on that plane. The distance to the + // round face is through the kernel's closest point on its surface, which never + // reports less than the true distance. + let on_plane = |v: f64, n: Vec3| (eval(um, v) - row.origin).dot(n).abs(); + let v_on = |n: Vec3| { + if on_plane(v0, n) < on_plane(v1, n) { + v0 + } else { + v1 + } + }; + // the rail on the plane of `n`: its distance from the other plane at `along` + let rail_across = |n: Vec3, other: Vec3, along: f64| { + let v = v_on(n); + let at_u = |u: f64| (eval(u, v) - row.origin).dot(row.e); + let rising = at_u(u1) > at_u(u0); + let (mut lo, mut hi) = (u0, u1); + for _ in 0..80 { + let mid = 0.5 * (lo + hi); + if (at_u(mid) < along) == rising { + lo = mid; + } else { + hi = mid; + } + } + (eval(lo, v) - row.origin).dot(other) + }; + let planes = [(row.na, row.nb), (row.nb, row.na)]; + let mut back = 0.0_f64; + for a in 0..=400 { + let s = -0.1 * row.len + 1.2 * row.len * f64::from(a) / 400.0; + for b in 0..=40 { + let (p, _) = touch_arc( + &r, + row.origin, + row.e, + row.na, + row.nb, + s, + f64::from(b) / 40.0, + ); + let along = (p - row.origin).dot(row.e); + if !(0.0..=row.len).contains(&along) { + continue; + } + let q = Point3::new(p.x, p.y, p.z); + let uv = surface_closest_point(k, &srf, q).unwrap().uvs[0]; + let mut d = srf.evaluate_point(k, uv).unwrap().distance(q); + for (n, other) in planes { + if (p - row.origin).dot(other) >= rail_across(n, other, along) { + d = d.min((p - row.origin).dot(n).abs()); + } + } + back = back.max(d); + } + } + // The rails against the law's contact lines: the foot on the plane of `n` is `r(s)` + // from the other plane, so the rail's offset is `g(u) = (R(u) - o).other - r(a(u))`, + // `a(u) = (R(u) - o).e`, along the face's boundary iso-curve `R` on that plane (the + // net's first or last column). Measured at 401 positions, and certified by branch + // and bound per u-span: `|g| <= max(|g(a)|, |g(b)|) + m h^2 / 8` on `[a, b]`, with + // `|g''| <= |R''| (1 + max|r'|) + max|r''| |R'|^2` from the span's control-net bounds. + let mut slip = 0.0_f64; + for a in 0..=2000 { + let s = row.len * f64::from(a) / 2000.0; + for (n, other) in planes { + slip = slip.max((rail_across(n, other, s) - r(s).0).abs()); + } + } + assert!( + (v0 - kv[0]).abs() < 1e-12 && (v1 - kv[kv.len() - 1]).abs() < 1e-12, + "{}: the face's v runs over the net's", + c.name + ); + let mut w_cert = 0.0_f64; + let mut rail_evaluations = 0usize; + for (n, other) in planes { + let column = if on_plane(v0, n) < on_plane(v1, n) { + 0 + } else { + nv - 1 + }; + for i in pu..nu { + let (lo_k, hi_k) = (ku[i], ku[i + 1]); + if !(hi_k > lo_k && hi_k > u0 && lo_k < u1) { + continue; + } + let (lo, hi) = (lo_k.max(u0), hi_k.min(u1)); + let hom: Vec<[f64; 4]> = (i - pu..=i).map(|m| net[m * nv + column]).collect(); + let at = |u: f64| { + let basis = Patch::basis(&ku, i, pu, u); + let mut acc = [0.0_f64; 4]; + for (nb, h) in basis.iter().zip(&hom) { + for (x, y) in acc.iter_mut().zip(h) { + *x += nb * y; + } + } + Vec3::new(acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3]) + }; + let mid = 0.5 * (lo + hi); + let off = (at(mid) - eval(mid, v_on(n))).length(); + assert!(off < 1e-9, "{}: rail evaluation ({off})", c.name); + // the span's first and second derivative bounds, as in `patch_bounds` + let pt = |h: [f64; 4]| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]); + let reference = pt(hom[0]); + let tr: Vec<[f64; 4]> = hom + .iter() + .map(|h| { + let x = pt(*h) - reference; + [x.x * h[3], x.y * h[3], x.z * h[3], h[3]] + }) + .collect(); + let w_min = hom.iter().map(|h| h[3]).fold(f64::INFINITY, f64::min); + assert!(w_min > 0.0, "a non-positive weight"); + let far = hom + .iter() + .map(|h| (pt(*h) - reference).length()) + .fold(0.0_f64, f64::max); + let first: Vec<[f64; 4]> = (0..pu) + .map(|k| { + let m = i - pu + k; + let den = ku[m + pu + 1] - ku[m + 1]; + let f = if den > 0.0 { pu as f64 / den } else { 0.0 }; + [0, 1, 2, 3].map(|q| (tr[k + 1][q] - tr[k][q]) * f) + }) + .collect(); + let second: Vec<[f64; 4]> = (0..pu.saturating_sub(1)) + .map(|k| { + let m = i - pu + k; + let den = ku[m + pu + 1] - ku[m + 2]; + let f = if den > 0.0 { + (pu - 1) as f64 / den + } else { + 0.0 + }; + [0, 1, 2, 3].map(|q| (first[k + 1][q] - first[k][q]) * f) + }) + .collect(); + let n3 = |d: &[f64; 4]| (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + let a1 = first.iter().map(n3).fold(0.0_f64, f64::max); + let w1 = first.iter().map(|d| d[3].abs()).fold(0.0_f64, f64::max); + let a2 = second.iter().map(n3).fold(0.0_f64, f64::max); + let w2 = second.iter().map(|d| d[3].abs()).fold(0.0_f64, f64::max); + let s1 = (a1 + far * w1) / w_min; + let s2 = (a2 + 2.0 * s1 * w1 + far * w2) / w_min; + let m = s2 * (1.0 + r1) + r2 * s1 * s1; + let g = |u: f64| { + let q = at(u) - row.origin; + q.dot(other) - r(q.dot(row.e)).0 + }; + // the rounding of a computed `g`: the rail's evaluation (as a patch's) and the + // law's ([`LawBounds::psi_err`] covers it) + let (mut cw_min, mut cw_max, mut cbig) = (f64::INFINITY, 0.0_f64, 0.0_f64); + for h in &hom { + cw_min = cw_min.min(h[3]); + cw_max = cw_max.max(h[3]); + cbig = cbig + .max((h[0] / h[3]).abs()) + .max((h[1] / h[3]).abs()) + .max((h[2] / h[3]).abs()); + } + let err_g = gamma(4 * pu + 32) * 4.0 * cbig * (cw_max / cw_min) * (1.0 + r1) + + lb.psi_err(at(mid)); + let samples: Vec<(f64, f64)> = (0..=16) + .map(|k| { + let u = if k == 16 { + hi + } else { + lo + (hi - lo) * f64::from(k) / 16.0 + }; + (u, g(u)) + }) + .collect(); + let mut best = samples.iter().map(|x| x.1.abs()).fold(0.0_f64, f64::max); + let mut stack: Vec<((f64, f64), (f64, f64))> = + samples.windows(2).map(|x| (x[0], x[1])).collect(); + while let Some(((ua_, ga), (ub_, gb))) = stack.pop() { + let h = ub_ - ua_; + if ga.abs().max(gb.abs()) + m * h * h / 8.0 * (1.0 + gamma(8)) + err_g + <= best + W_EPS + { + continue; + } + let um_ = 0.5 * (ua_ + ub_); + let gm = g(um_); + rail_evaluations += 1; + assert!( + rail_evaluations < 20_000_000, + "{}: uncertified: the rail search did not close", + c.name + ); + best = best.max(gm.abs()); + stack.push(((ua_, ga), (um_, gm))); + stack.push(((um_, gm), (ub_, gb))); + } + w_cert = w_cert.max(best + W_EPS + err_g); + } + } + // The true round within T of the body (G3): ARGUED, not certified. The steps below are + // prose, and they rest on premises this test does not certify: P1, each skin point's + // nearest ball direction lies on the front arc between the feet (asserted only at the + // nodes, below); P2, near its rails the round face is a graph over the plane (not + // checked); P3, near the box's end planes the end faces close the body (only the + // sampled `back` column). The second step also takes the arc's crossing with the + // projected rail as the nearest point of the body, which is not so in general. The + // code computes the bound the argument gives. `eps` is the certified bound above; + // every skin point is within it of the envelope. + // - The rails lie on their planes within `h_rail`: the rail is the net's first or last + // column, a rational curve with positive weights inside its control points' hull. + // - A point of the true round near plane a whose projection onto the plane is beyond + // the rail is above the plane face by at most the height of the arc's crossing `Q` + // with the projected rail: on a ball tangent to the plane at its foot `F`, the height + // is `|X - F|^2 / (2 r)`, which grows along the arc from `F`, and `Q` is within `eps` + // of a rail point, so its height is at most `h_rail + eps`. + // - Otherwise the skin lies over the point's projection: the vertical through it meets + // the skin at `S*`, and along that vertical `phi` changes at least as fast as + // `cos = (r_lo - h) / (r_lo + eps)`, `h` the greatest height on the segment (the + // gradient of `phi` is the unit vector from the nearest ball's centre). So + // `|S* - P| <= eps / cos`, solved with `h = h_rail + eps + |S* - P|`. + // - Elsewhere every point of the true round is the projection of a skin point, at its + // distance `|phi| <= eps`. + let mut h_rail = 0.0_f64; + for (n, _) in planes { + let column = if on_plane(v0, n) < on_plane(v1, n) { + 0 + } else { + nv - 1 + }; + for a in 0..nu { + let h = net[a * nv + column]; + let x = Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]); + h_rail = h_rail.max((x - row.origin).dot(n).abs() + lb.psi_err(x)); + } + } + let eps = certified; + let mut slide = 2.0 * eps; + for _ in 0..4 { + let height = h_rail + eps + slide; + let cos = (r_lo - height) / (r_lo + eps); + // (from `r_lo` and the heights only; it does not check P2) + assert!(cos > 0.5, "{}: the vertical's slope bound {cos}", c.name); + let next = eps / cos * (1.0 + gamma(8)); + assert!( + next <= slide, + "{}: the vertical bound does not close", + c.name + ); + slide = next; + } + let g3 = eps.max(h_rail + eps).max(slide) * (1.0 + gamma(4)); + assert!(g3 < t, "{}: true round to body {g3}", c.name); + + eprintln!( + "CERT {}: K {kk:.4}, {cells} cells ({nodes} nodes); nodes max {node_max:.3e}; certified max {certified:.3e} < T {t:.1e}; reversed law {reversed_max:.3e}; true round to body: argued given P1 to P3 {g3:.4e} (rails off their planes, certified, {h_rail:.1e}), measured {back:.3e}; rails off the contact lines: measured {slip:.3e}, certified {w_cert:.4e} ({rail_evaluations} evaluations); P1 at the nodes: max(u.na, u.nb) {front_max:.2e}", + c.name + ); + assert!( + certified < t, + "{}: certified {certified} not below T {t}", + c.name + ); + let symmetric = c.radii.iter().eq(c.radii.iter().rev()) + && (row.m0 + row.slope * row.len / 2.0 - 0.5).abs() < 1e-12; + if !symmetric { + assert!( + reversed_max > 10.0 * t, + "{}: the reversed law is {reversed_max} off", + c.name + ); + } + assert!(back < t, "{}: true round to body {back}", c.name); + // P1 at the nodes only: past a foot by an angle `theta` (`max(u.na, u.nb) = sin theta`) + // the nearest point leaves the front arc; between the nodes this is not certified + assert!( + front_max <= 1e-3, + "{}: P1: a node's nearest ball direction is past a foot ({front_max})", + c.name + ); + } } diff --git a/solidcore/plan/panic-sites.tsv b/solidcore/plan/panic-sites.tsv index 2933d790bc6..0707355c37b 100644 --- a/solidcore/plan/panic-sites.tsv +++ b/solidcore/plan/panic-sites.tsv @@ -338,9 +338,15 @@ crates/solidcore/src/blend/fillet_geom/tangent_end_rib.rs tangent_end_rib Vec::i crates/solidcore/src/blend/fillet_geom/tangent_end_rib.rs tangent_end_rib Vec::insert 3 open insert(at, uv) crates/solidcore/src/blend/fillet_geom/tangent_end_rib.rs tangent_end_rib Vec::insert 4 open insert(at, exact) crates/solidcore/src/blend/fillet_geom/tangent_end_rib.rs tangent_end_rib int-rem 1 proven order % 2 constant non-zero divisor -crates/solidcore/src/blend/fillet_intersector.rs FilletIntersector::flush_curve Vec::insert 1 open insert(j + 1, split_knot) -crates/solidcore/src/blend/fillet_intersector.rs FilletIntersector::flush_curve Vec::insert 2 open insert(j + 1, mid_pnt) -crates/solidcore/src/blend/fillet_intersector.rs FilletIntersector::flush_curve windows 1 proven windows(2) constant non-zero size +crates/solidcore/src/blend/fillet_intersector.rs FilletIntersector::equalise_spans Vec::insert 1 proven insert(j + 1, split_knot) j + 1 < knots.len() by the loop condition +crates/solidcore/src/blend/fillet_intersector.rs FilletIntersector::equalise_spans Vec::insert 2 proven insert(j + 1, mid_pnt) pnts.get(j + 1) succeeded just above, so j + 1 < pnts.len() +crates/solidcore/src/blend/fillet_intersector.rs FilletIntersector::build_flush_geometry windows 1 proven windows(2) constant non-zero size +crates/solidcore/src/blend/fillet_intersector/skin_bound.rs BallFamily::nearest f64::clamp 1 proven clamp(lo, hi) range is [lo, hi] with lo < hi: BallFamily::through returns None unless above(hi, lo), which a NaN fails +crates/solidcore/src/blend/fillet_intersector/skin_bound.rs BallFamily::piece_bound f64::clamp 1 proven clamp(lo, hi) range is [lo, hi] with lo < hi: BallFamily::through returns None unless above(hi, lo), which a NaN fails +crates/solidcore/src/blend/fillet_intersector/skin_bound.rs BallFamily::radius_vanishes_on f64::clamp 1 proven clamp(lo, hi) range is [lo, hi] with lo < hi: BallFamily::through returns None unless above(hi, lo), which a NaN fails +crates/solidcore/src/blend/fillet_intersector/skin_bound.rs BallFamily::radius_vanishes_on f64::clamp 2 proven clamp(lo, hi) range is [lo, hi] with lo < hi: BallFamily::through returns None unless above(hi, lo), which a NaN fails +crates/solidcore/src/blend/fillet_intersector/skin_bound.rs BallFamily::through with_capacity 1 proven Vec::with_capacity(nodes.len()) n = nodes.len(), an existing slice (at most five balls); f64 is no larger than a Ball +crates/solidcore/src/blend/fillet_intersector/skin_bound.rs linear_through Ord::clamp 1 proven clamp(1, n.saturating_sub(1).max(1)) min 1 <= max, which is at least 1 crates/solidcore/src/blend/fillet_outline.rs decide with_capacity 1 proven Vec::with_capacity(2) constant capacity crates/solidcore/src/blend/fillet_outline.rs decide with_capacity 2 proven Vec::with_capacity(2) constant capacity crates/solidcore/src/blend/fillet_outline.rs decide with_capacity 3 proven Vec::with_capacity(2) constant capacity