1pub use crate::{
2 interpolate_curve, project_point_to_surface, project_point_to_surface_seeded, AnalyticSurface,
3 DiagnosticSeverity, KernelDiagnostics, KernelStage, KnotVector, NurbsCurve, NurbsSurface, Vec3,
4 Vec4, KNOT_IDENTITY_TOL,
5};
6
7const EPSILON: f64 = crate::tolerance::FP_FLOOR;
8const LINEAR_TOLERANCE: f64 = crate::tolerance::DEFAULT_MODEL;
9
10struct PcurvePhaseClock {
12 started: Option<web_time::Instant>,
13 phase: &'static str,
14 samples: usize,
15 tracking: bool,
16}
17impl PcurvePhaseClock {
18 fn new(phase: &'static str, samples: usize, tracking: bool) -> Self {
19 Self { started: crate::profile::profile_enabled().then(web_time::Instant::now), phase, samples, tracking }
20 }
21}
22impl Drop for PcurvePhaseClock {
23 fn drop(&mut self) {
24 if let Some(started) = self.started {
25 crate::profile::profile_emit(format_args!("pcurve.phase_time phase={} initial_samples={} tracking={} ms={:.3}", self.phase, self.samples, self.tracking, started.elapsed().as_secs_f64()*1000.0));
26 }
27 }
28}
29
30pub fn surface_domains(surface: &NurbsSurface) -> Result<([f64; 2], [f64; 2]), String> {
31 Ok((
32 KnotVector::new(surface.knots_u.clone(), surface.degree_u)?.domain(),
33 KnotVector::new(surface.knots_v.clone(), surface.degree_v)?.domain(),
34 ))
35}
36
37fn surface_closedness(surface: &NurbsSurface) -> Result<(bool, bool), String> {
44 surface.closed_directions()
45}
46
47thread_local! {
48 static PCURVE_REJECT_BOUNDS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
49}
50struct PcurveRejectScope(bool);
51impl PcurveRejectScope {
52 fn open(enabled: bool) -> Self {
53 Self(PCURVE_REJECT_BOUNDS.with(|state| state.replace(enabled)))
54 }
55}
56impl Drop for PcurveRejectScope {
57 fn drop(&mut self) { PCURVE_REJECT_BOUNDS.with(|state| state.set(self.0)); }
58}
59
60thread_local! {
61 static PCURVE_STACK_POINT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
62}
63pub struct PcurveStackPointScope(bool);
64impl PcurveStackPointScope {
65 pub fn open(enabled: bool) -> Self { Self(PCURVE_STACK_POINT.with(|state| state.replace(enabled))) }
66}
67impl Drop for PcurveStackPointScope {
68 fn drop(&mut self) { PCURVE_STACK_POINT.with(|state| state.set(self.0)); }
69}
70
71#[cfg_attr(feature = "profile-wall", track_caller)]
78pub fn section_extended_point(surface: &NurbsSurface, u: f64, v: f64, enabled: bool) -> Result<Vec3, String> {
79 let _reader = crate::reader_profile::Point::open(crate::reader_profile::SURFACE, std::panic::Location::caller());
80 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
81 if enabled && u.is_finite() && v.is_finite()
82 && surface.degree_u <= crate::curve::MAX_STACK_DEGREE
83 && surface.degree_v <= crate::curve::MAX_STACK_DEGREE {
84 let [u0,u1] = surface.domain_u()?;
85 let [v0,v1] = surface.domain_v()?;
86 let mut uu = u;
87 let mut vv = v;
88 if u < u0 || u > u1 || v < v0 || v > v1 {
89 let (closed_u, closed_v) = surface_closedness(surface)?;
90 if closed_u && (u < u0 || u > u1) { uu = u0 + (u - u0).rem_euclid(u1 - u0); }
93 if closed_v && (v < v0 || v > v1) { vv = v0 + (v - v0).rem_euclid(v1 - v0); }
94 }
95 if uu >= u0 && uu <= u1 && vv >= v0 && vv <= v1 {
96 let point = surface.evaluate_homogeneous(uu, vv)?;
97 if point.w.abs() <= EPSILON {
98 return Err("NurbsSurface: zero evaluated weight".into());
99 }
100 return Ok(Vec3::new(point.x, point.y, point.z).scale(1.0 / point.w));
101 }
102 }
103 surface.evaluate_extended(u,v)
104}
105
106pub struct PcurveSampleCache {
109 curve_trace: Option<crate::reuse_profile::Trace<u64>>,
110 surface_trace: Option<crate::reuse_profile::Trace<(u64, u64, bool, bool)>>,
111 rollover: bool,
112 point_limit: usize,
113 surface: usize,
114 curve: usize,
115 pub curves: rustc_hash::FxHashMap<u64, Vec3>,
116 pub surfaces: rustc_hash::FxHashMap<(u64, u64, bool, bool), Vec3>,
117 pub inversions: rustc_hash::FxHashMap<[u64; 3], ([f64; 2], f64)>,
118 pub requests: [usize; 4],
119 pub hits: [usize; 4],
120 pub speeds: rustc_hash::FxHashMap<(u64, u64), f64>,
121}
122thread_local! {
123 pub static PCURVE_SAMPLES: std::cell::RefCell<Vec<Option<PcurveSampleCache>>> = const { std::cell::RefCell::new(Vec::new()) };
124}
125pub struct PcurveSampleScope<'a>(std::marker::PhantomData<(&'a NurbsSurface, &'a NurbsCurve)>);
126impl<'a> PcurveSampleScope<'a> {
127 pub fn open(surface: &'a NurbsSurface, curve: &'a NurbsCurve, enabled: bool) -> Self {
128 Self::open_limit(surface, curve, enabled, switch!("BREP_PCURVE_SAMPLE_ROLLOVER", false),
129 if larger_working_set() { 65536 } else { PCURVE_SAMPLE_CACHE_LIMIT })
130 }
131
132 pub fn open_limit(surface: &'a NurbsSurface, curve: &'a NurbsCurve, enabled: bool, rollover: bool, point_limit: usize) -> Self {
133 let cache = enabled
134 .then(|| PcurveSampleCache {
135 curve_trace: crate::reuse_profile::Trace::open("curve", || serde_json::json!({"curve":curve,"identity":curve as *const _ as usize,"limit":point_limit})),
136 surface_trace: crate::reuse_profile::Trace::open("surface", || serde_json::json!({"surface":surface,"identity":surface as *const _ as usize,"curve":curve,"limit":point_limit})),
137 rollover, point_limit, surface: surface as *const _ as usize,
138 curve: curve as *const _ as usize, curves: Default::default(),
139 surfaces: Default::default(), inversions: Default::default(), requests: [0; 4], hits: [0; 4], speeds: Default::default() });
140 PCURVE_SAMPLES.with(|stack| stack.borrow_mut().push(cache));
141 Self(std::marker::PhantomData)
142 }
143}
144impl Drop for PcurveSampleScope<'_> {
145 fn drop(&mut self) {
146 PCURVE_SAMPLES.with(|stack| {
147 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
148 if let Some(Some(cache)) = stack.borrow_mut().pop() {
149 if crate::profile::profile_enabled() {
150 profile_line!("pcurve.samples requests={:?} hits={:?} retained={:?}", cache.requests,
151 cache.hits, [cache.curves.len(), cache.surfaces.len(), cache.inversions.len(), cache.speeds.len()]);
152 }
153 }
154 });
155 }
156}
157pub const PCURVE_SAMPLE_CACHE_LIMIT: usize = 16384;
158
159pub fn larger_working_set() -> bool {
163 switch!("BREP_PCURVE_WORKING_SET", false)
164}
165
166fn retain_sample<K: std::hash::Hash + Eq, V>(
171 map: &mut rustc_hash::FxHashMap<K, V>, key: K, value: V, rollover: bool, limit: usize,
172) {
173 if rollover && map.len() >= limit { map.clear(); }
174 if map.len() < limit { map.insert(key, value); }
175}
176pub fn section_u_speed(surface: &NurbsSurface, u: f64, v: f64) -> Result<f64, String> {
177 let key = (u.to_bits(), v.to_bits());
178 let (active, hit) = PCURVE_SAMPLES.with(|stack| {
179 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
180 let mut stack = stack.borrow_mut();
181 let Some(Some(cache)) = stack.last_mut() else { return (false, None) };
182 if cache.surface != surface as *const _ as usize { return (false, None) }
183 cache.requests[3] += 1;
184 let hit = cache.speeds.get(&key).copied();
185 cache.hits[3] += usize::from(hit.is_some());
186 (true, hit)
187 });
188 if let Some(hit) = hit { return Ok(hit) }
189 let speed = surface.deriv1(u, v)?.1.length();
190 if active { PCURVE_SAMPLES.with(|stack| {
191 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
192 let mut stack = stack.borrow_mut();
193 let cache = stack.last_mut().unwrap().as_mut().unwrap();
194 if cache.speeds.len() < PCURVE_SAMPLE_CACHE_LIMIT { cache.speeds.insert(key, speed); }
195 }); }
196 Ok(speed)
197}
198
199#[track_caller]
200pub fn section_curve_point(curve: &NurbsCurve, parameter: f64) -> Result<Vec3, String> {
201 let caller = std::panic::Location::caller();
202 let key = parameter.to_bits();
203 let (active, hit) = PCURVE_SAMPLES.with(|stack| {
204 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
205 let mut stack = stack.borrow_mut();
206 let Some(Some(cache)) = stack.last_mut() else { return (false, None) };
207 if cache.curve != curve as *const _ as usize { return (false, None) }
208 cache.requests[0] += 1;
209 let hit = cache.curves.get(&key).copied();
210 cache.hits[0] += usize::from(hit.is_some());
211 if hit.is_some() { if let Some(trace) = &mut cache.curve_trace { trace.access(&key, caller, true, true); } }
212 (true, hit)
213 });
214 if let Some(hit) = hit { return Ok(hit) }
215 let result = curve.evaluate(parameter);
216 let point = match result {
217 Ok(point) => point,
218 Err(error) => {
219 if active { PCURVE_SAMPLES.with(|stack| {
220 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP); if let Some(trace) = &mut stack.borrow_mut().last_mut().unwrap().as_mut().unwrap().curve_trace {
221 trace.access(&key, caller, false, false);
222 } }); }
223 return Err(error);
224 }
225 };
226 if active { PCURVE_SAMPLES.with(|stack| {
227 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
228 let mut stack = stack.borrow_mut();
229 let cache = stack.last_mut().unwrap().as_mut().unwrap();
230 if let Some(trace) = &mut cache.curve_trace { trace.access(&key, caller, false, true); }
231 retain_sample(&mut cache.curves, key, point, cache.rollover, cache.point_limit);
232 }); }
233 Ok(point)
234}
235#[track_caller]
236pub fn section_surface_point(surface: &NurbsSurface, u: f64, v: f64, extended: bool) -> Result<Vec3, String> {
237 let caller = std::panic::Location::caller();
238 let stack_point = PCURVE_STACK_POINT.with(|state| state.get());
241 let key = (u.to_bits(), v.to_bits(), extended, stack_point);
242 let (active, hit) = PCURVE_SAMPLES.with(|stack| {
243 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
244 let mut stack = stack.borrow_mut();
245 let Some(Some(cache)) = stack.last_mut() else { return (false, None) };
246 if cache.surface != surface as *const _ as usize { return (false, None) }
247 cache.requests[1] += 1;
248 let hit = cache.surfaces.get(&key).copied();
249 cache.hits[1] += usize::from(hit.is_some());
250 if hit.is_some() { if let Some(trace) = &mut cache.surface_trace { trace.access(&key, caller, true, true); } }
251 (true, hit)
252 });
253 if let Some(hit) = hit { return Ok(hit) }
254 let result = if extended { section_extended_point(surface, u, v, stack_point) } else { surface.evaluate(u, v) };
255 let point = match result {
256 Ok(point) => point,
257 Err(error) => {
258 if active { PCURVE_SAMPLES.with(|stack| {
259 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP); if let Some(trace) = &mut stack.borrow_mut().last_mut().unwrap().as_mut().unwrap().surface_trace {
260 trace.access(&key, caller, false, false);
261 } }); }
262 return Err(error);
263 }
264 };
265 if active { PCURVE_SAMPLES.with(|stack| {
266 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
267 let mut stack = stack.borrow_mut();
268 let cache = stack.last_mut().unwrap().as_mut().unwrap();
269 if let Some(trace) = &mut cache.surface_trace { trace.access(&key, caller, false, true); }
270 retain_sample(&mut cache.surfaces, key, point, cache.rollover, cache.point_limit);
271 }); }
272 Ok(point)
273}
274pub fn invert_checked(surface: &NurbsSurface, point: Vec3) -> Result<([f64; 2], f64), String> {
275 let key = [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()];
276 let (active, hit) = PCURVE_SAMPLES.with(|stack| {
277 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
278 let mut stack = stack.borrow_mut();
279 let Some(Some(cache)) = stack.last_mut() else { return (false, None) };
280 if cache.surface != surface as *const _ as usize { return (false, None) }
281 cache.requests[2] += 1;
282 let hit = cache.inversions.get(&key).copied();
283 cache.hits[2] += usize::from(hit.is_some());
284 (true, hit)
285 });
286 if let Some(hit) = hit { return Ok(hit) }
287 let projection = invert_checked_uncached(surface, point)?;
288 if active { PCURVE_SAMPLES.with(|stack| {
289 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
290 let mut stack = stack.borrow_mut();
291 let cache = stack.last_mut().unwrap().as_mut().unwrap();
292 if cache.inversions.len() < PCURVE_SAMPLE_CACHE_LIMIT { cache.inversions.insert(key, projection); }
293 }); }
294 Ok(projection)
295}
296
297pub fn invert_checked_uncached(surface: &NurbsSurface, point: Vec3) -> Result<([f64; 2], f64), String> {
298 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INVERT_CHECKED, surface);
299 if surface.is_affine()? {
300 let ([u0, _], [v0, _]) = surface_domains(surface)?;
301 let (origin, du, dv) = surface.deriv1(u0, v0)?;
302 let delta = point.sub(origin);
303 let uu = du.dot(du);
304 let uv = du.dot(dv);
305 let vv = dv.dot(dv);
306 let along_u = delta.dot(du);
307 let along_v = delta.dot(dv);
308 let determinant = uu * vv - uv * uv;
309 if determinant.abs() > EPSILON {
310 let parameter = [
311 u0 + (along_u * vv - along_v * uv) / determinant,
312 v0 + (along_v * uu - along_u * uv) / determinant,
313 ];
314 let foot = origin.add(du.scale(parameter[0] - u0)).add(dv.scale(parameter[1] - v0));
318 return Ok((parameter, point.sub(foot).length()));
319 }
320 }
321 let projection = project_point_to_surface(surface, point)?;
322 if crate::switch!("BREP_STEP_PRECISION_FOOT_REUSE", true) && !crate::projection::global_site_filter_active() {
326 FOOT_MEMO.with(|memo| {
327 if let Some(open) = memo.borrow_mut().as_mut().filter(|m| !m.precision && std::ptr::eq(m.surface,surface)) {
328 let key = point_bits(point);
329 if DEFER_FOOT_INSERTS.with(|cell|cell.get()) {
330 open.pending_global.push((key,Some(projection)));
331 } else {
332 open.global.insert(key,Some(projection));
333 }
334 }
335 });
336 }
337 Ok(([projection.u, projection.v], projection.distance))
338}
339
340fn cone_apex_u() -> bool {
345 switch!("BREP_PCURVE_CONE_APEX_U", true)
346}
347
348fn worst_first() -> bool {
352 switch!("BREP_PCURVE_WORST_FIRST", true)
353}
354
355fn pole_row_crossing() -> bool {
368 switch!(live "BREP_PCURVE_POLE_ROW_CROSSING", true)
369}
370
371fn row_collapsed(surface: &NurbsSurface, v: f64) -> Result<bool, String> {
376 if surface.control_points.iter().flatten().any(|control| !(control.w > 0.0)) {
377 return Ok(false);
378 }
379 let mut row = Vec::with_capacity(surface.control_points.len());
380 for column in &surface.control_points {
381 let curve = NurbsCurve::new(surface.degree_v, surface.knots_v.clone(), column.clone())?;
382 row.push(curve.evaluate(v)?);
383 }
384 let Some(&first) = row.first() else { return Ok(false) };
385 let extent = surface
386 .control_points
387 .iter()
388 .flatten()
389 .filter_map(|control| control.point().ok())
390 .map(|point| point.sub(first).length())
391 .fold(0.0_f64, f64::max);
392 Ok(row.iter().all(|point| point.sub(first).length() <= 1e-12 * (1.0 + extent)))
393}
394
395fn pole_longitude(points: &[Vec3], parameters: &[f64], pole: usize, near: usize, far: usize) -> f64 {
400 let (t_pole, t_near, t_far) = (parameters[pole], parameters[near], parameters[far]);
401 if (t_near - t_far).abs() <= f64::EPSILON * t_near.abs().max(1.0) {
402 return points[near].x;
403 }
404 points[near].x + (points[near].x - points[far].x) * (t_pole - t_near) / (t_near - t_far)
405}
406
407fn pole_row_crossings(surface: &NurbsSurface, points: &mut [Vec3], parameters: &[f64], pieces: &[usize]) -> Result<Vec<(usize, Vec3, Vec3)>, String> {
413 let ([u0, u1], _) = surface_domains(surface)?;
414 let period = (u1 - u0).abs();
415 let mut crossings = Vec::new();
416 for &join in &pieces[1..pieces.len() - 1] {
417 if join < 2 || join + 2 >= points.len() || !row_collapsed(surface, points[join].y)? {
418 continue;
419 }
420 let incoming = pole_longitude(points, parameters, join, join - 1, join - 2);
421 let outgoing = pole_longitude(points, parameters, join, join + 1, join + 2);
422 if (incoming - outgoing).abs() <= 1e-12 * period.max(1.0) {
423 continue;
424 }
425 let pole_v = points[join].y;
426 crossings.push((join, Vec3::new(incoming, pole_v, 0.0), Vec3::new(outgoing, pole_v, 0.0)));
427 }
428 Ok(crossings)
429}
430
431fn hold_pole_row_ends(surface: &NurbsSurface, points: &mut [Vec3], parameters: &[f64]) -> Result<(), String> {
435 if points.len() < 3 {
436 return Ok(());
437 }
438 let last = points.len() - 1;
439 if row_collapsed(surface, points[0].y)? && !row_collapsed(surface, points[1].y)? {
440 points[0].x = pole_longitude(points, parameters, 0, 1, 2);
441 }
442 if row_collapsed(surface, points[last].y)? && !row_collapsed(surface, points[last - 1].y)? {
443 points[last].x = pole_longitude(points, parameters, last, last - 1, last - 2);
444 }
445 Ok(())
446}
447
448fn sphere_pole_ends() -> bool {
464 switch!(live "BREP_PCURVE_SPHERE_POLE_ENDS", false)
465}
466
467fn sphere_pole_end_links(
474 surface: &NurbsSurface,
475 points: &[Vec3],
476 parameters: &[f64],
477 joins: &[f64],
478 pole_rows: bool,
479) -> Result<Option<NurbsCurve>, String> {
480 if points.len() < 4 || points.len() != parameters.len() || !parameters.windows(2).all(|pair| pair[1] > pair[0]) {
481 return Ok(None);
482 }
483 let ([u0, u1], _) = surface_domains(surface)?;
484 let period = (u1 - u0).abs();
485 let last = points.len() - 1;
486 let held_longitude = |end: usize, near: usize, far: usize| -> Result<Option<f64>, String> {
487 if !row_collapsed(surface, points[end].y)? || row_collapsed(surface, points[near].y)? {
488 return Ok(None);
489 }
490 let longitude = pole_longitude(points, parameters, end, near, far);
491 let apart = (longitude - points[end].x).rem_euclid(period.max(f64::MIN_POSITIVE));
493 let apart = apart.min(period - apart);
494 Ok((longitude.is_finite() && apart > 1e-12 * period.max(1.0)).then_some(longitude))
495 };
496 let start = held_longitude(0, 1, 2)?;
497 let end = held_longitude(last, last - 1, last - 2)?;
498 if start.is_none() && end.is_none() {
499 return Ok(None);
500 }
501 let (mut held, mut stations) = (points.to_vec(), parameters.to_vec());
505 if let Some(longitude) = start {
506 held[0].x = longitude;
507 stations[0] += 0.5 * (parameters[1] - parameters[0]);
508 }
509 if let Some(longitude) = end {
510 held[last].x = longitude;
511 stations[last] -= 0.5 * (parameters[last] - parameters[last - 1]);
512 }
513 let body = interpolate_stations(surface, held.clone(), &stations, joins, pole_rows)?;
514 if body.degree != 3 {
515 return Ok(None);
516 }
517 let link = |from: Vec3, to: Vec3, along: f64| Vec4::from_point(Vec3::new(from.x + (to.x - from.x) * along, from.y + (to.y - from.y) * along, 0.0), 1.0);
518 let mut knots: Vec<f64> = Vec::with_capacity(body.knots.len() + 6);
519 let mut control: Vec<Vec4> = Vec::with_capacity(body.control_points.len() + 6);
520 let body_knots = &body.knots[..];
521 let mut body_from = 0usize;
522 if start.is_some() {
523 knots.extend(std::iter::repeat(parameters[0]).take(4));
524 knots.extend(std::iter::repeat(stations[0]).take(3));
525 body_from = 4;
526 for along in [0.0, 1.0 / 3.0, 2.0 / 3.0] {
527 control.push(link(points[0], held[0], along));
528 }
529 }
530 let body_to = if end.is_some() { body_knots.len() - 1 } else { body_knots.len() };
531 knots.extend(body_knots[body_from..body_to].iter().copied());
532 control.extend(body.control_points.iter().copied());
533 if end.is_some() {
534 for along in [1.0 / 3.0, 2.0 / 3.0, 1.0] {
535 control.push(link(held[last], points[last], along));
536 }
537 knots.extend(std::iter::repeat(parameters[last]).take(4));
538 }
539 Ok(Some(NurbsCurve::new(3, knots, control)?))
540}
541
542fn c0_joins() -> bool {
543 switch!("BREP_PCURVE_C0_JOIN", true)
544}
545
546fn seeded_inserts() -> bool {
547 switch!("BREP_PCURVE_SEEDED_INSERTS", true)
548}
549
550fn invert_near(
560 surface: &NurbsSurface,
561 point: Vec3,
562 seed: [f64; 2],
563 neighbour_gap: f64,
564) -> Result<([f64; 2], f64), String> {
565 if !seeded_inserts() || surface.is_affine()? || surface.analytic().is_some() || surface.affine_sphere().is_some() {
566 return invert_checked(surface, point);
567 }
568 let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
569 if seeded.distance <= neighbour_gap + PCURVE_REFINEMENT_TOLERANCE {
570 return Ok(([seeded.u, seeded.v], seeded.distance));
571 }
572 invert_checked(surface, point)
573}
574
575fn unwrap_periodic(values: &mut [f64], minimum: f64, maximum: f64) {
576 let period = maximum - minimum;
577 for index in 1..values.len() {
578 while values[index] - values[index - 1] > period / 2.0 {
579 values[index] -= period;
580 }
581 while values[index] - values[index - 1] < -period / 2.0 {
582 values[index] += period;
583 }
584 }
585 if values.len() > 1 {
586 while values[0] - values[1] > period / 2.0 {
587 values[0] -= period;
588 }
589 while values[0] - values[1] < -period / 2.0 {
590 values[0] += period;
591 }
592 }
593 if values.len() > 1 {
603 let excursion = |shift: f64| -> f64 {
604 values
605 .iter()
606 .map(|value| {
607 let v = value + shift;
608 (minimum - v).max(0.0) + (v - maximum).max(0.0)
609 })
610 .sum::<f64>()
611 };
612 let mean = values.iter().copied().sum::<f64>() / values.len() as f64;
613 let center = 0.5 * (minimum + maximum);
614 let base_k = ((center - mean) / period).round() as i64;
615 let mut best_shift = 0.0;
616 let mut best_excursion = f64::INFINITY;
617 for k in (base_k - 1)..=(base_k + 1) {
618 let shift = k as f64 * period;
619 let value = excursion(shift);
620 if value < best_excursion {
621 best_excursion = value;
622 best_shift = shift;
623 }
624 }
625 if best_shift != 0.0 {
626 for value in values.iter_mut() {
627 *value += best_shift;
628 }
629 }
630 }
631}
632
633pub fn build_interpolant(
639 surface: &NurbsSurface,
640 raw_parameters: &[[f64; 2]],
641 curve_parameters: &[f64],
642) -> Result<(NurbsCurve, f64, f64), String> {
643 build_interpolant_joined(surface, raw_parameters, curve_parameters, &[])
644}
645
646pub fn build_interpolant_joined(
660 surface: &NurbsSurface,
661 raw_parameters: &[[f64; 2]],
662 curve_parameters: &[f64],
663 joins: &[f64],
664) -> Result<(NurbsCurve, f64, f64), String> {
665 let _clock = PcurvePhaseClock::new("interpolant", raw_parameters.len(), false);
666 let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
667 let (closed_u, closed_v) = surface_closedness(surface)?;
668 let mut parameters = raw_parameters.to_vec();
669 if cone_apex_u() && matches!(surface.analytic(), Some(AnalyticSurface::RuledRevolution { .. })) && parameters.len() >= 2 {
679 let speeds = parameters
680 .iter()
681 .map(|parameter| section_u_speed(surface, parameter[0], parameter[1]))
682 .collect::<Result<Vec<_>, _>>()?;
683 let reference = speeds.iter().copied().fold(0.0_f64, f64::max);
684 let singular = |index: usize| speeds[index] <= reference * 1e-2;
685 if let (Some(first), Some(last)) = (
686 (0..parameters.len()).find(|&index| !singular(index)),
687 (0..parameters.len()).rfind(|&index| !singular(index)),
688 ) {
689 for index in 0..first {
690 parameters[index][0] = parameters[first][0];
691 }
692 for index in last + 1..parameters.len() {
693 parameters[index][0] = parameters[last][0];
694 }
695 }
696 }
697 let sphere_u_singular = if matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })) {
709 let speeds = parameters
710 .iter()
711 .map(|parameter| {
712 section_u_speed(surface, parameter[0], parameter[1])
713 })
714 .collect::<Result<Vec<_>, _>>()?;
715 let reference = speeds.iter().copied().fold(0.0_f64, f64::max);
716 speeds
717 .into_iter()
718 .map(|speed| speed <= reference * 1e-2)
723 .collect::<Vec<_>>()
724 } else {
725 vec![false; parameters.len()]
726 };
727 let has_interior_pole_crossing = sphere_u_singular
736 .iter()
737 .position(|singular| !singular)
738 .zip(sphere_u_singular.iter().rposition(|singular| !singular))
739 .is_some_and(|(first, last)| sphere_u_singular[first..=last].iter().any(|value| *value));
740 let period = (u1 - u0).abs();
741 let interior_pole_branch_reset = closed_u
742 && has_interior_pole_crossing
743 && parameters.windows(2).zip(sphere_u_singular.windows(2)).any(
744 |(parameter_pair, singular_pair)| {
745 (singular_pair[0] || singular_pair[1])
746 && (parameter_pair[1][0] - parameter_pair[0][0]).abs()
747 >= 0.5 * period - 1e-12 * period.max(1.0)
748 },
749 );
750 if closed_u {
751 let mut values = parameters.iter().map(|value| value[0]).collect::<Vec<_>>();
752 if interior_pole_branch_reset {
753 let mut start = 0;
754 while start < values.len() {
755 while start < values.len() && sphere_u_singular[start] {
756 start += 1;
757 }
758 let mut end = start;
759 while end < values.len() && !sphere_u_singular[end] {
760 end += 1;
761 }
762 unwrap_periodic(&mut values[start..end], u0, u1);
763 start = end;
764 }
765 } else {
766 unwrap_periodic(&mut values, u0, u1);
767 }
768 for (parameter, value) in parameters.iter_mut().zip(values) {
769 parameter[0] = value;
770 }
771 }
772 if closed_v {
773 let mut values = parameters.iter().map(|value| value[1]).collect::<Vec<_>>();
774 unwrap_periodic(&mut values, v0, v1);
775 for (parameter, value) in parameters.iter_mut().zip(values) {
776 parameter[1] = value;
777 }
778 }
779 let mut excursion = 0.0_f64;
796 let mut distance = 0.0_f64;
797 let mut points = Vec::with_capacity(parameters.len());
798 for parameter in parameters {
799 let u = if closed_u {
800 parameter[0]
801 } else {
802 parameter[0].clamp(u0, u1)
803 };
804 let v = if closed_v {
805 parameter[1]
806 } else {
807 parameter[1].clamp(v0, v1)
808 };
809 let pulled = ((parameter[0] - u).powi(2) + (parameter[1] - v).powi(2)).sqrt();
810 if pulled > 0.0 {
811 excursion = excursion.max(pulled);
812 let extended = surface.evaluate_extended(parameter[0], parameter[1])?;
813 distance = distance.max(extended.sub(surface.evaluate(u, v)?).length());
814 }
815 points.push(Vec3::new(u, v, 0.0));
816 }
817 let pole_rows = pole_row_crossing() && closed_u && !matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. }));
824 if pole_rows {
825 hold_pole_row_ends(surface, &mut points, curve_parameters)?;
826 }
827 if sphere_pole_ends() && closed_u && !interior_pole_branch_reset && matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })) {
828 if let Ok(Some(curve)) = sphere_pole_end_links(surface, &points, curve_parameters, joins, pole_rows) {
830 return Ok((curve, excursion, distance));
831 }
832 }
833 let curve = interpolate_stations(surface, points, curve_parameters, joins, pole_rows)?;
834 Ok((curve, excursion, distance))
835}
836
837fn interpolate_stations(
842 surface: &NurbsSurface,
843 points: Vec<Vec3>,
844 curve_parameters: &[f64],
845 joins: &[f64],
846 pole_rows: bool,
847) -> Result<NurbsCurve, String> {
848 let degree = 3usize.min(points.len() - 1);
849 let mut bounds: Vec<usize> = joins
850 .iter()
851 .filter_map(|join| curve_parameters.iter().position(|parameter| parameter == join))
852 .filter(|&index| index > 0 && index + 1 < curve_parameters.len())
853 .collect();
854 bounds.sort_unstable();
855 bounds.dedup();
856 if degree < 3 || bounds.is_empty() || !c0_joins() {
857 return interpolate_curve(&points, degree, curve_parameters);
858 }
859 let mut pieces = vec![0usize];
862 for bound in bounds {
863 if bound + 1 - pieces[pieces.len() - 1] >= 4 {
864 pieces.push(bound);
865 }
866 }
867 if curve_parameters.len() - pieces[pieces.len() - 1] < 4 {
868 pieces.pop();
869 }
870 pieces.push(curve_parameters.len() - 1);
871 if pieces.len() < 3 {
872 return interpolate_curve(&points, degree, curve_parameters);
873 }
874 let mut points = points;
879 let crossings = if pole_rows { pole_row_crossings(surface, &mut points, curve_parameters, &pieces)? } else { Vec::new() };
880 let mut knots: Vec<f64> = Vec::with_capacity(curve_parameters.len() + 8);
881 let mut control: Vec<Vec4> = Vec::with_capacity(curve_parameters.len() + 4);
882 let last_piece = pieces.len() - 2;
883 let mut start_override: Option<Vec3> = None;
885 for piece in 0..=last_piece {
886 let (from, to) = (pieces[piece], pieces[piece + 1]);
887 let mut piece_points = points[from..=to].to_vec();
888 let mut piece_parameters = curve_parameters[from..=to].to_vec();
889 if let Some(start) = start_override.take() {
890 piece_points[0] = start;
891 }
892 let crossing = crossings.iter().find(|crossing| crossing.0 == to).copied();
893 if let Some((_, before, _)) = crossing {
894 let span = piece_parameters[piece_parameters.len() - 1] - piece_parameters[piece_parameters.len() - 2];
897 let sliver = (1e-9 * (curve_parameters[curve_parameters.len() - 1] - curve_parameters[0]).abs()).min(0.1 * span);
898 let last = piece_parameters.len() - 1;
899 piece_parameters[last] -= sliver;
900 piece_points[last] = before;
901 }
902 let fitted = interpolate_curve(&piece_points, 3, &piece_parameters)?;
903 if piece == 0 {
904 knots.extend(fitted.knots[..4].iter().copied());
905 }
906 knots.extend(fitted.knots[4..fitted.knots.len() - 4].iter().copied());
907 control.extend(fitted.control_points.iter().skip(usize::from(piece > 0)).copied());
908 if let Some((_, before, after)) = crossing {
909 let link_start = piece_parameters[piece_parameters.len() - 1];
910 knots.extend(std::iter::repeat(link_start).take(3));
911 for k in 1..=3 {
912 let along = k as f64 / 3.0;
913 let point = Vec3::new(before.x + (after.x - before.x) * along, before.y + (after.y - before.y) * along, 0.0);
914 control.push(Vec4::from_point(point, 1.0));
915 }
916 start_override = Some(after);
917 }
918 let multiplicity = if piece == last_piece { 4 } else { 3 };
919 knots.extend(std::iter::repeat(curve_parameters[to]).take(multiplicity));
920 }
921 NurbsCurve::new(3, knots, control)
922}
923
924pub const PCURVE_REFINEMENT_TOLERANCE: f64 = 1e-7;
972
973pub const MAX_PCURVE_SAMPLES: usize = 600;
989
990const PCURVE_RAISED_SAMPLES: usize = 2000;
996
997#[derive(Clone, Copy, Debug, PartialEq)]
1010pub struct PcurveFitReport {
1011 pub residual: f64,
1018 pub floor: f64,
1020 pub samples: usize,
1022 pub exit: PcurveFitExit,
1024 pub off_surface: f64,
1031 pub raised: bool,
1034 pub clamped_excursion: f64,
1051 pub clamped_distance: f64,
1055}
1056
1057impl PcurveFitReport {
1058 pub fn met_floor(&self) -> bool {
1060 self.residual <= self.floor
1061 }
1062
1063 pub fn on_bar(&self) -> bool {
1078 self.residual <= self.floor + self.off_surface
1079 }
1080}
1081
1082#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1086pub enum PcurveFitExit {
1087 Converged,
1090 SampleCeiling,
1095 RoundBudget,
1098 Stalled,
1108 SpanFloor,
1117}
1118
1119#[derive(Clone, Debug)]
1121pub struct PcurveFit {
1122 pub curve: NurbsCurve,
1123 pub report: PcurveFitReport,
1124}
1125
1126#[derive(Clone, Copy, Debug, Default, PartialEq)]
1146pub struct PcurveFitLedger {
1147 pub fits: u64,
1149 pub unmet: u64,
1151 pub sample_ceiling: u64,
1153 pub round_budget: u64,
1155 pub stalled: u64,
1157 pub span_floor: u64,
1160 pub worst_unmet_residual: f64,
1162 pub raised: u64,
1165 pub raise_declined: u64,
1168 pub worst_off_surface: f64,
1170 pub clamped: u64,
1173 pub worst_clamped_excursion: f64,
1175 pub worst_clamped_distance: f64,
1177}
1178
1179impl PcurveFitLedger {
1180 fn record(&mut self, report: &PcurveFitReport) {
1181 self.fits += 1;
1182 if report.raised {
1183 self.raised += 1;
1184 }
1185 self.worst_off_surface = self.worst_off_surface.max(report.off_surface);
1186 if report.clamped_excursion > 0.0 {
1187 self.clamped += 1;
1188 self.worst_clamped_excursion = self.worst_clamped_excursion.max(report.clamped_excursion);
1189 self.worst_clamped_distance = self.worst_clamped_distance.max(report.clamped_distance);
1190 }
1191 if report.met_floor() {
1192 return;
1193 }
1194 self.unmet += 1;
1195 match report.exit {
1196 PcurveFitExit::Converged => {}
1197 PcurveFitExit::SampleCeiling => {
1198 self.sample_ceiling += 1;
1199 if !report.raised {
1200 self.raise_declined += 1;
1201 }
1202 }
1203 PcurveFitExit::RoundBudget => self.round_budget += 1,
1204 PcurveFitExit::Stalled => self.stalled += 1,
1205 PcurveFitExit::SpanFloor => self.span_floor += 1,
1206 }
1207 self.worst_unmet_residual = self.worst_unmet_residual.max(report.residual);
1208 }
1209
1210 fn fold(&mut self, child: &PcurveFitLedger) {
1211 self.fits += child.fits;
1212 self.unmet += child.unmet;
1213 self.sample_ceiling += child.sample_ceiling;
1214 self.round_budget += child.round_budget;
1215 self.stalled += child.stalled;
1216 self.span_floor += child.span_floor;
1217 self.worst_unmet_residual = self.worst_unmet_residual.max(child.worst_unmet_residual);
1218 self.raised += child.raised;
1219 self.raise_declined += child.raise_declined;
1220 self.worst_off_surface = self.worst_off_surface.max(child.worst_off_surface);
1221 self.clamped += child.clamped;
1222 self.worst_clamped_excursion = self.worst_clamped_excursion.max(child.worst_clamped_excursion);
1223 self.worst_clamped_distance = self.worst_clamped_distance.max(child.worst_clamped_distance);
1224 }
1225
1226 pub fn report_into(&self, diagnostics: &mut KernelDiagnostics) {
1232 diagnostics.count_n("pcurve.fits", self.fits);
1233 diagnostics.count_n("pcurve.unmet_floor", self.unmet);
1234 diagnostics.count_n("pcurve.exit.sample_ceiling", self.sample_ceiling);
1235 diagnostics.count_n("pcurve.exit.round_budget", self.round_budget);
1236 diagnostics.count_n("pcurve.exit.stalled", self.stalled);
1237 diagnostics.count_n("pcurve.exit.span_floor", self.span_floor);
1238 diagnostics.count_n("pcurve.budget_raised", self.raised);
1239 diagnostics.count_n("pcurve.budget_raise_declined", self.raise_declined);
1240 diagnostics.measure_max("pcurve.worst_unmet_residual", self.worst_unmet_residual);
1241 diagnostics.measure_max("pcurve.worst_off_surface", self.worst_off_surface);
1242 diagnostics.count_n("pcurve.clamped", self.clamped);
1243 diagnostics.measure_max("pcurve.worst_clamped_excursion", self.worst_clamped_excursion);
1244 diagnostics.measure_max("pcurve.worst_clamped_distance", self.worst_clamped_distance);
1245 if self.unmet > 0 {
1246 diagnostics.event(
1247 DiagnosticSeverity::Degraded,
1248 KernelStage::Refine,
1249 "pcurve.unmet_floor",
1250 format!(
1251 "{} of {} pcurve fits did not reach the {:.0e} floor \
1252 (sample ceiling {}, round budget {}, stalled {}, span floor {}); \
1253 worst residual {:.3e}; budget raised on {}, declined on {}; \
1254 edge curves sit off their surfaces by up to {:.3e}{}",
1255 self.unmet,
1256 self.fits,
1257 PCURVE_REFINEMENT_TOLERANCE,
1258 self.sample_ceiling,
1259 self.round_budget,
1260 self.stalled,
1261 self.span_floor,
1262 self.worst_unmet_residual,
1263 self.raised,
1264 self.raise_declined,
1265 self.worst_off_surface,
1266 if self.clamped > 0 {
1267 format!(
1268 "; {} fit(s) clamped into their chart by up to {:.3e} in parameter, {:.3e} in 3D",
1269 self.clamped, self.worst_clamped_excursion, self.worst_clamped_distance
1270 )
1271 } else {
1272 String::new()
1273 },
1274 ),
1275 );
1276 }
1277 }
1278}
1279
1280thread_local! {
1281 static FOOT_MEMO: std::cell::RefCell<Option<FootMemo>> = const { std::cell::RefCell::new(None) };
1283}
1284
1285pub struct FootMemo {
1304 precision: bool,
1305 surface: *const NurbsSurface,
1306 coarse_global: Option<rustc_hash::FxHashMap<[u64; 3], Option<crate::SurfaceProjection>>>,
1309 global: rustc_hash::FxHashMap<[u64; 3], Option<crate::SurfaceProjection>>,
1310 seeded: rustc_hash::FxHashMap<[u64; 5], Option<crate::SurfaceProjection>>,
1311 pending_global: Vec<([u64; 3], Option<crate::SurfaceProjection>)>,
1312 pending_seeded: Vec<([u64; 5], Option<crate::SurfaceProjection>)>,
1313}
1314
1315impl FootMemo {
1316 fn new(surface: *const NurbsSurface) -> Self {
1317 Self { precision: false, surface, coarse_global: None, global: Default::default(), seeded: Default::default(), pending_global: Vec::new(), pending_seeded: Vec::new() }
1318 }
1319
1320 fn fold_pending(&mut self) {
1323 if !self.pending_global.is_empty() {
1324 self.global.reserve(self.pending_global.len());
1325 self.global.extend(self.pending_global.drain(..));
1326 }
1327 if !self.pending_seeded.is_empty() {
1328 self.seeded.reserve(self.pending_seeded.len());
1329 self.seeded.extend(self.pending_seeded.drain(..));
1330 }
1331 }
1332}
1333
1334thread_local! {
1335 static DEFER_FOOT_INSERTS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1336}
1337
1338pub fn defer_foot_inserts<T>(read: impl FnOnce() -> T) -> T {
1341 let previous = DEFER_FOOT_INSERTS.with(|cell| cell.replace(true));
1342 let result = read();
1343 DEFER_FOOT_INSERTS.with(|cell| cell.set(previous));
1344 result
1345}
1346
1347pub struct FootMemoScope<'a> {
1354 previous: Option<Option<FootMemo>>,
1355 _surface: std::marker::PhantomData<&'a NurbsSurface>,
1356 _thread_bound: std::marker::PhantomData<*const ()>,
1358}
1359
1360impl<'a> FootMemoScope<'a> {
1361 fn precision(surface: &'a NurbsSurface) -> Self {
1364 let mut next = FootMemo::new(surface);
1365 next.precision = true;
1366 if crate::switch!("BREP_STEP_PRECISION_FOOT_REUSE", true) && !crate::projection::global_site_filter_active() {
1367 FOOT_MEMO.with(|memo| {
1368 if let Some(parent) = memo.borrow().as_ref().filter(|m| !m.precision && std::ptr::eq(m.surface,surface)) {
1369 let mut coarse = parent.global.clone();
1370 coarse.extend(parent.pending_global.iter().copied());
1371 next.coarse_global = Some(coarse);
1372 }
1373 });
1374 }
1375 let previous = FOOT_MEMO.with(|memo| memo.replace(Some(next)));
1376 Self { previous: Some(previous), _surface: std::marker::PhantomData, _thread_bound: std::marker::PhantomData }
1377 }
1378
1379 pub fn open(surface: &'a NurbsSurface) -> Self {
1380 let key = surface as *const NurbsSurface;
1381 let previous = FOOT_MEMO.with(|memo| {
1382 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1383 let mut memo = memo.borrow_mut();
1384 if memo.as_ref().is_some_and(|open| std::ptr::eq(open.surface, key)) {
1385 None
1386 } else {
1387 Some(memo.replace(FootMemo::new(key)))
1388 }
1389 });
1390 Self { previous, _surface: std::marker::PhantomData, _thread_bound: std::marker::PhantomData }
1391 }
1392}
1393
1394impl Drop for FootMemoScope<'_> {
1395 fn drop(&mut self) {
1396 if let Some(previous) = self.previous.take() {
1397 if crate::profile::profile_enabled() {
1398 FOOT_MEMO.with(|memo| {
1399 let memo = memo.borrow();
1400 if let Some(open) = memo.as_ref().filter(|m| m.precision) {
1401 if let Some(coarse) = &open.coarse_global {
1402 let reused = open.global.keys().filter(|key|coarse.contains_key(*key)).count();
1403 eprintln!("pcurve.precision_memo coarse={} reused_global={reused}",coarse.len());
1404 }
1405 }
1406 });
1407 }
1408 FOOT_MEMO.with(|memo| *memo.borrow_mut() = previous);
1409 }
1410 }
1411}
1412
1413pub fn foot_memo_open() -> bool {
1415 FOOT_MEMO.with(|memo| memo.borrow().is_some())
1416}
1417
1418fn precision_trim_feet(surface: &NurbsSurface) -> bool {
1419 FOOT_MEMO.with(|memo| memo.borrow().as_ref().is_some_and(|m| m.precision && std::ptr::eq(m.surface, surface)))
1420}
1421
1422fn refine_memo_foot(surface: &NurbsSurface, point: Vec3, foot: Option<crate::SurfaceProjection>) -> Option<crate::SurfaceProjection> {
1423 if precision_trim_feet(surface) {
1424 foot.and_then(|foot| crate::projection::refine_trim_foot(surface, point, foot).ok())
1425 } else { foot }
1426}
1427
1428fn point_bits(point: Vec3) -> [u64; 3] {
1429 [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()]
1430}
1431
1432#[track_caller]
1438fn memo_global_foot(surface: &NurbsSurface, point: Vec3) -> Option<crate::SurfaceProjection> {
1439 if crate::projection::global_site_filter_active() {
1440 return refine_memo_foot(surface, point, project_point_to_surface(surface, point).ok());
1441 }
1442 let key = point_bits(point);
1443 let deferring = DEFER_FOOT_INSERTS.with(|cell| cell.get());
1444 let mut coarse = None;
1445 let hit = FOOT_MEMO.with(|memo| {
1446 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1447 memo.borrow_mut().as_mut().filter(|open| std::ptr::eq(open.surface, surface)).map(|open| {
1448 let hit = match open.global.get(&key).copied() {
1449 Some(foot) => Some(foot),
1450 None if !deferring && !open.pending_global.is_empty() => {
1451 open.fold_pending();
1452 open.global.get(&key).copied()
1453 }
1454 None => None,
1455 };
1456 if hit.is_none() {
1457 coarse = open.coarse_global.as_ref().and_then(|memo|memo.get(&key).copied());
1458 }
1459 hit
1460 })
1461 });
1462 match hit {
1463 Some(Some(foot)) => foot,
1464 Some(None) => {
1465 let raw = coarse.unwrap_or_else(||project_point_to_surface(surface,point).ok());
1466 let foot = refine_memo_foot(surface, point, raw);
1467 FOOT_MEMO.with(|memo| {
1468 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1469 if let Some(open) = memo.borrow_mut().as_mut().filter(|open| std::ptr::eq(open.surface, surface)) {
1470 if deferring {
1471 open.pending_global.push((key, foot));
1472 } else {
1473 open.global.insert(key, foot);
1474 }
1475 }
1476 });
1477 foot
1478 }
1479 None => refine_memo_foot(surface, point, project_point_to_surface(surface, point).ok()),
1480 }
1481}
1482
1483fn memo_seeded_foot(surface: &NurbsSurface, point: Vec3, seed_u: f64, seed_v: f64) -> Option<crate::SurfaceProjection> {
1486 let [x, y, z] = point_bits(point);
1487 let key = [x, y, z, seed_u.to_bits(), seed_v.to_bits()];
1488 let deferring = DEFER_FOOT_INSERTS.with(|cell| cell.get());
1489 let hit = FOOT_MEMO.with(|memo| {
1490 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1491 memo.borrow_mut().as_mut().filter(|open| std::ptr::eq(open.surface, surface)).map(|open| {
1492 match open.seeded.get(&key).copied() {
1493 Some(foot) => Some(foot),
1494 None if !deferring && !open.pending_seeded.is_empty() => {
1495 open.fold_pending();
1496 open.seeded.get(&key).copied()
1497 }
1498 None => None,
1499 }
1500 })
1501 });
1502 match hit {
1503 Some(Some(foot)) => foot,
1504 Some(None) => {
1505 let foot = refine_memo_foot(surface, point, project_point_to_surface_seeded(surface, point, seed_u, seed_v).ok());
1506 FOOT_MEMO.with(|memo| {
1507 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1508 if let Some(open) = memo.borrow_mut().as_mut().filter(|open| std::ptr::eq(open.surface, surface)) {
1509 if deferring {
1510 open.pending_seeded.push((key, foot));
1511 } else {
1512 open.seeded.insert(key, foot);
1513 }
1514 }
1515 });
1516 foot
1517 }
1518 None => refine_memo_foot(surface, point, project_point_to_surface_seeded(surface, point, seed_u, seed_v).ok()),
1519 }
1520}
1521
1522thread_local! {
1523 static PCURVE_FIT_SCOPES: std::cell::RefCell<Vec<PcurveFitLedger>> =
1525 const { std::cell::RefCell::new(Vec::new()) };
1526}
1527
1528static PCURVE_TRACK_CALL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1532
1533pub struct PcurveFitScope {
1540 _thread_bound: std::marker::PhantomData<*const ()>,
1542}
1543
1544impl PcurveFitScope {
1545 pub fn open() -> Self {
1546 PCURVE_FIT_SCOPES.with(|scopes| scopes.borrow_mut().push(PcurveFitLedger::default()));
1547 Self {
1548 _thread_bound: std::marker::PhantomData,
1549 }
1550 }
1551
1552 pub fn close(self) -> PcurveFitLedger {
1554 let ledger = PCURVE_FIT_SCOPES.with(|scopes| {
1555 let mut scopes = scopes.borrow_mut();
1556 let ledger = scopes.pop().unwrap_or_default();
1557 if let Some(parent) = scopes.last_mut() {
1558 parent.fold(&ledger);
1559 }
1560 ledger
1561 });
1562 std::mem::forget(self);
1563 ledger
1564 }
1565}
1566
1567impl Drop for PcurveFitScope {
1568 fn drop(&mut self) {
1569 PCURVE_FIT_SCOPES.with(|scopes| {
1570 scopes.borrow_mut().pop();
1571 });
1572 }
1573}
1574
1575pub fn record_fit(report: &PcurveFitReport) {
1576 crate::work_counts::add(|c| { c.fit_reports += 1; c.fit_samples += report.samples as u64; c.fit_raised += u64::from(report.raised); });
1577 if env_read!("BREP_DEBUG_PCURVE_FIT").is_some() {
1581 eprintln!("PCURVE-FIT {report:?}");
1582 }
1583 PCURVE_FIT_SCOPES.with(|scopes| {
1584 if let Some(open) = scopes.borrow_mut().last_mut() {
1585 open.record(report);
1586 }
1587 });
1588}
1589
1590pub fn probe_residual(
1595 surface: &NurbsSurface,
1596 curve: &NurbsCurve,
1597 pcurve: &NurbsCurve,
1598 parameters: &[f64],
1599 domain: [f64; 2],
1600 _u_domain: [f64; 2],
1601 _v_domain: [f64; 2],
1602) -> Result<f64, String> {
1603 probe_residual_at(surface, curve, pcurve, parameters, domain, &[0.25, 0.5, 0.75])
1604}
1605
1606pub const TRACKING_ACCEPTANCE_POINTS: usize = 16;
1615
1616pub struct ProbeCurveReader<'a> {
1621 curve: &'a NurbsCurve,
1622 pub enabled: bool,
1623 pub domain: Option<[f64; 2]>,
1624 span: Option<usize>,
1625 pub previous: Option<u64>,
1626 pub basis: [f64; crate::curve::MAX_STACK_ORDER],
1627 left: [f64; crate::curve::MAX_STACK_ORDER],
1628 right: [f64; crate::curve::MAX_STACK_ORDER],
1629}
1630impl<'a> ProbeCurveReader<'a> {
1631 pub fn new(curve: &'a NurbsCurve, enabled: bool) -> Self {
1632 Self { curve, enabled, domain: None, span: None, previous: None,
1633 basis: [0.0; crate::curve::MAX_STACK_ORDER],
1634 left: [0.0; crate::curve::MAX_STACK_ORDER], right: [0.0; crate::curve::MAX_STACK_ORDER] }
1635 }
1636 #[cfg_attr(feature = "profile-wall", track_caller)]
1637 pub fn evaluate(&mut self, parameter: f64) -> Result<Vec3, String> {
1638 let _reader = crate::reader_profile::Point::open(crate::reader_profile::PCURVE, std::panic::Location::caller());
1639 if !self.enabled || self.curve.degree > crate::curve::MAX_STACK_DEGREE || !parameter.is_finite() {
1640 return self.curve.evaluate(parameter);
1641 }
1642 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
1643 let [start, end] = match self.domain {
1644 Some(domain) => domain,
1645 None => {
1646 let domain = self.curve.domain()?;
1647 if self.curve.knots.windows(2).any(|w| w[1] < w[0]) {
1650 self.enabled = false;
1651 return self.curve.evaluate(parameter);
1652 }
1653 self.domain = Some(domain); domain
1654 }
1655 };
1656 let parameter = parameter.clamp(start, end);
1657 if self.previous != Some(parameter.to_bits()) {
1658 let knots = &self.curve.knots;
1659 let degree = self.curve.degree;
1660 let span = match self.span {
1661 Some(mut span) if parameter > start && parameter < end && parameter >= knots[span] => {
1662 while parameter >= knots[span + 1] { span += 1; }
1663 span
1664 }
1665 _ => crate::curve::knot_find_span(knots, degree, parameter),
1666 };
1667 match degree {
1671 1 => self.fill_basis::<1>(span, parameter),
1672 2 => self.fill_basis::<2>(span, parameter),
1673 3 => self.fill_basis::<3>(span, parameter),
1674 4 => self.fill_basis::<4>(span, parameter),
1675 5 => self.fill_basis::<5>(span, parameter),
1676 6 => self.fill_basis::<6>(span, parameter),
1677 7 => self.fill_basis::<7>(span, parameter),
1678 _ => self.fill_basis::<0>(span, parameter),
1679 }
1680 self.span = Some(span);
1681 self.previous = Some(parameter.to_bits());
1682 }
1683 let span = self.span.unwrap();
1684 let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
1685 let mut point = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1686 for (index, value) in self.basis[..=self.curve.degree].iter().enumerate() {
1687 point = point.add(self.curve.control_points[span - self.curve.degree + index].scale(*value));
1688 }
1689 point.point()
1690 }
1691 #[inline(always)]
1692 fn fill_basis<const DEGREE: usize>(&mut self, span: usize, parameter: f64) {
1693 crate::curve::basis_functions_raw_into(&self.curve.knots, DEGREE, span, parameter,
1694 EPSILON, &mut self.basis, &mut self.left, &mut self.right);
1695 }
1696}
1697
1698fn probe_batch_enabled() -> bool { switch!("BREP_PCURVE_PROBE_BATCH", false) }
1699
1700pub fn probe_residual_at(
1704 surface: &NurbsSurface,
1705 curve: &NurbsCurve,
1706 pcurve: &NurbsCurve,
1707 parameters: &[f64],
1708 [t0, t1]: [f64; 2],
1709 locals: &[f64],
1710) -> Result<f64, String> {
1711 crate::work_counts::add(|c| { c.pcurve_probe_passes += 1; c.pcurve_probe_samples += (parameters.len().saturating_sub(1) * locals.len()) as u64; });
1712 let mut worst = 0.0_f64;
1713 let mut reader = ProbeCurveReader::new(pcurve, probe_batch_enabled());
1714 for span in parameters.windows(2) {
1715 for &local in locals {
1716 let fraction = span[0] + (span[1] - span[0]) * local;
1717 let parameter = reader.evaluate(fraction)?;
1718 let on_surface =
1719 section_surface_point(surface, parameter.x, parameter.y, true)?;
1720 let on_curve = section_curve_point(curve, t0 + (t1 - t0) * fraction)?;
1721 let distance = on_surface.sub(on_curve).length();
1726 if !distance.is_finite() {
1727 return Err(format!(
1728 "probe_residual: non-finite image distance {distance} at fraction {fraction}"
1729 ));
1730 }
1731 worst = worst.max(distance);
1732 }
1733 }
1734 Ok(worst)
1735}
1736
1737pub fn native_probe_fractions(curves: &[&NurbsCurve]) -> Result<Vec<f64>, String> {
1744 let locals: Vec<f64> = [0.25, 0.5, 0.75]
1745 .into_iter()
1746 .chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64))
1747 .collect();
1748 let mut fractions = Vec::new();
1749 for curve in curves {
1750 let [q0, q1] = curve.domain()?;
1751 fractions.push(q0);
1752 fractions.push(q1);
1753 let mut knots: Vec<f64> = curve.knots.iter().copied().filter(|k| *k >= q0 && *k <= q1).collect();
1754 knots.dedup();
1755 for span in knots.windows(2).filter(|w| w[1] > w[0]) {
1756 for &local in &locals {
1757 fractions.push(span[0] + (span[1] - span[0]) * local);
1758 }
1759 }
1760 }
1761 fractions.sort_by(f64::total_cmp);
1762 fractions.dedup();
1763 Ok(fractions)
1764}
1765
1766#[derive(Clone, Copy, Debug, PartialEq)]
1775pub struct NativeRead {
1776 pub tracking: f64,
1777 pub deviation: f64,
1778 pub standoff: f64,
1779}
1780
1781fn native_read(surface: &NurbsSurface, curve: &NurbsCurve, pcurve: &NurbsCurve, domain: [f64; 2], fractions: &[f64]) -> Result<NativeRead, String> {
1782 native_read_memo(surface, curve, pcurve, domain, fractions, None)
1783}
1784
1785pub type NativeReadMemo = rustc_hash::FxHashMap<u64, NativeRead>;
1788
1789fn native_read_memo(
1800 surface: &NurbsSurface,
1801 curve: &NurbsCurve,
1802 pcurve: &NurbsCurve,
1803 [t0, t1]: [f64; 2],
1804 fractions: &[f64],
1805 mut memo: Option<&mut NativeReadMemo>,
1806) -> Result<NativeRead, String> {
1807 let mut read = NativeRead { tracking: 0.0, deviation: 0.0, standoff: 0.0 };
1808 let mut reader = ProbeCurveReader::new(pcurve, probe_batch_enabled());
1809 let mut computed = 0u64;
1810 for &fraction in fractions {
1811 let probe = match memo.as_deref().and_then(|memo| memo.get(&fraction.to_bits())) {
1812 Some(&probe) => probe,
1813 None => {
1814 computed += 1;
1815 let parameter = reader.evaluate(fraction)?;
1816 let image = section_surface_point(surface, parameter.x, parameter.y, true)?;
1817 let on_curve = section_curve_point(curve, t0 + (t1 - t0) * fraction)?;
1818 let foot = crate::projection::project_point_to_surface_from_seed(surface, on_curve, [parameter.x, parameter.y])?;
1819 let tracking = image.sub(foot.point).length();
1820 let deviation = image.sub(on_curve).length();
1821 if !(tracking.is_finite() && deviation.is_finite() && foot.distance.is_finite()) {
1822 return Err(format!("native read: non-finite reading at fraction {fraction}"));
1823 }
1824 let probe = NativeRead { tracking, deviation, standoff: foot.distance };
1825 if let Some(memo) = memo.as_deref_mut() {
1826 memo.insert(fraction.to_bits(), probe);
1827 }
1828 probe
1829 }
1830 };
1831 read.tracking = read.tracking.max(probe.tracking);
1832 read.deviation = read.deviation.max(probe.deviation);
1833 read.standoff = read.standoff.max(probe.standoff);
1834 }
1835 crate::work_counts::add(|c| { c.pcurve_native_passes += 1; c.pcurve_native_samples += computed; });
1836 Ok(read)
1837}
1838
1839fn pcurve_read_memo_enabled() -> bool {
1844 crate::switch!("BREP_PCURVE_READ_MEMO", true)
1845}
1846
1847pub fn standoff_candidate_accepted(standing: NativeRead, candidate: NativeRead, candidate_fields_finite: bool, floor: f64) -> bool {
1853 candidate_fields_finite
1854 && candidate.tracking.is_finite()
1855 && candidate.deviation.is_finite()
1856 && candidate.tracking <= floor
1857 && candidate.tracking < standing.tracking
1858 && candidate.deviation <= standing.deviation
1859}
1860
1861pub fn tracking_acceptance_residual(
1867 surface: &NurbsSurface,
1868 curve: &NurbsCurve,
1869 pcurve: &NurbsCurve,
1870 parameters: &[f64],
1871 domain: [f64; 2],
1872) -> Result<f64, String> {
1873 let locals: Vec<f64> = [0.25, 0.5, 0.75]
1874 .into_iter()
1875 .chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64))
1876 .collect();
1877 probe_residual_at(surface, curve, pcurve, parameters, domain, &locals)
1878}
1879
1880pub fn tracking_candidate_accepted(standing: f64, standing_dense: bool, floor: f64, exit: PcurveFitExit, reading: f64) -> bool {
1902 if exit == PcurveFitExit::Converged && !standing_dense {
1903 return reading <= floor && reading < standing;
1904 }
1905 if exit != PcurveFitExit::Converged && !(standing > floor) {
1906 return false;
1907 }
1908 reading.is_finite() && reading <= floor && reading < standing
1909}
1910
1911
1912pub fn judge_tracking_candidate_with_bounds(
1913 standing: f64,
1914 standing_dense: bool,
1915 floor: f64,
1916 exit: PcurveFitExit,
1917 own: f64,
1918 dense: impl FnOnce() -> Result<f64, String>,
1919 bounds: bool,
1920) -> (Result<Option<f64>, String>, bool) {
1921 if bounds && exit != PcurveFitExit::Converged && own > floor {
1925 if crate::profile::profile_enabled() { profile_line!("pcurve.reject_bound kind=quarter_residual"); }
1926 return (Ok(Some(own)), false);
1927 }
1928 let reading = if exit == PcurveFitExit::Converged && !standing_dense {
1929 Ok(Some(own))
1930 } else if exit == PcurveFitExit::Converged || standing > floor {
1931 dense().map(Some)
1932 } else {
1933 Ok(None)
1934 };
1935 let accepted = matches!(
1936 reading,
1937 Ok(Some(value)) if tracking_candidate_accepted(standing, standing_dense, floor, exit, value)
1938 );
1939 (reading, accepted)
1940}
1941
1942pub struct Refinement {
1945 pub exit: PcurveFitExit,
1946 pub residual: f64,
1947 pub off_surface: f64,
1948 pub raised: bool,
1949 pub clamped: [f64; 2],
1952}
1953
1954#[allow(clippy::too_many_arguments)]
1987pub fn refine_pcurve(
1988 surface: &NurbsSurface,
1989 curve: &NurbsCurve,
1990 domain: [f64; 2],
1991 u_domain: [f64; 2],
1992 v_domain: [f64; 2],
1993 floor: f64,
1994 joins: &[f64],
1995 parameters: &mut Vec<f64>,
1996 raw: &mut Vec<[f64; 2]>,
1997 pcurve: &mut NurbsCurve,
1998 off_surface: f64,
1999 clamped: [f64; 2],
2000 mut insert: impl FnMut(f64, Vec3, Vec3) -> Result<(Option<[f64; 2]>, f64), String>,
2001) -> Result<Refinement, String> {
2002 let trace = env_read!("BREP_DEBUG_PCURVE_FIT").is_some();
2005 let call = if trace {
2006 PCURVE_TRACK_CALL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
2007 } else {
2008 0
2009 };
2010 let reject_bounds = PCURVE_REJECT_BOUNDS.with(|state| state.get());
2011 let best = refine_pcurve_pass(surface, curve, domain, u_domain, v_domain,
2012 floor, joins, parameters, raw, pcurve, off_surface, clamped, false, 1.0, false, &mut insert, false)?;
2013 if trace {
2014 eprintln!(
2015 "PCURVE-TRACK call={call} first-pass exit={:?} residual={:e} floor={floor:e} off_surface={:e} samples={} raised={} tracking={}",
2016 best.exit,
2017 best.residual,
2018 best.off_surface,
2019 parameters.len(),
2020 best.raised,
2021 if best.off_surface <= floor { "eligible" } else { "standoff-tracking" }
2022 );
2023 }
2024 if best.off_surface > floor {
2025 if !standoff_tracking_enabled() {
2045 return Ok(best);
2046 }
2047 return standoff_tracking_rungs(surface, curve, domain, u_domain, v_domain, floor, joins,
2048 parameters, raw, pcurve, best, trace, call, &mut insert);
2049 }
2050 let baseline_parameters = parameters.clone();
2055 let baseline_raw = raw.clone();
2056 let baseline_curve = pcurve.clone();
2057 let baseline_off_surface = best.off_surface;
2058 let baseline_clamped = best.clamped;
2059 let standing_misses = best.residual > floor;
2068 Ok(tracking_rungs(
2069 best,
2070 floor,
2071 trace,
2072 call,
2073 true,
2074 |fraction| {
2075 let mut refined_parameters = baseline_parameters.clone();
2076 let mut refined_raw = baseline_raw.clone();
2077 let mut refined_curve = baseline_curve.clone();
2078 let candidate = refine_pcurve_pass(surface, curve, domain, u_domain, v_domain,
2079 floor, joins, &mut refined_parameters, &mut refined_raw, &mut refined_curve,
2080 baseline_off_surface, baseline_clamped, true, fraction, standing_misses, &mut insert, reject_bounds && !standing_misses);
2081 (candidate, (refined_parameters, refined_raw, refined_curve))
2082 },
2083 |state: &RungState| tracking_acceptance_residual(surface, curve, &state.2, &state.0, domain),
2084 |state: &RungState| state.0.len(),
2085 |(refined_parameters, refined_raw, refined_curve): RungState| {
2086 *parameters = refined_parameters;
2087 *raw = refined_raw;
2088 *pcurve = refined_curve;
2089 },
2090 ))
2091}
2092
2093type RungState = (Vec<f64>, Vec<[f64; 2]>, NurbsCurve);
2096
2097#[allow(clippy::too_many_arguments)]
2107pub fn tracking_rungs<S>(
2108 mut best: Refinement,
2109 floor: f64,
2110 trace: bool,
2111 call: u64,
2112 thread_dense: bool,
2113 mut run_pass: impl FnMut(f64) -> (Result<Refinement, String>, S),
2114 mut dense: impl FnMut(&S) -> Result<f64, String>,
2115 samples: impl Fn(&S) -> usize,
2116 mut adopt: impl FnMut(S),
2117) -> Refinement {
2118 let mut standing_dense = false;
2121 let reject_bounds = PCURVE_REJECT_BOUNDS.with(|state| state.get());
2122 for fraction in [0.1, 0.01] {
2123 if best.residual <= floor * fraction {
2124 if trace {
2125 eprintln!(
2126 "PCURVE-TRACK call={call} candidate fraction={fraction} skipped best_residual={:e} <= {:e}",
2127 best.residual,
2128 floor * fraction
2129 );
2130 }
2131 continue;
2132 }
2133 let (candidate, state) = run_pass(fraction);
2134 let judged_dense = matches!(&candidate, Ok(seen) if seen.exit != PcurveFitExit::Converged || standing_dense);
2138 let (effective, accepted) = match &candidate {
2139 Ok(seen) => judge_tracking_candidate_with_bounds(best.residual, standing_dense, floor, seen.exit, seen.residual, || {
2140 dense(&state)
2141 }, reject_bounds),
2142 Err(_) => (Ok(None), false),
2143 };
2144 if trace {
2145 let judged_on = match &effective {
2146 Ok(Some(reading)) => format!("{reading:e}"),
2147 Ok(None) => "-".to_string(),
2148 Err(message) => format!("error:{message:?}"),
2149 };
2150 match &candidate {
2151 Ok(seen) => eprintln!(
2152 "PCURVE-TRACK call={call} candidate fraction={fraction} exit={:?} residual={:e} judged_on={judged_on} standing_dense={standing_dense} floor={floor:e} off_surface={:e} samples={} raised={} residual_meets_floor={} decision={}",
2153 seen.exit,
2154 seen.residual,
2155 seen.off_surface,
2156 samples(&state),
2157 seen.raised,
2158 seen.residual <= floor,
2159 if accepted { "accept" } else { "decline-stop" }
2160 ),
2161 Err(message) => eprintln!(
2162 "PCURVE-TRACK call={call} candidate fraction={fraction} error={message:?} decision=decline-stop"
2163 ),
2164 }
2165 }
2166 match candidate {
2167 Ok(mut candidate) if accepted => {
2168 if let Ok(Some(reading)) = effective {
2170 candidate.residual = reading;
2171 }
2172 if thread_dense {
2174 standing_dense |= judged_dense;
2175 }
2176 adopt(state);
2177 best = candidate;
2178 }
2179 _ => break,
2180 }
2181 }
2182 best
2183}
2184
2185fn standoff_tracking_enabled() -> bool {
2189 switch!("BREP_PCURVE_STANDOFF_TRACKING", true)
2190}
2191
2192#[allow(clippy::too_many_arguments)]
2208fn standoff_tracking_rungs(
2209 surface: &NurbsSurface,
2210 curve: &NurbsCurve,
2211 domain: [f64; 2],
2212 u_domain: [f64; 2],
2213 v_domain: [f64; 2],
2214 floor: f64,
2215 joins: &[f64],
2216 parameters: &mut Vec<f64>,
2217 raw: &mut Vec<[f64; 2]>,
2218 pcurve: &mut NurbsCurve,
2219 mut best: Refinement,
2220 trace: bool,
2221 call: u64,
2222 insert: &mut impl FnMut(f64, Vec3, Vec3) -> Result<(Option<[f64; 2]>, f64), String>,
2223) -> Result<Refinement, String> {
2224 let memoise = pcurve_read_memo_enabled();
2227 let mut standing_memo = NativeReadMemo::default();
2228 let first = native_probe_fractions(&[&*pcurve])
2229 .and_then(|probes| native_read_memo(surface, curve, pcurve, domain, &probes, memoise.then_some(&mut standing_memo)));
2230 if trace {
2231 eprintln!("PCURVE-TRACK call={call} standoff-tracking first-pass native={first:?} floor={floor:e}");
2232 }
2233 let Ok(first) = first else { return Ok(best) };
2234 if first.tracking <= floor {
2235 return Ok(best);
2236 }
2237 let baseline_parameters = parameters.clone();
2238 let baseline_raw = raw.clone();
2239 let baseline_curve = pcurve.clone();
2240 for fraction in [0.1, 0.01] {
2241 let mut refined_parameters = baseline_parameters.clone();
2242 let mut refined_raw = baseline_raw.clone();
2243 let mut refined_curve = baseline_curve.clone();
2244 let candidate = refine_pcurve_pass(surface, curve, domain, u_domain, v_domain, floor, joins,
2245 &mut refined_parameters, &mut refined_raw, &mut refined_curve, best.off_surface, best.clamped,
2246 true, fraction, true, &mut *insert, false);
2247 let mut candidate_memo = NativeReadMemo::default();
2248 let reads = candidate.as_ref().ok().map(|_| {
2249 native_probe_fractions(&[&*pcurve, &refined_curve]).and_then(|probes| {
2250 Ok((
2251 native_read_memo(surface, curve, pcurve, domain, &probes, memoise.then_some(&mut standing_memo))?,
2252 native_read_memo(surface, curve, &refined_curve, domain, &probes, memoise.then_some(&mut candidate_memo))?,
2253 ))
2254 })
2255 });
2256 let fields_finite = matches!(&candidate, Ok(seen) if seen.residual.is_finite() && seen.off_surface.is_finite());
2257 let decision = match &reads {
2258 Some(Ok((standing, read))) => standoff_rung_decision(*standing, *read, fields_finite, floor),
2259 _ => RungDecision::Stop,
2260 };
2261 if trace {
2262 eprintln!(
2263 "PCURVE-TRACK call={call} standoff-tracking fraction={fraction} candidate={} reads={reads:?} decision={}",
2264 match &candidate { Ok(seen) => format!("{:?}/{:e}/raised={}", seen.exit, seen.residual, seen.raised), Err(message) => format!("error:{message:?}") },
2265 match decision { RungDecision::Accept => "accept", RungDecision::Continue => "decline-continue", RungDecision::Stop => "decline-stop" }
2266 );
2267 }
2268 let (Ok(mut taken), Some(Ok((_, read))), RungDecision::Accept) = (candidate, reads, decision) else {
2269 if decision == RungDecision::Continue {
2270 continue;
2271 }
2272 break;
2273 };
2274 taken.residual = read.deviation;
2275 taken.off_surface = taken.off_surface.max(read.standoff);
2276 *parameters = refined_parameters;
2277 *raw = refined_raw;
2278 *pcurve = refined_curve;
2279 standing_memo = candidate_memo;
2281 best = taken;
2282 if read.tracking <= floor * 0.01 {
2283 break;
2284 }
2285 }
2286 Ok(best)
2287}
2288
2289#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2292pub enum RungDecision {
2293 Accept,
2295 Continue,
2300 Stop,
2302}
2303
2304pub fn standoff_rung_decision(standing: NativeRead, candidate: NativeRead, fields_finite: bool, floor: f64) -> RungDecision {
2305 if standoff_candidate_accepted(standing, candidate, fields_finite, floor) {
2306 RungDecision::Accept
2307 } else if candidate.tracking.is_finite() && candidate.tracking < standing.tracking {
2308 RungDecision::Continue
2309 } else {
2310 RungDecision::Stop
2311 }
2312}
2313
2314pub fn takes_raise(exit: PcurveFitExit, raised: bool, residual: f64, off_surface: f64, floor: f64, unmet_tracking: bool) -> bool {
2321 exit == PcurveFitExit::SampleCeiling && !raised && (residual > off_surface + floor || unmet_tracking)
2322}
2323
2324pub fn refine_pcurve_pass(
2325 surface: &NurbsSurface,
2326 curve: &NurbsCurve,
2327 [t0, t1]: [f64; 2],
2328 [u0, u1]: [f64; 2],
2329 [v0, v1]: [f64; 2],
2330 floor: f64,
2331 joins: &[f64],
2332 parameters: &mut Vec<f64>,
2333 raw: &mut Vec<[f64; 2]>,
2334 pcurve: &mut NurbsCurve,
2335 mut off_surface: f64,
2336 mut clamped: [f64; 2],
2337 track_projection: bool,
2338 tracking_fraction: f64,
2339 raise_unmet_tracking: bool,
2340 mut insert: impl FnMut(f64, Vec3, Vec3) -> Result<(Option<[f64; 2]>, f64), String>,
2341 reject_budget: bool,
2342) -> Result<Refinement, String> {
2343 let _clock = PcurvePhaseClock::new("refinement", parameters.len(), track_projection);
2344 let tracking_floor = if track_projection { floor * tracking_fraction } else { floor };
2345 let mut max_samples = MAX_PCURVE_SAMPLES;
2346 let mut raised = false;
2347 loop {
2348 let mut exit = PcurveFitExit::RoundBudget;
2352 let mut residual = None;
2353 for round in 0..4 {
2354 crate::work_counts::add(|c| c.refinement_rounds += 1);
2355 if parameters.len() >= max_samples {
2356 exit = PcurveFitExit::SampleCeiling;
2357 break;
2358 }
2359 let mut inserts = Vec::new();
2360 let mut round_max = 0.0_f64;
2361 let mut truncated = false;
2362 let mut skipped_narrow = false;
2363 let mut reader = ProbeCurveReader::new(pcurve, probe_batch_enabled());
2364 for index in 0..parameters.len() - 1 {
2365 if parameters.len() + inserts.len() >= max_samples {
2366 truncated = true;
2367 break;
2368 }
2369 let start = parameters[index];
2370 let end = parameters[index + 1];
2371 if end - start < if track_projection { SPAN_FLOOR } else { 1e-3 } {
2375 skipped_narrow = true;
2376 continue;
2377 }
2378 for local_fraction in [0.25, 0.5, 0.75] {
2379 if parameters.len() + inserts.len() >= max_samples {
2380 truncated = true;
2381 break;
2382 }
2383 let fraction = start + (end - start) * local_fraction;
2384 let parameter = reader.evaluate(fraction)?;
2385 let on_surface =
2386 section_surface_point(surface, parameter.x, parameter.y, true)?;
2387 let on_curve = section_curve_point(curve, t0 + (t1 - t0) * fraction)?;
2388 let deviation = on_surface.sub(on_curve).length();
2389 if !deviation.is_finite() {
2395 return Err(format!(
2396 "refine_pcurve_pass: non-finite station distance {deviation} at fraction {fraction}"
2397 ));
2398 }
2399 round_max = round_max.max(deviation);
2400 if deviation <= tracking_floor {
2401 continue;
2402 }
2403 let (surface_parameter, gap) = insert(fraction, parameter, on_curve)?;
2404 off_surface = off_surface.max(gap);
2405 if let Some(surface_parameter) = surface_parameter {
2406 if raised || track_projection {
2415 let projected =
2416 section_surface_point(surface, surface_parameter[0], surface_parameter[1], false)?;
2417 if on_surface.sub(projected).length() <= tracking_floor {
2418 continue;
2419 }
2420 }
2421 inserts.push((index + 1, fraction, surface_parameter));
2422 }
2423 }
2424 }
2425 if inserts.is_empty() {
2426 exit = if truncated {
2431 PcurveFitExit::SampleCeiling
2432 } else if round_max > floor {
2433 PcurveFitExit::Stalled
2434 } else if skipped_narrow {
2435 PcurveFitExit::SpanFloor
2436 } else {
2437 residual = Some(round_max);
2438 PcurveFitExit::Converged
2439 };
2440 break;
2441 }
2442 if reject_budget && round == 3 && !truncated {
2447 if crate::profile::profile_enabled() { profile_line!("pcurve.reject_bound kind=fifth_round"); }
2448 return Err("pcurve tracking candidate requires a fifth round".into());
2449 }
2450 for (at, fraction, surface_parameter) in inserts.into_iter().rev() {
2451 parameters.insert(at, fraction);
2452 raw.insert(at, surface_parameter);
2453 }
2454 let (rebuilt, excursion, distance) = build_interpolant_joined(surface, raw, parameters, joins)?;
2455 *pcurve = rebuilt;
2456 clamped = [excursion, distance];
2457 if truncated {
2458 exit = PcurveFitExit::SampleCeiling;
2459 break;
2460 }
2461 }
2462 let residual = match residual {
2463 Some(measured) => measured,
2464 None => probe_residual(
2468 surface,
2469 curve,
2470 pcurve,
2471 parameters,
2472 [t0, t1],
2473 [u0, u1],
2474 [v0, v1],
2475 )?,
2476 };
2477 if exit == PcurveFitExit::SpanFloor && residual <= floor {
2478 exit = PcurveFitExit::Converged;
2479 }
2480 let unmet_tracking = track_projection
2497 && raise_unmet_tracking
2498 && exit == PcurveFitExit::SampleCeiling
2499 && !raised
2500 && native_probe_fractions(&[&*pcurve])
2501 .and_then(|probes| native_read(surface, curve, pcurve, [t0, t1], &probes))
2502 .is_ok_and(|read| read.tracking > tracking_floor);
2503 if takes_raise(exit, raised, residual, off_surface, floor, unmet_tracking) {
2504 raised = true;
2505 max_samples = PCURVE_RAISED_SAMPLES;
2506 continue;
2507 }
2508 return Ok(Refinement {
2509 exit,
2510 residual,
2511 off_surface,
2512 raised,
2513 clamped,
2514 });
2515 }
2516}
2517
2518struct AffineInversion {
2526 origin: Vec3,
2527 du: Vec3,
2528 dv: Vec3,
2529 u0: f64,
2530 v0: f64,
2531 uu: f64,
2532 uv: f64,
2533 vv: f64,
2534 determinant: f64,
2535}
2536
2537impl AffineInversion {
2538 fn of(surface: &NurbsSurface) -> Result<Option<Self>, String> {
2543 if !surface.is_affine()? {
2544 return Ok(None);
2545 }
2546 let ([u0, _], [v0, _]) = surface_domains(surface)?;
2547 let (origin, du, dv) = surface.deriv1(u0, v0)?;
2548 let uu = du.dot(du);
2549 let uv = du.dot(dv);
2550 let vv = dv.dot(dv);
2551 let determinant = uu * vv - uv * uv;
2552 if determinant.abs() <= 1e-18 {
2553 return Ok(None);
2554 }
2555 Ok(Some(Self {
2556 origin,
2557 du,
2558 dv,
2559 u0,
2560 v0,
2561 uu,
2562 uv,
2563 vv,
2564 determinant,
2565 }))
2566 }
2567
2568 fn uv_of(&self, point: Vec3) -> [f64; 2] {
2569 let delta = point.sub(self.origin);
2570 let along_u = delta.dot(self.du);
2571 let along_v = delta.dot(self.dv);
2572 [
2573 self.u0 + (along_u * self.vv - along_v * self.uv) / self.determinant,
2574 self.v0 + (along_v * self.uu - along_u * self.uv) / self.determinant,
2575 ]
2576 }
2577
2578 fn image_of(&self, curve: &NurbsCurve) -> Result<NurbsCurve, String> {
2581 let control_points = curve
2582 .control_points
2583 .iter()
2584 .map(|control| {
2585 let [u, v] = self.uv_of(control.point()?);
2586 Ok(Vec4::from_point(Vec3::new(u, v, 0.0), control.w))
2587 })
2588 .collect::<Result<Vec<_>, String>>()?;
2589 NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
2590 }
2591}
2592
2593fn sphere_iso_enabled() -> bool {
2594 env_read!("BREP_PCURVE_SPHERE_ISO").is_none_or(|mode| mode != "0")
2595}
2596
2597pub fn sphere_iso_fit(surface: &NurbsSurface, curve: &NurbsCurve) -> Option<PcurveFit> {
2604 if surface.degree_u != 2 { return None; }
2607 let [t0, t1] = curve.domain().ok()?;
2608 let [u0, u1] = surface.domain_u().ok()?;
2609 let [v0, v1] = surface.domain_v().ok()?;
2610 if !matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })) { return None; }
2611 let middle = curve.evaluate(t0 + (t1 - t0) * 0.5).ok()?;
2612 let projected = project_point_to_surface(surface, middle).ok()?;
2613 let mut candidates = vec![projected.u];
2614 for &knot in &surface.knots_u {
2617 if (knot - projected.u).abs() <= 1e-12 && !candidates.contains(&knot) { candidates.push(knot); }
2618 }
2619 for u in candidates {
2620 if !(u >= u0 && u <= u1) { continue; }
2621 let iso = surface.iso_curve_u(u).ok()?;
2622 if iso.degree != curve.degree || iso.knots.len() != curve.knots.len()
2623 || iso.control_points.len() != curve.control_points.len() { continue; }
2624 for reverse in [false, true] {
2625 let n = iso.control_points.len();
2626 fn exact_difference(a: f64, b: f64) -> Option<f64> {
2632 if !(a.is_finite() && b.is_finite()) || a.abs().max(b.abs()) > 1e100 { return None; }
2633 let x = a - b;
2634 let bv = a - x;
2635 let av = x + bv;
2636 let error = (a - av) + (bv - b);
2637 (error == 0.).then_some(x)
2638 }
2639 fn exact_fraction(offset: f64, span: f64) -> Option<f64> {
2640 if !(1e-100..=1e100).contains(&span) { return None; }
2641 let ratio = offset / span;
2642 if !(0.0..=1.0).contains(&ratio) || (ratio != 0. && ratio < 1e-100) { return None; }
2643 (ratio.mul_add(span, -offset) == 0.).then_some(ratio)
2644 }
2645 let knots_match = (|| {
2646 let section_span = exact_difference(t1, t0)?;
2647 let native_span = exact_difference(v1, v0)?;
2648 for (i, &knot) in curve.knots.iter().enumerate() {
2649 let section = exact_difference(knot, t0)?;
2650 let native = if reverse { exact_difference(v1, iso.knots[iso.knots.len() - 1 - i])? }
2651 else { exact_difference(iso.knots[i], v0)? };
2652 if exact_fraction(section, section_span)? != exact_fraction(native, native_span)? { return None; }
2653 }
2654 Some(())
2655 })().is_some();
2656 if !knots_match { continue; }
2657 let mut bound = 0.0_f64;
2658 let mut matches = true;
2659 for (i, control) in curve.control_points.iter().enumerate() {
2660 let native = &iso.control_points[if reverse { n - 1 - i } else { i }];
2661 if !(control.w > 0.) || control.w != native.w { matches = false; break; }
2662 let distance = control.point().ok()?.sub(native.point().ok()?).length();
2663 if !distance.is_finite() { matches = false; break; }
2664 bound = bound.max(distance);
2665 }
2666 if !matches || bound > PCURVE_REFINEMENT_TOLERANCE * 0.0625 { continue; }
2667 let (start, end) = if reverse { (v1, v0) } else { (v0, v1) };
2668 let pcurve = NurbsCurve::new(1, vec![0., 0., 1., 1.], vec![
2669 Vec4::from_point(Vec3::new(u, start, 0.), 1.),
2670 Vec4::from_point(Vec3::new(u, end, 0.), 1.),
2671 ]).ok()?;
2672 for i in 0..=96 {
2677 let fraction = i as f64 / 96.;
2678 let uv = pcurve.evaluate(fraction).ok()?;
2679 let image = surface.evaluate(uv.x, uv.y).ok()?;
2680 let on_curve = curve.evaluate(t0 + (t1 - t0) * fraction).ok()?;
2681 let error = image.sub(on_curve).length();
2682 if !error.is_finite() { matches = false; break; }
2683 bound = bound.max(error);
2684 }
2685 if !matches || bound > PCURVE_REFINEMENT_TOLERANCE * 0.0625 { continue; }
2686 crate::work_counts::constructed("analytic_certified", 0, pcurve.control_points.len());
2687 return Some(PcurveFit { curve: pcurve, report: PcurveFitReport {
2688 residual: bound, floor: PCURVE_REFINEMENT_TOLERANCE, samples: 2,
2689 exit: PcurveFitExit::Converged, off_surface: bound, raised: false,
2690 clamped_excursion: 0., clamped_distance: 0.,
2691 } });
2692 }
2693 }
2694 None
2695}
2696
2697pub fn fit_pcurve_on_surface(
2707 surface: &NurbsSurface,
2708 curve: &NurbsCurve,
2709) -> Result<PcurveFit, String> {
2710 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
2711 crate::work_counts::add(|c| c.fit_calls += 1);
2712 if sphere_iso_enabled() {
2713 if let Some(fit) = sphere_iso_fit(surface, curve) { return Ok(fit); }
2714 }
2715 let mode = env_read!("BREP_PCURVE_EVAL_CACHE").unwrap_or_default();
2716 let bounds = env_read!("BREP_PCURVE_REJECT_BOUNDS").unwrap_or_else(|| "on".into());
2717 let stack = env_read!("BREP_PCURVE_STACK_POINT").unwrap_or_else(|| "on".into());
2718 if mode == "check" || bounds == "check" || stack == "check" {
2719 let old = fit_pcurve_on_surface_cached(surface, curve, false, false, false)?;
2720 if matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })) {
2721 let candidate = fit_pcurve_on_surface_cached(surface, curve, mode == "check" || mode == "on" || mode == "1", bounds == "check" || bounds == "on" || bounds == "1", stack == "check" || stack == "on" || stack == "1");
2722 let identical = candidate.as_ref().is_ok_and(|new| {
2723 old.curve.degree == new.curve.degree
2724 && old.curve.knots.len() == new.curve.knots.len()
2725 && old.curve.knots.iter().zip(&new.curve.knots).all(|(a, b)| a.to_bits() == b.to_bits())
2726 && old.curve.control_points.len() == new.curve.control_points.len()
2727 && old.curve.control_points.iter().zip(&new.curve.control_points).all(|(a, b)| {
2728 [a.x.to_bits(), a.y.to_bits(), a.z.to_bits(), a.w.to_bits()]
2729 == [b.x.to_bits(), b.y.to_bits(), b.z.to_bits(), b.w.to_bits()]
2730 }) && old.report == new.report
2731 });
2732 if let Ok(path) = std::env::var("BREP_PCURVE_EVAL_CENSUS") {
2733 use std::io::Write;
2734 if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
2735 let _ = writeln!(file, "pcurve.eval_census identical={identical} controls={} samples={}", old.curve.control_points.len(), old.report.samples);
2736 }
2737 }
2738 }
2739 return Ok(old);
2740 }
2741 fit_pcurve_on_surface_cached(surface, curve, mode == "1" || mode == "on", bounds == "1" || bounds == "on", stack == "1" || stack == "on")
2742}
2743
2744pub fn fit_pcurve_on_surface_cached(surface: &NurbsSurface, curve: &NurbsCurve, enabled: bool, bounds: bool, stack: bool) -> Result<PcurveFit, String> {
2745 let _stack = PcurveStackPointScope::open(stack && matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })));
2746 let _samples = PcurveSampleScope::open(surface, curve, enabled
2750 || !matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })));
2751 let _bounds = PcurveRejectScope::open(bounds && matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })));
2752 let [t0, t1] = curve.domain()?;
2753 if surface.is_affine()? {
2754 let Some(inversion) = AffineInversion::of(surface)? else {
2755 return Err("build_pcurve_on_surface: singular affine parameterization".into());
2756 };
2757 let pcurve = inversion.image_of(curve)?;
2758 crate::work_counts::constructed("affine", 0, pcurve.control_points.len());
2759 return Ok(PcurveFit {
2760 report: PcurveFitReport {
2761 residual: 0.0,
2762 floor: PCURVE_REFINEMENT_TOLERANCE,
2763 samples: pcurve.control_points.len(),
2764 exit: PcurveFitExit::Converged,
2765 off_surface: 0.0,
2766 raised: false,
2767 clamped_excursion: 0.0,
2768 clamped_distance: 0.0,
2769 },
2770 curve: pcurve,
2771 });
2772 }
2773
2774 let scale = 1.0 + curve.evaluate((t0 + t1) / 2.0)?.length();
2775 let drop_tolerance = 1e-4 * scale;
2776 let endpoint_tolerance = 1e-3 * scale;
2777 let refinement_tolerance = PCURVE_REFINEMENT_TOLERANCE;
2778 let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
2779 let invert =
2780 |fraction: f64| invert_checked(surface, section_curve_point(curve, t0 + (t1 - t0) * fraction)?);
2781
2782 let mut parameters = Vec::with_capacity(25);
2783 let mut raw_surface_parameters = Vec::with_capacity(25);
2784 let mut off_surface = 0.0_f64;
2787 let corners = range_breaks(curve, t0, t1, true);
2790 let mut stations: Vec<f64> = (0..=24).map(|index| index as f64 / 24.0).collect();
2791 stations.retain(|station| {
2794 *station == 0.0 || *station == 1.0 || corners.contains(station)
2795 || !corners.iter().any(|corner| (*station - corner).abs() <= SPAN_FLOOR)
2796 });
2797 for &corner in &corners {
2798 let at = stations.partition_point(|value| *value < corner);
2799 if stations.get(at) != Some(&corner) {
2800 stations.insert(at, corner);
2801 }
2802 }
2803 let joins = corners;
2804 for (index, &fraction) in stations.iter().enumerate() {
2805 let (parameter, distance) = invert(fraction)?;
2806 off_surface = off_surface.max(distance);
2807 if distance > drop_tolerance && index != 0 && index != stations.len() - 1 {
2808 continue;
2809 }
2810 if distance > endpoint_tolerance {
2811 if std::env::var("BREP_DEBUG_PCURVE").is_ok() {
2812 let p3 = curve.evaluate(t0 + (t1 - t0) * fraction).ok();
2813 let p0 = curve.evaluate(t0).ok();
2814 let p1 = curve.evaluate(t1).ok();
2815 eprintln!(
2816 "PCURVE-FAIL idx={index} frac={fraction} dist={distance} endpt_tol={endpoint_tolerance} scale={scale}\n curve3D@frac={p3:?}\n curve3D@t0={p0:?} curve3D@t1={p1:?}\n surf_domain=u[{u0},{u1}] v[{v0},{v1}] invpar={parameter:?}\n surf@invpar={:?}",
2817 surface.evaluate(parameter[0], parameter[1]).ok()
2818 );
2819 }
2820 return Err(format!(
2821 "build_pcurve_on_surface: endpoint projection failed (distance={distance})"
2822 ));
2823 }
2824 parameters.push(fraction);
2825 raw_surface_parameters.push(parameter);
2826 }
2827
2828 let (mut pcurve, excursion, distance) =
2829 build_interpolant_joined(surface, &raw_surface_parameters, ¶meters, &joins)?;
2830 let refinement = refine_pcurve(
2831 surface,
2832 curve,
2833 [t0, t1],
2834 [u0, u1],
2835 [v0, v1],
2836 refinement_tolerance,
2837 &joins,
2838 &mut parameters,
2839 &mut raw_surface_parameters,
2840 &mut pcurve,
2841 off_surface,
2842 [excursion, distance],
2843 |fraction, _parameter, _on_curve| {
2844 let (surface_parameter, distance) = invert(fraction)?;
2845 Ok((
2846 (distance <= drop_tolerance).then_some(surface_parameter),
2847 distance,
2848 ))
2849 },
2850 )?;
2851 crate::work_counts::constructed("projected_global", parameters.len(), pcurve.control_points.len());
2852 Ok(PcurveFit {
2853 curve: pcurve,
2854 report: PcurveFitReport {
2855 residual: refinement.residual,
2856 floor: refinement_tolerance,
2857 samples: parameters.len(),
2858 exit: refinement.exit,
2859 off_surface: refinement.off_surface,
2860 raised: refinement.raised,
2861 clamped_excursion: refinement.clamped[0],
2862 clamped_distance: refinement.clamped[1],
2863 },
2864 })
2865}
2866
2867pub fn build_pcurve_on_surface(
2872 surface: &NurbsSurface,
2873 curve: &NurbsCurve,
2874) -> Result<NurbsCurve, String> {
2875 let fit = fit_pcurve_on_surface(surface, curve)?;
2876 record_fit(&fit.report);
2877 Ok(fit.curve)
2878}
2879
2880struct SectionFitClock {
2882 started: Option<web_time::Instant>,
2883 global: std::time::Duration,
2884 seeded: bool,
2885}
2886impl SectionFitClock {
2887 fn new() -> Self {
2888 Self { started: crate::profile::profile_enabled().then(web_time::Instant::now),
2889 global: std::time::Duration::ZERO, seeded: false }
2890 }
2891}
2892impl Drop for SectionFitClock {
2893 fn drop(&mut self) {
2894 if let Some(started) = self.started {
2895 crate::profile::profile_emit(format_args!("pcurve.section_time global={:.3} seeded={:.3} result={}",
2896 self.global.as_secs_f64() * 1000.0,
2897 started.elapsed().saturating_sub(self.global).as_secs_f64() * 1000.0,
2898 if self.seeded { "seeded" } else { "global" }));
2899 }
2900 }
2901}
2902
2903pub fn fit_pcurve_on_surface_marched(
2934 surface: &NurbsSurface,
2935 curve: &NurbsCurve,
2936) -> Result<PcurveFit, String> {
2937 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
2938 crate::work_counts::add(|c| c.fit_calls += 1);
2939 fn run(surface: &NurbsSurface, curve: &NurbsCurve, eager: bool) -> Result<PcurveFit, String> {
2940 let _samples = PcurveSampleScope::open(surface, curve, true);
2943 let mut clock = SectionFitClock::new();
2944 let mut fallback = || {
2948 let started = clock.started.map(|_| web_time::Instant::now());
2949 let fit = fit_pcurve_on_surface(surface, curve);
2950 if let Some(started) = started { clock.global += started.elapsed(); }
2951 fit
2952 };
2953 let global = if eager { Some(fallback()?) } else { None };
2954 if !eager { curve.domain()?; }
2958 if env_read!("BREP_SECTION_PCURVE_MARCH").as_deref() == Some("0") || surface.is_affine()? {
2959 return global.map_or_else(&mut fallback, Ok);
2960 }
2961 let [t0, t1] = curve.domain()?;
2962 if curve.evaluate(t0)?.sub(curve.evaluate(t1)?).length() <= 1e-6 {
2965 return global.map_or_else(&mut fallback, Ok);
2966 }
2967 const SAMPLES: usize = 24;
2968 let fractions: Vec<f64> = (0..=SAMPLES).map(|i| i as f64 / SAMPLES as f64).collect();
2969 let edge: Vec<Vec3> = fractions
2970 .iter()
2971 .map(|fraction| curve.evaluate(t0 + (t1 - t0) * fraction))
2972 .collect::<Result<Vec<_>, _>>()?;
2973 let scale = 1.0 + curve.evaluate((t0 + t1) / 2.0)?.length();
2974 let endpoint_tolerance = 1e-3 * scale;
2975 let (first, first_distance) = invert_checked(surface, edge[0])?;
2976 let (last, last_distance) = invert_checked(surface, edge[SAMPLES])?;
2977 if first_distance > endpoint_tolerance || last_distance > endpoint_tolerance {
2978 return global.map_or_else(&mut fallback, Ok);
2979 }
2980 let mut off_surface = first_distance.max(last_distance);
2983 let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
2984 let u_span = (u1 - u0).abs().max(EPSILON);
2985 let v_span = (v1 - v0).abs().max(EPSILON);
2986 let (closed_u, closed_v) = surface_closedness(surface)?;
2987 let norm_step = |a: [f64; 2], b: [f64; 2]| -> f64 {
2988 let mut du = a[0] - b[0];
2989 if closed_u {
2990 while du > 0.5 * u_span {
2991 du -= u_span;
2992 }
2993 while du < -0.5 * u_span {
2994 du += u_span;
2995 }
2996 }
2997 let mut dv = a[1] - b[1];
2998 if closed_v {
2999 while dv > 0.5 * v_span {
3000 dv -= v_span;
3001 }
3002 while dv < -0.5 * v_span {
3003 dv += v_span;
3004 }
3005 }
3006 ((du / u_span).powi(2) + (dv / v_span).powi(2)).sqrt()
3007 };
3008 let mut raw = vec![first];
3010 let mut previous = first;
3011 for index in 1..SAMPLES {
3012 let seeded =
3013 crate::projection::project_point_to_surface_from_seed(surface, edge[index], previous)?;
3014 let (_, global_distance) = invert_checked(surface, edge[index])?;
3015 if seeded.distance > 4.0 * global_distance + endpoint_tolerance {
3019 return global.map_or_else(&mut fallback, Ok);
3020 }
3021 off_surface = off_surface.max(seeded.distance);
3022 previous = [seeded.u, seeded.v];
3023 raw.push(previous);
3024 }
3025 raw.push(last);
3026 let mut steps: Vec<f64> = (1..raw.len())
3032 .map(|i| norm_step(raw[i], raw[i - 1]))
3033 .collect();
3034 let endpoint_gap = steps.pop().unwrap_or(0.0);
3035 steps.sort_by(f64::total_cmp);
3036 let median = steps
3037 .get(steps.len() / 2)
3038 .copied()
3039 .unwrap_or(0.0)
3040 .max(EPSILON);
3041 if endpoint_gap > (4.0 * median).max(0.05) {
3042 return global.map_or_else(&mut fallback, Ok);
3043 }
3044 let mut parameters = fractions;
3048 let (mut pcurve, excursion, distance) = build_interpolant(surface, &raw, ¶meters)?;
3049 let refinement_tolerance = PCURVE_REFINEMENT_TOLERANCE;
3050 let refinement = refine_pcurve(
3053 surface,
3054 curve,
3055 [t0, t1],
3056 [u0, u1],
3057 [v0, v1],
3058 refinement_tolerance,
3059 &[],
3060 &mut parameters,
3061 &mut raw,
3062 &mut pcurve,
3063 off_surface,
3064 [excursion, distance],
3065 |_fraction, seed, on_curve| {
3066 let seeded = crate::projection::project_point_to_surface_from_seed(surface, on_curve, [seed.x, seed.y])?;
3067 Ok((Some([seeded.u, seeded.v]), seeded.distance))
3068 },
3069 )?;
3070 clock.seeded = true;
3071 crate::work_counts::constructed("projected_seeded", parameters.len(), pcurve.control_points.len());
3072 Ok(PcurveFit {
3073 curve: pcurve,
3074 report: PcurveFitReport {
3075 residual: refinement.residual,
3076 floor: refinement_tolerance,
3077 samples: parameters.len(),
3078 exit: refinement.exit,
3079 off_surface: refinement.off_surface,
3080 raised: refinement.raised,
3081 clamped_excursion: refinement.clamped[0],
3082 clamped_distance: refinement.clamped[1],
3083 },
3084 })
3085 }
3086
3087 let mode = match std::env::var("BREP_PCURVE_LAZY_GLOBAL") {
3088 Ok(mode) => mode,
3089 Err(std::env::VarError::NotPresent) => "on".to_owned(),
3090 Err(std::env::VarError::NotUnicode(_)) => String::new(),
3091 };
3092 if mode != "check" {
3093 return run(surface, curve, !matches!(mode.as_str(), "1" | "on"));
3094 }
3095 let lazy_surface = surface.clone();
3098 let lazy_curve = curve.clone();
3099 let eager = run(surface, curve, true);
3100 let lazy = run(&lazy_surface, &lazy_curve, false);
3101 let identical = match (&eager, &lazy) {
3102 (Ok(a), Ok(b)) => {
3103 a.curve.degree == b.curve.degree
3104 && a.curve.knots.len() == b.curve.knots.len()
3105 && a.curve.knots.iter().zip(&b.curve.knots).all(|(a,b)| a.to_bits() == b.to_bits())
3106 && a.curve.control_points.len() == b.curve.control_points.len()
3107 && a.curve.control_points.iter().zip(&b.curve.control_points).all(|(a,b)| {
3108 [a.x.to_bits(),a.y.to_bits(),a.z.to_bits(),a.w.to_bits()]
3109 == [b.x.to_bits(),b.y.to_bits(),b.z.to_bits(),b.w.to_bits()]
3110 })
3111 && a.report == b.report
3112 && [a.report.residual, a.report.floor, a.report.off_surface,
3113 a.report.clamped_excursion, a.report.clamped_distance].map(f64::to_bits)
3114 == [b.report.residual, b.report.floor, b.report.off_surface,
3115 b.report.clamped_excursion, b.report.clamped_distance].map(f64::to_bits)
3116 }
3117 (Err(a), Err(b)) => a == b,
3118 _ => false,
3119 };
3120 if let Ok(path) = std::env::var("BREP_PCURVE_LAZY_GLOBAL_CENSUS") {
3121 use std::io::Write;
3122 let mut file = std::fs::OpenOptions::new().create(true).append(true).open(path)
3123 .expect("open lazy-global differential ledger");
3124 writeln!(file, "pcurve.lazy_global identical={identical} eager_ok={} lazy_ok={} degree={} controls={}",
3125 eager.is_ok(), lazy.is_ok(), curve.degree, curve.control_points.len())
3126 .expect("append lazy-global differential ledger");
3127 }
3128 assert!(identical, "lazy global pcurve fallback changed the curve, report or error");
3129 eager
3130}
3131
3132pub fn build_pcurve_on_surface_marched(
3136 surface: &NurbsSurface,
3137 curve: &NurbsCurve,
3138) -> Result<NurbsCurve, String> {
3139 let fit = fit_pcurve_on_surface_marched(surface, curve)?;
3140 record_fit(&fit.report);
3141 Ok(fit.curve)
3142}
3143
3144pub fn fit_pcurve_on_surface_range(
3152 surface: &NurbsSurface,
3153 curve: &NurbsCurve,
3154 edge_start: f64,
3155 edge_end: f64,
3156 forward: bool,
3157 tolerance: f64,
3158) -> Result<PcurveFit, String> {
3159 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
3160 crate::work_counts::add(|c| c.fit_calls += 1);
3161 if let Some(exact) =
3162 affine_pcurve_on_range(surface, curve, edge_start, edge_end, forward, tolerance)?
3163 {
3164 return Ok(exact);
3165 }
3166 fit_pcurve_on_surface_range_dense(
3167 surface, curve, edge_start, edge_end, forward, tolerance, 64, 3, 513,
3168 )
3169}
3170
3171pub fn refine_import_projected_range(
3175 surface: &NurbsSurface,
3176 curve: &NurbsCurve,
3177 edge_start: f64,
3178 edge_end: f64,
3179 forward: bool,
3180 legacy: PcurveFit,
3181) -> PcurveFit {
3182 let _feet = FootMemoScope::precision(surface);
3183 let evaluate = |fraction: f64| {
3184 let along = if forward { fraction } else { 1.0 - fraction };
3185 curve.evaluate(edge_start + (edge_end - edge_start) * along)
3186 };
3187 let Ok(fixed) = range_use_probes(&[&legacy.curve], curve, edge_start, edge_end, forward) else { return legacy };
3188 let Ok((old, _)) = common_station_read_with_excess(surface, &evaluate, &legacy.curve, &legacy.curve, &fixed) else { return legacy };
3189 if old[0] <= PCURVE_REFINEMENT_TOLERANCE { return legacy; }
3190 let breaks = range_breaks(curve, edge_start, edge_end, forward);
3191 for span_floor in [SPAN_FLOOR, SPAN_FLOOR * 0.01] {
3196 let Ok(candidate) = fit_station_pcurve_mode(surface, &evaluate, &breaks, &breaks,
3197 PCURVE_REFINEMENT_TOLERANCE * 0.1, 64, 3, 513, span_floor, true, Some(&legacy.curve), &fixed) else { return legacy };
3198 let Ok(probes) = range_use_probes(&[&legacy.curve, &candidate.curve], curve, edge_start, edge_end, forward) else { return legacy };
3199 let readings = common_station_read_with_excess(surface, &evaluate, &legacy.curve, &candidate.curve, &probes);
3200 let accepted = matches!(&readings, Ok((old, new)) if floor_admits(*old, *new));
3201 if station_fit_tracing() {
3202 eprintln!("STATION-FIT import projected challenger: span_floor={span_floor:e} old={:?} candidate={:?} common={readings:?} accepted={accepted}", legacy.report, candidate.report);
3203 }
3204 if accepted { return candidate; }
3205 if candidate.report.exit != PcurveFitExit::SpanFloor { break; }
3206 }
3207 legacy
3208}
3209
3210pub fn build_pcurve_on_surface_range(
3214 surface: &NurbsSurface,
3215 curve: &NurbsCurve,
3216 edge_start: f64,
3217 edge_end: f64,
3218 forward: bool,
3219 tolerance: f64,
3220) -> Result<NurbsCurve, String> {
3221 accept_fit(fit_pcurve_on_surface_range(
3222 surface, curve, edge_start, edge_end, forward, tolerance,
3223 )?)
3224}
3225
3226fn station_fit_tracing() -> bool {
3229 debug_flag!("BREP_DEBUG_STATION_FIT")
3230}
3231
3232pub const SPAN_FLOOR: f64 = 1e-6;
3239
3240const RAISED_ROUNDS: usize = 40;
3243
3244pub const PCURVE_OFF_BAR: &str = "pcurve fit refused: the trim misses its stations by";
3246
3247fn accept_fit(fit: PcurveFit) -> Result<NurbsCurve, String> {
3260 let report = fit.report;
3261 if report.on_bar() {
3262 return Ok(fit.curve);
3263 }
3264 Err(off_bar_message(&report))
3265}
3266
3267fn off_bar_message(report: &PcurveFitReport) -> String {
3268 format!(
3269 "{PCURVE_OFF_BAR} {:.3e} out of sample against a bar of {:.3e} (asked {:.1e}, the \
3270 stations stand {:.3e} off the carrier; {:?} at {} samples{}{})",
3271 report.residual,
3272 report.floor + report.off_surface,
3273 report.floor,
3274 report.off_surface,
3275 report.exit,
3276 report.samples,
3277 if report.raised { ", after the raise" } else { "" },
3278 if report.clamped_excursion > 0.0 {
3279 format!(
3280 "; clamped into the chart by {:.3e} in parameter, {:.3e} in 3D",
3281 report.clamped_excursion, report.clamped_distance
3282 )
3283 } else {
3284 String::new()
3285 },
3286 )
3287}
3288
3289pub const PCURVE_OFF_BAR_WHAT: &str = "pcurve_fit_off_bar";
3295
3296pub fn is_pcurve_off_bar(refusal: &crate::KernelRefusal) -> bool {
3298 matches!(&refusal.class, crate::RefusalClass::NonConvergence { what } if what == PCURVE_OFF_BAR_WHAT)
3299}
3300
3301pub fn build_pcurve_on_surface_range_classed(
3305 surface: &NurbsSurface,
3306 curve: &NurbsCurve,
3307 edge_start: f64,
3308 edge_end: f64,
3309 forward: bool,
3310 tolerance: f64,
3311 stage: KernelStage,
3312 what: &'static str,
3313) -> Result<NurbsCurve, crate::KernelRefusal> {
3314 use crate::OrRefuse;
3315 let fit = fit_pcurve_on_surface_range(surface, curve, edge_start, edge_end, forward, tolerance)
3316 .or_refuse(stage, what)?;
3317 accept_fit_classed(fit, stage)
3318}
3319
3320pub fn accept_fit_classed(fit: PcurveFit, stage: KernelStage) -> Result<NurbsCurve, crate::KernelRefusal> {
3323 if fit.report.on_bar() {
3324 return Ok(fit.curve);
3325 }
3326 Err(crate::KernelRefusal {
3327 class: crate::RefusalClass::NonConvergence { what: PCURVE_OFF_BAR_WHAT.into() },
3328 stage,
3329 message: off_bar_message(&fit.report),
3330 })
3331}
3332
3333pub fn affine_pcurve_on_range(
3355 surface: &NurbsSurface,
3356 curve: &NurbsCurve,
3357 edge_start: f64,
3358 edge_end: f64,
3359 forward: bool,
3360 tolerance: f64,
3361) -> Result<Option<PcurveFit>, String> {
3362 if std::env::var("BREP_AFFINE_RANGE_PCURVE").as_deref() == Ok("0") {
3368 return Ok(None);
3369 }
3370 let Some(inversion) = AffineInversion::of(surface)? else {
3371 return Ok(None);
3372 };
3373 if !(edge_start.is_finite() && edge_end.is_finite() && edge_start < edge_end) {
3374 return Ok(None);
3376 }
3377 let [t0, t1] = curve.domain()?;
3378 let start = edge_start.max(t0);
3379 let end = edge_end.min(t1);
3380 if end - start <= 2.0 * KNOT_IDENTITY_TOL {
3383 return Ok(None);
3384 }
3385 let mut restricted = curve.clone();
3386 if end < t1 - KNOT_IDENTITY_TOL {
3387 restricted = restricted.split(end)?.0;
3388 }
3389 if start > t0 + KNOT_IDENTITY_TOL {
3390 restricted = restricted.split(start)?.1;
3391 }
3392 let mut pcurve = inversion.image_of(&restricted)?;
3393 if !forward {
3394 pcurve = pcurve.reversed()?;
3395 }
3396 let first = pcurve.knots[0];
3397 let last = pcurve.knots[pcurve.knots.len() - 1];
3398 if !(last - first > 0.0) {
3399 return Ok(None);
3400 }
3401 let knots = pcurve
3402 .knots
3403 .iter()
3404 .map(|knot| (knot - first) / (last - first))
3405 .collect::<Vec<_>>();
3406 let pcurve = NurbsCurve::new(pcurve.degree, knots, pcurve.control_points.clone())?;
3407
3408 let scale = 1.0 + curve.evaluate((start + end) / 2.0)?.length();
3414 let bar = tolerance.max(1e-11 * scale);
3415 let mut residual = 0.0_f64;
3416 for index in 0..=32 {
3417 let fraction = index as f64 / 32.0;
3418 let uv = pcurve.evaluate(fraction)?;
3419 let on_carrier = surface.evaluate_extended(uv.x, uv.y)?;
3423 let edge_fraction = if forward { fraction } else { 1.0 - fraction };
3424 let on_edge = curve.evaluate(start + (end - start) * edge_fraction)?;
3425 residual = residual.max(on_carrier.sub(on_edge).length());
3426 if residual > bar {
3427 return Ok(None);
3428 }
3429 }
3430 let samples = pcurve.control_points.len();
3431 crate::work_counts::constructed("affine_range", 0, pcurve.control_points.len());
3432 Ok(Some(PcurveFit {
3433 curve: pcurve,
3434 report: PcurveFitReport {
3435 residual,
3436 floor: bar,
3441 samples,
3442 exit: PcurveFitExit::Converged,
3443 off_surface: 0.0,
3444 raised: false,
3445 clamped_excursion: 0.0,
3446 clamped_distance: 0.0,
3447 },
3448 }))
3449}
3450
3451pub fn align_collapsed_endpoints(surface: &NurbsSurface, raw: &mut [[f64; 2]]) -> Result<(), String> {
3452 let anchor = surface.control_points[0][0].point()?;
3453 let mut extent = 0.0_f64;
3454 for control in surface.control_points.iter().flatten() {
3455 extent = extent.max(control.point()?.sub(anchor).length());
3456 }
3457 let pole_band = (1e-10 * (1.0 + extent)).min(LINEAR_TOLERANCE);
3462 for (endpoint, neighbor) in [(0, 1), (raw.len() - 1, raw.len() - 2)] {
3463 let point = surface.evaluate(raw[endpoint][0], raw[endpoint][1])?;
3464 for axis in 0..2 {
3465 let mut candidate = raw[endpoint];
3466 candidate[axis] = raw[neighbor][axis];
3467 if candidate == raw[endpoint]
3468 || surface
3469 .evaluate(candidate[0], candidate[1])?
3470 .sub(point)
3471 .length()
3472 > pole_band
3473 {
3474 continue;
3475 }
3476 let row = if axis == 0 {
3477 surface.iso_curve_v(raw[endpoint][1])?
3478 } else {
3479 surface.iso_curve_u(raw[endpoint][0])?
3480 };
3481 let mut collapsed = true;
3482 for control in &row.control_points {
3483 if control.point()?.sub(point).length() > pole_band {
3484 collapsed = false;
3485 break;
3486 }
3487 }
3488 if collapsed {
3489 raw[endpoint] = candidate;
3490 }
3491 }
3492 }
3493 Ok(())
3494}
3495
3496fn repair_branch_jumps(
3519 surface: &NurbsSurface,
3520 edge_points: &[Vec3],
3521 raw: &mut [[f64; 2]],
3522 tolerance: f64,
3523) -> Result<(), String> {
3524 if raw.len() < 3 {
3525 return Ok(());
3526 }
3527 if surface.is_affine()? {
3530 return Ok(());
3531 }
3532 if std::env::var("BREP_NO_PCURVE_REPAIR").is_ok() {
3534 return Ok(());
3535 }
3536 align_collapsed_endpoints(surface, raw)?;
3540 let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
3541 let u_span = (u1 - u0).abs().max(EPSILON);
3542 let v_span = (v1 - v0).abs().max(EPSILON);
3543 let (closed_u, closed_v) = surface_closedness(surface)?;
3544 let norm_step = |a: [f64; 2], b: [f64; 2]| -> f64 {
3548 let mut du = a[0] - b[0];
3549 if closed_u {
3550 while du > 0.5 * u_span {
3551 du -= u_span;
3552 }
3553 while du < -0.5 * u_span {
3554 du += u_span;
3555 }
3556 }
3557 let mut dv = a[1] - b[1];
3558 if closed_v {
3559 while dv > 0.5 * v_span {
3560 dv -= v_span;
3561 }
3562 while dv < -0.5 * v_span {
3563 dv += v_span;
3564 }
3565 }
3566 ((du / u_span).powi(2) + (dv / v_span).powi(2)).sqrt()
3567 };
3568 const JUMP_THRESHOLD: f64 = 0.2;
3572 let count = raw.len();
3573
3574 let (mut best_start, mut best_len, mut run_start) = (0usize, 1usize, 0usize);
3578 for index in 1..count {
3579 if norm_step(raw[index], raw[index - 1]) > JUMP_THRESHOLD {
3580 if index - run_start > best_len {
3581 best_len = index - run_start;
3582 best_start = run_start;
3583 }
3584 run_start = index;
3585 }
3586 }
3587 if count - run_start > best_len {
3588 best_len = count - run_start;
3589 best_start = run_start;
3590 }
3591 let (spine_lo, spine_hi) = (best_start, best_start + best_len - 1);
3592
3593 let reseat = |edge_point: Vec3,
3599 previous: [f64; 2],
3600 global: [f64; 2]|
3601 -> Result<[f64; 2], String> {
3602 let global_step = norm_step(global, previous);
3603 if global_step <= JUMP_THRESHOLD {
3604 return Ok(global);
3605 }
3606 let seeded =
3607 project_point_to_surface_seeded(surface, edge_point, previous[0], previous[1])?;
3608 let candidate = [seeded.u, seeded.v];
3609 let global_residual = surface
3610 .evaluate(global[0], global[1])?
3611 .sub(edge_point)
3612 .length();
3613 let on_surface = seeded.distance <= 4.0 * global_residual + tolerance.max(1e-12);
3614 if on_surface && norm_step(candidate, previous) < 0.5 * global_step {
3615 if std::env::var("BREP_DEBUG_PCURVE").is_ok() {
3616 eprintln!(
3617 "pcurve repair: jump {global_step:.4} ({global:?}) -> {:.4} ({candidate:?}) res {:.2e}->{:.2e}",
3618 norm_step(candidate, previous),
3619 global_residual,
3620 seeded.distance
3621 );
3622 }
3623 Ok(candidate)
3624 } else {
3625 Ok(global)
3626 }
3627 };
3628
3629 let mut previous = raw[spine_hi];
3643 for index in (spine_hi + 1)..count.saturating_sub(1) {
3644 raw[index] = reseat(edge_points[index], previous, raw[index])?;
3645 previous = raw[index];
3646 }
3647 let mut previous = raw[spine_lo];
3648 for index in (1..spine_lo).rev() {
3649 raw[index] = reseat(edge_points[index], previous, raw[index])?;
3650 previous = raw[index];
3651 }
3652 Ok(())
3653}
3654
3655#[allow(clippy::too_many_arguments)]
3671pub fn fit_pcurve_on_surface_range_dense(
3672 surface: &NurbsSurface,
3673 curve: &NurbsCurve,
3674 edge_start: f64,
3675 edge_end: f64,
3676 forward: bool,
3677 tolerance: f64,
3678 base_samples: usize,
3679 refinement_rounds: usize,
3680 parameter_cap: usize,
3681) -> Result<PcurveFit, String> {
3682 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
3683 crate::work_counts::add(|c| c.fit_calls += 1);
3684 if !(edge_start.is_finite() && edge_end.is_finite() && edge_start < edge_end) {
3685 return Err("build_pcurve_on_surface_range: invalid edge interval".into());
3686 }
3687 let evaluate_edge = |fraction: f64| {
3688 let edge_fraction = if forward { fraction } else { 1.0 - fraction };
3689 curve.evaluate(edge_start + (edge_end - edge_start) * edge_fraction)
3690 };
3691 let breaks = range_breaks(curve, edge_start, edge_end, forward);
3692 let ask = tolerance.max(PCURVE_REFINEMENT_TOLERANCE);
3693 let fit = fit_station_pcurve(
3694 surface,
3695 &evaluate_edge,
3696 &breaks,
3697 &breaks,
3698 ask,
3699 base_samples,
3700 refinement_rounds,
3701 parameter_cap,
3702 SPAN_FLOOR,
3703 )?;
3704 end_span_challenger(surface, curve, &evaluate_edge, edge_start, edge_end, forward, &breaks, ask, base_samples, refinement_rounds, parameter_cap, fit)
3705}
3706
3707pub fn native_end_knot_fractions(curve: &NurbsCurve, edge_start: f64, edge_end: f64, forward: bool, pcurve: &NurbsCurve) -> Result<Vec<f64>, String> {
3712 let [q0, q1] = pcurve.domain()?;
3713 let mut interior: Vec<f64> = pcurve.knots.iter().copied().filter(|k| *k > q0 && *k < q1).collect();
3714 interior.dedup();
3715 let (Some(&first), Some(&last)) = (interior.first(), interior.last()) else { return Ok(Vec::new()) };
3716 let (low, high) = (edge_start.min(edge_end), edge_start.max(edge_end));
3717 let span = edge_end - edge_start;
3718 let mut fractions: Vec<f64> = curve
3719 .knots
3720 .iter()
3721 .copied()
3722 .filter(|k| *k > low && *k < high)
3723 .map(|k| {
3724 let along = (k - edge_start) / span;
3725 if forward { along } else { 1.0 - along }
3726 })
3727 .filter(|f| f.is_finite() && ((*f > q0 && *f < first) || (*f > last && *f < q1)))
3728 .collect();
3729 fractions.sort_by(f64::total_cmp);
3730 fractions.dedup();
3731 Ok(fractions)
3732}
3733
3734pub fn foot_admitted(foot: &crate::SurfaceProjection, [u0, u1]: [f64; 2], [v0, v1]: [f64; 2]) -> bool {
3738 let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
3739 foot.distance.is_finite() && finite(foot.point) && foot.u.is_finite() && foot.v.is_finite() && (u0..=u1).contains(&foot.u) && (v0..=v1).contains(&foot.v)
3740}
3741
3742pub fn verification_fractions(pcurve: &NurbsCurve, verify: &[f64]) -> Result<Vec<f64>, String> {
3748 let mut fractions = native_probe_fractions(&[pcurve])?;
3749 fractions.extend(pcurve.knots.iter().copied());
3750 fractions.extend(verify.iter().copied());
3751 fractions.retain(|f| f.is_finite() && (0.0..=1.0).contains(f));
3752 fractions.sort_by(f64::total_cmp);
3753 fractions.dedup();
3754 Ok(fractions)
3755}
3756
3757pub fn floor_admits(old: [f64; 3], new: [f64; 3]) -> bool {
3776 let floor = PCURVE_REFINEMENT_TOLERANCE;
3777 old.iter().chain(new.iter()).all(|v| v.is_finite())
3778 && new[0] < old[0]
3779 && (new[1] <= old[1] || (new[0] <= floor && new[2] <= floor))
3780}
3781
3782pub fn common_foot(
3790 global: Option<crate::SurfaceProjection>,
3791 reference: Option<crate::SurfaceProjection>,
3792 candidate: Option<crate::SurfaceProjection>,
3793 domain_u: [f64; 2],
3794 domain_v: [f64; 2],
3795) -> Option<crate::SurfaceProjection> {
3796 [global, reference, candidate]
3797 .into_iter()
3798 .flatten()
3799 .filter(|f| foot_admitted(f, domain_u, domain_v))
3800 .min_by(|a, b| a.distance.total_cmp(&b.distance))
3801}
3802
3803pub fn range_use_probes(curves: &[&NurbsCurve], edge_curve: &NurbsCurve, t0: f64, t1: f64, forward: bool) -> Result<Vec<f64>, String> {
3810 let mut probes = native_probe_fractions(curves)?;
3811 for curve in curves {
3812 probes.extend(curve.knots.iter().copied());
3813 }
3814 let span = t1 - t0;
3815 if span.is_finite() && span != 0.0 {
3816 let (low, high) = (t0.min(t1), t0.max(t1));
3817 let mut knots: Vec<f64> = edge_curve.knots.iter().copied().filter(|k| *k >= low && *k <= high).collect();
3818 knots.push(low);
3819 knots.push(high);
3820 knots.sort_by(f64::total_cmp);
3821 knots.dedup();
3822 let locals: Vec<f64> = [0.25, 0.5, 0.75]
3823 .into_iter()
3824 .chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64))
3825 .collect();
3826 let mut ts = knots.clone();
3827 for pair in knots.windows(2).filter(|w| w[1] > w[0]) {
3828 for &local in &locals {
3829 ts.push(pair[0] + (pair[1] - pair[0]) * local);
3830 }
3831 }
3832 for t in ts {
3833 let along = (t - t0) / span;
3834 probes.push(if forward { along } else { 1.0 - along });
3835 }
3836 }
3837 probes.retain(|f| f.is_finite() && (0.0..=1.0).contains(f));
3838 probes.sort_by(f64::total_cmp);
3839 probes.dedup();
3840 Ok(probes)
3841}
3842
3843#[cfg_attr(not(test), allow(dead_code))]
3851pub fn range_common_read(
3852 surface: &NurbsSurface,
3853 edge_curve: &NurbsCurve,
3854 t0: f64,
3855 t1: f64,
3856 forward: bool,
3857 old: &NurbsCurve,
3858 new: &NurbsCurve,
3859) -> Result<((f64, f64), (f64, f64)), String> {
3860 let (o, n) = range_common_read_with_excess(surface, edge_curve, t0, t1, forward, old, new)?;
3861 Ok(((o[0], o[1]), (n[0], n[1])))
3862}
3863
3864#[cfg_attr(not(test), allow(dead_code))]
3870pub fn range_common_read_with_excess(
3871 surface: &NurbsSurface,
3872 edge_curve: &NurbsCurve,
3873 t0: f64,
3874 t1: f64,
3875 forward: bool,
3876 old: &NurbsCurve,
3877 new: &NurbsCurve,
3878) -> Result<([f64; 3], [f64; 3]), String> {
3879 for curve in [old, new] {
3880 if !matches!(curve.domain(), Ok([a, b]) if a == 0.0 && b == 1.0) {
3881 return Err("range common read: a trim not on [0, 1]".into());
3882 }
3883 }
3884 let probes = range_use_probes(&[old, new], edge_curve, t0, t1, forward)?;
3885 let evaluate = |fraction: f64| -> Result<Vec3, String> {
3886 let along = if forward { fraction } else { 1.0 - fraction };
3887 edge_curve.evaluate(t0 + (t1 - t0) * along)
3888 };
3889 common_station_read_with_excess(surface, &evaluate, old, new, &probes)
3890}
3891
3892pub fn common_station_read(
3905 surface: &NurbsSurface,
3906 evaluate_edge: &dyn Fn(f64) -> Result<Vec3, String>,
3907 legacy: &NurbsCurve,
3908 candidate: &NurbsCurve,
3909 probes: &[f64],
3910) -> Result<((f64, f64), (f64, f64)), String> {
3911 let (old, new) = common_station_read_with_excess(surface, evaluate_edge, legacy, candidate, probes)?;
3912 Ok(((old[0], old[1]), (new[0], new[1])))
3913}
3914
3915fn tracking_closed_foot_enabled() -> bool {
3924 let enabled = crate::switch!("BREP_TRACKING_CLOSED_FOOT", true);
3925 enabled
3926}
3927
3928
3929pub fn common_station_read_with_excess(
3930 surface: &NurbsSurface,
3931 evaluate_edge: &dyn Fn(f64) -> Result<Vec3, String>,
3932 legacy: &NurbsCurve,
3933 candidate: &NurbsCurve,
3934 probes: &[f64],
3935) -> Result<([f64; 3], [f64; 3]), String> {
3936 let (domain_u, domain_v) = surface_domains(surface)?;
3937 let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
3938 let mut read = ([0.0_f64, 0.0, f64::NEG_INFINITY], [0.0_f64, 0.0, f64::NEG_INFINITY]);
3942 let same = std::ptr::eq(legacy, candidate);
3947 let ellipsoid = if same && surface.analytic().is_none() { surface.affine_sphere() } else { None };
3954 let analytic = if same && ellipsoid.is_none() && tracking_closed_foot_enabled() {
3970 surface.analytic().filter(|analytic| !matches!(analytic, crate::AnalyticSurface::Plane { .. }))
3971 } else {
3972 None
3973 };
3974 for &fraction in probes {
3975 let point = evaluate_edge(fraction)?;
3976 let old_uv = legacy.evaluate(fraction)?;
3977 let new_uv = if same { old_uv } else { candidate.evaluate(fraction)? };
3978 let old_image = surface.evaluate_extended(old_uv.x, old_uv.y)?;
3979 let new_image = if same { old_image } else { surface.evaluate_extended(new_uv.x, new_uv.y)? };
3980 if !(finite(point) && finite(old_image) && finite(new_image)) {
3981 return Err(format!("common station read: non-finite point at fraction {fraction}"));
3982 }
3983 let closed_form = ellipsoid.and_then(|ellipsoid| ellipsoid.project(surface, point)).or_else(|| {
3984 analytic
3985 .and_then(|analytic| analytic.project(surface, point))
3986 .filter(|foot| foot_admitted(foot, domain_u, domain_v))
3987 });
3988 let foot = if let Some(foot) = closed_form {
3989 common_foot(Some(foot), Some(foot), Some(foot), domain_u, domain_v)
3990 } else {
3991 let reference_foot = memo_seeded_foot(surface, point, old_uv.x, old_uv.y);
3992 let candidate_foot = if same {
3993 reference_foot
3994 } else {
3995 memo_seeded_foot(surface, point, new_uv.x, new_uv.y)
3996 };
3997 common_foot(
3998 memo_global_foot(surface, point),
3999 reference_foot,
4000 candidate_foot,
4001 domain_u,
4002 domain_v,
4003 )
4004 }
4005 .ok_or_else(|| format!("common station read: no admitted foot at fraction {fraction}"))?;
4006 let values = [
4007 old_image.sub(foot.point).length(),
4008 old_image.sub(point).length(),
4009 new_image.sub(foot.point).length(),
4010 new_image.sub(point).length(),
4011 ];
4012 if values.iter().any(|v| !v.is_finite()) {
4013 return Err(format!("common station read: non-finite distance at fraction {fraction}"));
4014 }
4015 if !foot.distance.is_finite() {
4016 return Err(format!("common station read: non-finite foot distance at fraction {fraction}"));
4017 }
4018 read.0[0] = read.0[0].max(values[0]);
4019 read.0[1] = read.0[1].max(values[1]);
4020 read.0[2] = read.0[2].max(values[1] - foot.distance);
4021 read.1[0] = read.1[0].max(values[2]);
4022 read.1[1] = read.1[1].max(values[3]);
4023 read.1[2] = read.1[2].max(values[3] - foot.distance);
4024 }
4025 Ok(read)
4026}
4027
4028pub fn edge_end_span_fractions(curve: &NurbsCurve, edge_start: f64, edge_end: f64, forward: bool) -> Vec<f64> {
4033 let (low, high) = (edge_start.min(edge_end), edge_start.max(edge_end));
4034 let mut knots: Vec<f64> = curve.knots.iter().copied().filter(|k| *k > low && *k < high).collect();
4035 knots.dedup();
4036 let spans = match (knots.first(), knots.last()) {
4037 (Some(&first), Some(&last)) => vec![(low, first), (last, high)],
4038 _ => vec![(low, high)],
4039 };
4040 let span = edge_end - edge_start;
4041 let mut out = Vec::new();
4042 for (a, b) in spans {
4043 if !(b > a) {
4044 continue;
4045 }
4046 for local in [0.25, 0.5, 0.75].into_iter().chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64)) {
4047 let along = (a + (b - a) * local - edge_start) / span;
4048 let fraction = if forward { along } else { 1.0 - along };
4049 if fraction.is_finite() && (0.0..=1.0).contains(&fraction) {
4050 out.push(fraction);
4051 }
4052 }
4053 }
4054 out.sort_by(f64::total_cmp);
4055 out.dedup();
4056 out
4057}
4058
4059const WORST_SPANS: usize = 4;
4061const WORST_SPAN_SEEDS: usize = 7;
4063
4064pub fn legacy_worst_span_seeds(
4073 evaluate_edge: &dyn Fn(f64) -> Result<Vec3, String>,
4074 surface: &NurbsSurface,
4075 pcurve: &NurbsCurve,
4076 bar: f64,
4077 extra_probes: &[f64],
4078) -> Result<Vec<f64>, String> {
4079 let [q0, q1] = pcurve.domain()?;
4080 let mut knots: Vec<f64> = pcurve.knots.iter().copied().filter(|k| *k >= q0 && *k <= q1).collect();
4081 knots.dedup();
4082 let locals: Vec<f64> = [0.25, 0.5, 0.75]
4083 .into_iter()
4084 .chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64))
4085 .collect();
4086 let mut over: Vec<(f64, f64, f64)> = Vec::new();
4087 for span in knots.windows(2).filter(|w| w[1] > w[0]) {
4088 let mut worst = 0.0_f64;
4089 let inside = extra_probes.iter().copied().filter(|f| *f > span[0] && *f < span[1]);
4090 for fraction in locals.iter().map(|local| span[0] + (span[1] - span[0]) * local).chain(inside) {
4091 let uv = pcurve.evaluate(fraction)?;
4092 let deviation = surface.evaluate_extended(uv.x, uv.y)?.sub(evaluate_edge(fraction)?).length();
4093 if !deviation.is_finite() {
4094 return Err(format!("worst-span read: non-finite deviation at fraction {fraction}"));
4095 }
4096 worst = worst.max(deviation);
4097 }
4098 if worst > bar {
4099 over.push((worst, span[0], span[1]));
4100 }
4101 }
4102 over.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.total_cmp(&b.1)));
4103 over.truncate(WORST_SPANS);
4104 Ok(over
4105 .into_iter()
4106 .flat_map(|(_, lo, hi)| (1..=WORST_SPAN_SEEDS).map(move |index| lo + (hi - lo) * index as f64 / (WORST_SPAN_SEEDS + 1) as f64))
4107 .collect())
4108}
4109
4110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4112pub enum ChallengerTrigger {
4113 Deviation,
4115 Tracking,
4119}
4120
4121pub fn challenger_trigger(residual: f64, off_surface: f64, ask: f64, tracking: impl FnOnce() -> Option<f64>) -> Option<ChallengerTrigger> {
4131 if residual > ask + off_surface {
4132 return Some(ChallengerTrigger::Deviation);
4133 }
4134 if !(off_surface > ask) {
4135 return None;
4136 }
4137 match tracking() {
4138 Some(value) if value.is_finite() && value > ask => Some(ChallengerTrigger::Tracking),
4139 _ => None,
4140 }
4141}
4142
4143#[allow(clippy::too_many_arguments)]
4162pub fn end_span_challenger(
4163 surface: &NurbsSurface,
4164 curve: &NurbsCurve,
4165 evaluate_edge: &dyn Fn(f64) -> Result<Vec3, String>,
4166 edge_start: f64,
4167 edge_end: f64,
4168 forward: bool,
4169 breaks: &[f64],
4170 ask: f64,
4171 base_samples: usize,
4172 refinement_rounds: usize,
4173 parameter_cap: usize,
4174 legacy: PcurveFit,
4175) -> Result<PcurveFit, String> {
4176 if !(legacy.report.residual > ask + legacy.report.off_surface) {
4184 return Ok(legacy);
4185 }
4186 let _feet = FootMemoScope::open(surface);
4189 let Ok(end_knots) = native_end_knot_fractions(curve, edge_start, edge_end, forward, &legacy.curve) else { return Ok(legacy) };
4190 let edge_end_probes = edge_end_span_fractions(curve, edge_start, edge_end, forward);
4204 let Ok(mut fixed) = native_probe_fractions(&[&legacy.curve]) else { return Ok(legacy) };
4211 fixed.extend(edge_end_probes.iter().copied());
4212 let (low, high) = (edge_start.min(edge_end), edge_start.max(edge_end));
4213 let mut edge_knots: Vec<f64> = curve.knots.iter().copied().filter(|k| *k >= low && *k <= high).collect();
4214 edge_knots.push(low);
4215 edge_knots.push(high);
4216 edge_knots.sort_by(f64::total_cmp);
4217 edge_knots.dedup();
4218 let to_fraction = |t: f64| {
4219 let along = (t - edge_start) / (edge_end - edge_start);
4220 if forward { along } else { 1.0 - along }
4221 };
4222 for span in edge_knots.windows(2).filter(|w| w[1] > w[0]) {
4223 for local in [0.25, 0.5, 0.75] {
4224 fixed.push(to_fraction(span[0] + (span[1] - span[0]) * local));
4225 }
4226 }
4227 fixed.extend(edge_knots.iter().map(|&t| to_fraction(t)));
4228 fixed.extend(end_knots.iter().copied());
4229 fixed.extend(legacy.curve.knots.iter().copied());
4230 fixed.retain(|f| f.is_finite() && (0.0..=1.0).contains(f));
4231 fixed.sort_by(f64::total_cmp);
4232 fixed.dedup();
4233 let trigger = challenger_trigger(legacy.report.residual, legacy.report.off_surface, ask, || {
4234 common_station_read(surface, evaluate_edge, &legacy.curve, &legacy.curve, &fixed).ok().map(|((tracking, _), _)| tracking)
4235 });
4236 let Some(trigger) = trigger else { return Ok(legacy) };
4237 let Ok(worst_seeds) = legacy_worst_span_seeds(evaluate_edge, surface, &legacy.curve, ask + legacy.report.off_surface, &edge_end_probes) else { return Ok(legacy) };
4238 if trigger == ChallengerTrigger::Deviation && end_knots.is_empty() && worst_seeds.is_empty() {
4242 return Ok(legacy);
4243 }
4244 let mut stations: Vec<f64> = breaks.iter().copied().chain(end_knots.iter().copied()).chain(worst_seeds.iter().copied()).collect();
4245 stations.sort_by(f64::total_cmp);
4246 stations.dedup();
4247 let initial = base_samples.max(1).checked_add(1).and_then(|count| count.checked_add(stations.len()));
4252 if initial.is_none_or(|count| count > parameter_cap) {
4253 return Ok(legacy);
4254 }
4255 let Ok(candidate) = fit_station_pcurve_mode(surface, evaluate_edge, &stations, breaks, ask, base_samples, refinement_rounds, parameter_cap, SPAN_FLOOR, true, Some(&legacy.curve), &fixed) else {
4256 return Ok(legacy);
4257 };
4258 if !(candidate.report.residual.is_finite() && candidate.report.off_surface.is_finite() && candidate.report.clamped_excursion.is_finite() && candidate.report.clamped_distance.is_finite()) {
4259 return Ok(legacy);
4260 }
4261 let Ok(mut probes) = native_probe_fractions(&[&candidate.curve]) else { return Ok(legacy) };
4265 probes.extend(fixed.iter().copied());
4266 probes.extend(candidate.curve.knots.iter().copied());
4267 probes.retain(|f| f.is_finite() && (0.0..=1.0).contains(f));
4268 probes.sort_by(f64::total_cmp);
4269 probes.dedup();
4270 let readings = common_station_read_with_excess(surface, evaluate_edge, &legacy.curve, &candidate.curve, &probes);
4271 let accepted = matches!(&readings, Ok((old, new)) if floor_admits(*old, *new));
4272 if station_fit_tracing() {
4273 eprintln!(
4274 "STATION-FIT end-span challenger: trigger={trigger:?} end_knots={} worst_span_seeds={} edge_end_probes={} legacy={:?}/{:e} candidate={:?}/{:e} common={readings:?} decision={}",
4275 end_knots.len(), worst_seeds.len(), edge_end_probes.len(), legacy.report.exit, legacy.report.residual, candidate.report.exit, candidate.report.residual,
4276 if accepted { "candidate" } else { "legacy" }
4277 );
4278 }
4279 Ok(if accepted { candidate } else { legacy })
4280}
4281
4282
4283#[allow(clippy::too_many_arguments)]
4286pub fn build_pcurve_on_surface_range_dense(
4287 surface: &NurbsSurface,
4288 curve: &NurbsCurve,
4289 edge_start: f64,
4290 edge_end: f64,
4291 forward: bool,
4292 tolerance: f64,
4293 base_samples: usize,
4294 refinement_rounds: usize,
4295 parameter_cap: usize,
4296) -> Result<NurbsCurve, String> {
4297 accept_fit(fit_pcurve_on_surface_range_dense(
4298 surface,
4299 curve,
4300 edge_start,
4301 edge_end,
4302 forward,
4303 tolerance,
4304 base_samples,
4305 refinement_rounds,
4306 parameter_cap,
4307 )?)
4308}
4309
4310pub fn range_breaks(
4320 curve: &NurbsCurve,
4321 edge_start: f64,
4322 edge_end: f64,
4323 forward: bool,
4324) -> Vec<f64> {
4325 let mut fractions = Vec::new();
4326 let span = edge_end - edge_start;
4327 if !(span.abs() > 0.0) {
4328 return fractions;
4329 }
4330 let (low, high) = (edge_start.min(edge_end), edge_start.max(edge_end));
4331 let mut index = 0;
4332 while index < curve.knots.len() {
4333 let value = curve.knots[index];
4334 let run = curve.knots[index..]
4335 .iter()
4336 .take_while(|knot| **knot == value)
4337 .count();
4338 if value > low && value < high && run >= curve.degree.max(1) {
4339 let along = (value - edge_start) / span;
4340 fractions.push(if forward { along } else { 1.0 - along });
4341 }
4342 index += run;
4343 }
4344 fractions.sort_by(f64::total_cmp);
4345 fractions
4346}
4347
4348#[allow(clippy::too_many_arguments)]
4399pub fn fit_pcurve_on_surface_stations(
4400 surface: &NurbsSurface,
4401 stations: &dyn Fn(f64) -> Result<Vec3, String>,
4402 breaks: &[f64],
4403 tolerance: f64,
4404 base_samples: usize,
4405 refinement_rounds: usize,
4406 parameter_cap: usize,
4407) -> Result<PcurveFit, String> {
4408 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
4409 crate::work_counts::add(|c| c.fit_calls += 1);
4410 let fit = fit_station_pcurve(
4411 surface, stations, breaks, &[], tolerance.max(PCURVE_REFINEMENT_TOLERANCE),
4412 base_samples, refinement_rounds, parameter_cap, SPAN_FLOOR,
4413 )?;
4414 record_fit(&fit.report);
4417 Ok(fit)
4418}
4419
4420pub fn analytic_station_pcurve(
4424 surface: &NurbsSurface,
4425 stations: &dyn Fn(f64) -> Result<Vec3, String>,
4426 tolerance: f64,
4427) -> Result<NurbsCurve, String> {
4428 if surface.analytic().is_none() {
4429 return Err("analytic pcurve requires an analytic carrier".into());
4430 }
4431 let mut breaks = Vec::new();
4432 for _ in 0..4 {
4433 let fit = fit_station_pcurve(surface, stations, &breaks, &[], tolerance, 64, 64, 8192, 1e-10)?;
4434 if fit.report.residual > tolerance || fit.report.off_surface > tolerance {
4435 return Err(format!(
4436 "analytic pcurve construction missed its contract: {:?}",
4437 fit.report
4438 ));
4439 }
4440 let mut failed = Vec::new();
4441 for pair in fit.curve.knots.windows(2) {
4444 if pair[1] <= pair[0] {
4445 continue;
4446 }
4447 for local in [
4448 0.06943184420297371,
4449 0.33000947820757187,
4450 0.6699905217924281,
4451 0.9305681557970262,
4452 ] {
4453 let t = pair[0] + (pair[1] - pair[0]) * local;
4454 let uv = fit.curve.evaluate(t)?;
4455 if surface
4456 .evaluate_extended(uv.x, uv.y)?
4457 .sub(stations(t)?)
4458 .length()
4459 > tolerance
4460 {
4461 failed.push(t);
4462 }
4463 }
4464 }
4465 if failed.is_empty() {
4466 return Ok(fit.curve);
4467 }
4468 if breaks.len() + failed.len() > 8192 {
4469 break;
4470 }
4471 breaks.extend(failed);
4472 breaks.sort_by(f64::total_cmp);
4473 breaks.dedup();
4474 }
4475 Err("analytic pcurve failed independent knot-span witnesses".into())
4476}
4477
4478#[allow(clippy::too_many_arguments)]
4479thread_local! {
4480 static STATION_LAPS: std::cell::Cell<[f64; 7]> = const { std::cell::Cell::new([0.0; 7]) };
4483}
4484
4485fn station_lap(slot: usize, lap: &mut Option<web_time::Instant>) {
4486 let Some(started) = *lap else { return };
4487 let now = web_time::Instant::now();
4488 STATION_LAPS.with(|laps| {
4489 let mut all = laps.get();
4490 all[slot] += (now - started).as_secs_f64() * 1e3;
4491 laps.set(all);
4492 });
4493 *lap = Some(now);
4494}
4495
4496#[doc(hidden)]
4498pub fn take_station_fit_laps() -> [f64; 7] {
4499 STATION_LAPS.with(|laps| laps.replace([0.0; 7]))
4500}
4501
4502#[allow(clippy::too_many_arguments)]
4503pub fn fit_station_pcurve(
4504 surface: &NurbsSurface,
4505 stations: &dyn Fn(f64) -> Result<Vec3, String>,
4506 breaks: &[f64],
4507 corners: &[f64],
4508 tolerance: f64,
4509 base_samples: usize,
4510 refinement_rounds: usize,
4511 parameter_cap: usize,
4512 span_floor: f64,
4513) -> Result<PcurveFit, String> {
4514 fit_station_pcurve_mode(surface, stations, breaks, corners, tolerance, base_samples, refinement_rounds, parameter_cap, span_floor, false, None, &[])
4515}
4516
4517#[allow(clippy::too_many_arguments)]
4536pub fn fit_station_pcurve_mode(
4537 surface: &NurbsSurface,
4538 stations: &dyn Fn(f64) -> Result<Vec3, String>,
4539 breaks: &[f64],
4540 corners: &[f64],
4541 tolerance: f64,
4542 base_samples: usize,
4543 refinement_rounds: usize,
4544 parameter_cap: usize,
4545 span_floor: f64,
4546 track_projection: bool,
4547 reference: Option<&NurbsCurve>,
4548 verify: &[f64],
4549) -> Result<PcurveFit, String> {
4550 let domains = if track_projection { Some(surface_domains(surface)?) } else { None };
4552 let tracking_of = |represented: Vec3, edge_point: Vec3, uv: Vec3, fraction: f64| -> Result<(f64, [f64; 2], f64), String> {
4559 let (domain_u, domain_v) = domains.ok_or_else(|| "station tracking: legacy mode".to_string())?;
4560 let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
4561 let reference_seed = match reference {
4562 Some(curve) => curve.evaluate(fraction).ok().and_then(|seed| memo_seeded_foot(surface, edge_point, seed.x, seed.y)),
4563 None => None,
4564 };
4565 let foot = common_foot(
4568 memo_global_foot(surface, edge_point),
4569 reference_seed,
4570 memo_seeded_foot(surface, edge_point, uv.x, uv.y),
4571 domain_u,
4572 domain_v,
4573 )
4574 .ok_or_else(|| "station tracking: no admitted foot".to_string())?;
4575 let tracking = represented.sub(foot.point).length();
4576 if !(finite(represented) && tracking.is_finite()) {
4577 return Err("station tracking: non-finite reading".into());
4578 }
4579 Ok((tracking, [foot.u, foot.v], foot.distance))
4580 };
4581 let mut tracking_unmet = false;
4583 let evaluate_edge = stations;
4584 let base_samples = base_samples.max(1);
4585 let mut parameters = (0..=base_samples)
4594 .map(|index| index as f64 / base_samples as f64)
4595 .collect::<Vec<_>>();
4596 let mut joins = Vec::with_capacity(corners.len());
4609 for &fraction in breaks {
4610 if !(fraction > 0.0 && fraction < 1.0) {
4611 continue;
4612 }
4613 let corner = corners.contains(&fraction);
4614 let at = parameters.partition_point(|parameter| *parameter < fraction);
4615 let near_left = at > 0 && fraction - parameters[at - 1] <= span_floor;
4616 let near_right = at < parameters.len() && parameters[at] - fraction <= span_floor;
4617 if near_left || near_right {
4618 if corner {
4622 joins.push(if near_right { parameters[at] } else { parameters[at - 1] });
4623 }
4624 continue;
4625 }
4626 parameters.insert(at, fraction);
4627 if corner {
4628 joins.push(fraction);
4629 }
4630 }
4631 let mut lap = crate::profile::profile_enabled().then(web_time::Instant::now);
4634 let mut edge_points = parameters
4635 .iter()
4636 .map(|fraction| evaluate_edge(*fraction))
4637 .collect::<Result<Vec<_>, _>>()?;
4638 let mut off_surface = 0.0_f64;
4641 let mut raw = Vec::with_capacity(edge_points.len());
4642 let mut gaps = Vec::with_capacity(edge_points.len());
4643 for point in &edge_points {
4644 let (parameter, gap) = if track_projection && precision_trim_feet(surface) {
4645 let foot = memo_global_foot(surface, *point).ok_or("precision trim has no foot")?;
4646 ([foot.u, foot.v], foot.distance)
4647 } else { invert_checked(surface, *point)? };
4648 off_surface = off_surface.max(gap);
4649 raw.push(parameter);
4650 gaps.push(gap);
4651 }
4652 repair_branch_jumps(surface, &edge_points, &mut raw, tolerance)?;
4653 let (mut pcurve, mut excursion, mut distance) =
4654 build_interpolant_joined(surface, &raw, ¶meters, &joins)?;
4655
4656 station_lap(0, &mut lap);
4657 let mut cap = parameter_cap.max(parameters.len());
4658 let mut rounds = refinement_rounds;
4659 let mut raised = false;
4660 loop {
4661 let mut exit = PcurveFitExit::RoundBudget;
4662 let mut converged_max = None;
4663 let mut tracking_met = false;
4666 for _ in 0..rounds {
4667 if parameters.len() >= cap {
4668 exit = PcurveFitExit::SampleCeiling;
4669 break;
4670 }
4671 let target = tolerance;
4679 let mut candidates = Vec::new();
4680 let mut round_max = 0.0_f64;
4681 let mut truncated = false;
4682 let mut skipped_narrow = false;
4683 let worst_first = worst_first();
4684 'spans: for index in 0..parameters.len() - 1 {
4685 if parameters[index + 1] - parameters[index] < span_floor {
4694 skipped_narrow = true;
4695 continue;
4696 }
4697 for local in [0.25, 0.5, 0.75] {
4698 if !worst_first && parameters.len() + candidates.len() >= cap {
4699 truncated = true;
4700 break 'spans;
4701 }
4702 let fraction =
4703 parameters[index] + (parameters[index + 1] - parameters[index]) * local;
4704 let uv = pcurve.evaluate(fraction)?;
4705 let represented = surface.evaluate_extended(uv.x, uv.y)?;
4706 let edge_point = evaluate_edge(fraction)?;
4707 let deviation = represented.sub(edge_point).length();
4708 let (reading, foot) = if track_projection {
4711 let (tracking, foot_uv, foot_gap) = tracking_of(represented, edge_point, uv, fraction)?;
4712 (tracking, Some((foot_uv, foot_gap)))
4713 } else {
4714 (deviation, None)
4715 };
4716 round_max = round_max.max(reading);
4717 if reading <= target {
4718 continue;
4719 }
4720 candidates.push((index, fraction, edge_point, uv, reading, foot));
4721 }
4722 }
4723 let mut verify_blocked = false;
4736 if track_projection && candidates.is_empty() && !truncated && !skipped_narrow {
4737 for fraction in verification_fractions(&pcurve, verify)? {
4738 let index = parameters.partition_point(|parameter| *parameter <= fraction).saturating_sub(1).min(parameters.len() - 2);
4739 let uv = pcurve.evaluate(fraction)?;
4740 let represented = surface.evaluate_extended(uv.x, uv.y)?;
4741 let edge_point = evaluate_edge(fraction)?;
4742 let (tracking, foot_uv, foot_gap) = tracking_of(represented, edge_point, uv, fraction)?;
4743 round_max = round_max.max(tracking);
4744 if tracking <= target {
4745 continue;
4746 }
4747 if fraction - parameters[index] <= span_floor || parameters[index + 1] - fraction <= span_floor {
4748 verify_blocked = true;
4749 continue;
4750 }
4751 if let Some(last) = candidates.last_mut() {
4754 if last.0 == index && fraction - last.1 <= span_floor {
4755 if tracking > last.4 {
4756 *last = (index, fraction, edge_point, uv, tracking, Some((foot_uv, foot_gap)));
4757 }
4758 continue;
4759 }
4760 }
4761 candidates.push((index, fraction, edge_point, uv, tracking, Some((foot_uv, foot_gap))));
4762 }
4763 }
4764 station_lap(if track_projection { 6 } else { 1 }, &mut lap);
4765 tracking_unmet = track_projection && round_max > target;
4766 let room = cap.saturating_sub(parameters.len());
4776 if candidates.len() > room {
4777 truncated = true;
4778 let mut order: Vec<usize> = (0..candidates.len()).collect();
4779 order.sort_by(|&a, &b| candidates[b].4.total_cmp(&candidates[a].4).then(a.cmp(&b)));
4780 order.truncate(room);
4781 order.sort_unstable();
4782 candidates = order.into_iter().map(|index| candidates[index]).collect();
4783 }
4784 let mut inserts = Vec::with_capacity(candidates.len());
4785 for (index, fraction, edge_point, uv, _, foot) in candidates {
4786 let (parameter, gap) = match foot {
4790 Some(placed) => placed,
4791 None => invert_near(surface, edge_point, [uv.x, uv.y], gaps[index].max(gaps[index + 1]))?,
4792 };
4793 inserts.push((index + 1, fraction, edge_point, parameter, gap));
4794 }
4795 station_lap(2, &mut lap);
4796 if station_fit_tracing() {
4797 eprintln!(
4798 "STATION-FIT round: samples={} target={target:.3e} round_max={round_max:.3e} inserts={} truncated={truncated}{}",
4799 parameters.len(),
4800 inserts.len(),
4801 if track_projection { " mode=tracking" } else { "" }
4803 );
4804 }
4805 if inserts.is_empty() {
4806 exit = if truncated {
4807 PcurveFitExit::SampleCeiling
4808 } else if skipped_narrow {
4809 PcurveFitExit::SpanFloor
4812 } else if track_projection {
4813 tracking_met = !verify_blocked;
4822 PcurveFitExit::Stalled
4823 } else {
4824 converged_max = Some(round_max);
4825 PcurveFitExit::Converged
4826 };
4827 break;
4828 }
4829 for (index, fraction, edge_point, parameter, gap) in inserts.into_iter().rev() {
4830 parameters.insert(index, fraction);
4831 edge_points.insert(index, edge_point);
4832 raw.insert(index, parameter);
4833 gaps.insert(index, gap);
4834 off_surface = off_surface.max(gap);
4835 }
4836 repair_branch_jumps(surface, &edge_points, &mut raw, tolerance)?;
4840 station_lap(3, &mut lap);
4841 let rebuilt = build_interpolant_joined(surface, &raw, ¶meters, &joins)?;
4842 station_lap(4, &mut lap);
4843 pcurve = rebuilt.0;
4844 excursion = rebuilt.1;
4845 distance = rebuilt.2;
4846 if truncated {
4847 exit = PcurveFitExit::SampleCeiling;
4848 break;
4849 }
4850 }
4851 station_lap(5, &mut lap);
4852 let residual = match converged_max {
4853 Some(measured) => measured,
4854 None => {
4855 station_residual(surface, evaluate_edge, &pcurve, ¶meters, tolerance, &mut off_surface)?
4856 }
4857 };
4858 station_lap(5, &mut lap);
4859 if station_fit_tracing() {
4860 eprintln!(
4861 "STATION-FIT pass raised={raised} exit={exit:?} samples={} residual={residual:.3e} off_surface={off_surface:.3e}",
4862 parameters.len()
4863 );
4864 if residual > tolerance + off_surface && (exit == PcurveFitExit::Converged || raised) {
4865 let (mut worst, mut at) = (0.0f64, 0usize);
4868 for (index, span) in parameters.windows(2).enumerate() {
4869 let fraction = 0.5 * (span[0] + span[1]);
4870 let uv = pcurve.evaluate(fraction)?;
4871 let deviation = surface.evaluate_extended(uv.x, uv.y)?.sub(evaluate_edge(fraction)?).length();
4872 if deviation > worst {
4873 worst = deviation;
4874 at = index;
4875 }
4876 }
4877 let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
4878 let (closed_u, closed_v) = surface_closedness(surface)?;
4879 eprintln!(
4880 "STATION-FIT OFF BAR: worst {worst:.3e} between stations {at} and {}; surface degree {}x{} net {}x{} domain u[{u0},{u1}] v[{v0},{v1}] closed ({closed_u},{closed_v}) analytic {:?}",
4881 at + 1,
4882 surface.degree_u,
4883 surface.degree_v,
4884 surface.control_points.len(),
4885 surface.control_points[0].len(),
4886 surface.analytic().map(|_| "yes").unwrap_or("no")
4887 );
4888 {
4889 let fraction = 0.5 * (parameters[at] + parameters[at + 1]);
4890 let uv = pcurve.evaluate(fraction)?;
4891 let image = surface.evaluate_extended(uv.x, uv.y)?;
4892 let station = evaluate_edge(fraction)?;
4893 let foot = project_point_to_surface(surface, station)?;
4894 let seeded = project_point_to_surface_seeded(surface, station, raw[at][0], raw[at][1])?;
4895 eprintln!(
4896 " at the worst midpoint: deviation {:.4e}, station gap {:.4e} (seeded {:.4e}), image-to-foot {:.4e} (to seeded foot {:.4e}), foot uv ({:.7}, {:.7}) seeded ({:.7}, {:.7}) image uv ({:.7}, {:.7})",
4897 image.sub(station).length(), foot.distance, seeded.distance, image.sub(foot.point).length(), image.sub(seeded.point).length(), foot.u, foot.v, seeded.u, seeded.v, uv.x, uv.y
4898 );
4899 }
4900 let lo = at.saturating_sub(3);
4901 let hi = (at + 4).min(parameters.len() - 1);
4902 for index in lo..=hi {
4903 eprintln!(
4904 " station {index}: fraction {:.6} uv ({:.6}, {:.6}) point ({:.4}, {:.4}, {:.4})",
4905 parameters[index], raw[index][0], raw[index][1], edge_points[index].x, edge_points[index].y, edge_points[index].z
4906 );
4907 }
4908 }
4909 }
4910 if !track_projection && exit == PcurveFitExit::SpanFloor && residual <= tolerance + off_surface {
4917 exit = PcurveFitExit::Converged;
4918 }
4919 if tracking_met && residual <= tolerance {
4920 exit = PcurveFitExit::Converged;
4921 }
4922 if exit != PcurveFitExit::Converged
4923 && !raised
4924 && (residual > tolerance + off_surface || tracking_unmet)
4925 && cap < PCURVE_RAISED_SAMPLES
4926 {
4927 raised = true;
4928 cap = PCURVE_RAISED_SAMPLES;
4929 rounds = RAISED_ROUNDS;
4936 continue;
4937 }
4938 crate::work_counts::constructed("station_fit", parameters.len(), pcurve.control_points.len());
4939 return Ok(PcurveFit {
4940 curve: pcurve,
4941 report: PcurveFitReport {
4942 residual,
4943 floor: tolerance,
4944 samples: parameters.len(),
4945 exit,
4946 off_surface,
4947 raised,
4948 clamped_excursion: excursion,
4949 clamped_distance: distance,
4950 },
4951 });
4952 }
4953}
4954
4955pub fn build_pcurve_on_surface_stations(
4958 surface: &NurbsSurface,
4959 stations: &dyn Fn(f64) -> Result<Vec3, String>,
4960 breaks: &[f64],
4961 tolerance: f64,
4962 base_samples: usize,
4963 refinement_rounds: usize,
4964 parameter_cap: usize,
4965) -> Result<NurbsCurve, String> {
4966 accept_fit(fit_pcurve_on_surface_stations(
4967 surface,
4968 stations,
4969 breaks,
4970 tolerance,
4971 base_samples,
4972 refinement_rounds,
4973 parameter_cap,
4974 )?)
4975}
4976
4977fn station_residual(
4985 surface: &NurbsSurface,
4986 stations: &dyn Fn(f64) -> Result<Vec3, String>,
4987 pcurve: &NurbsCurve,
4988 parameters: &[f64],
4989 tolerance: f64,
4990 off_surface: &mut f64,
4991) -> Result<f64, String> {
4992 let mut worst = 0.0_f64;
4993 let mut read = |fraction: f64| -> Result<(), String> {
4994 let uv = pcurve.evaluate(fraction)?;
4995 let represented = surface.evaluate_extended(uv.x, uv.y)?;
4996 let station = stations(fraction)?;
4997 let deviation = represented.sub(station).length();
4998 worst = worst.max(deviation);
4999 if deviation > tolerance + *off_surface {
5000 *off_surface = off_surface.max(invert_checked(surface, station)?.1);
5001 }
5002 Ok(())
5003 };
5004 for span in parameters.windows(2) {
5005 for local in [0.25, 0.5, 0.75] {
5006 read(span[0] + (span[1] - span[0]) * local)?;
5007 }
5008 }
5009 Ok(worst)
5010}
5011
5012
5013
5014