1use crate::curve::interior_knots;
2pub use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
3use serde::Serialize;
4
5const EPSILON: f64 = crate::tolerance::FP_FLOOR;
6const LINEAR_TOLERANCE: f64 = crate::tolerance::DEFAULT_MODEL;
7const MAX_NEWTON_ITERATIONS: usize = 50;
8
9#[derive(Clone, Copy, Debug, Serialize)]
10pub struct CurveProjection {
11 pub u: f64,
12 pub point: Vec3,
13 pub distance: f64,
14}
15
16#[derive(Clone, Copy, Debug, Serialize)]
17pub struct SurfaceProjection {
18 pub u: f64,
19 pub v: f64,
20 pub point: Vec3,
21 pub distance: f64,
22}
23
24pub fn fit_parameter(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
25 if closed {
26 let period = maximum - minimum;
27 (value - minimum).rem_euclid(period) + minimum
28 } else {
29 value.clamp(minimum, maximum)
30 }
31}
32
33fn witness_rescue_enabled() -> bool {
39 switch!("BREP_PROJECTION_WITNESS", true)
40}
41
42fn point_segment_distance_squared(point: Vec3, a: Vec3, b: Vec3) -> f64 {
48 point.distance_to_segment_squared(a, b)
49}
50
51#[allow(clippy::too_many_arguments)]
59fn curve_newton(
60 curve: &NurbsCurve,
61 point: Vec3,
62 seed: f64,
63 start: f64,
64 end: f64,
65 closed: bool,
66 best_u: &mut f64,
67 best_distance_squared: &mut f64,
68) -> Result<f64, String> {
69 let (last, nearest, squared) = curve_foot_newton_state(curve, point, seed, [start, end],
70 CurveFootPolicy {
71 domain: if closed { FootDomain::Wrap } else { FootDomain::Clamp },
72 iterations: MAX_NEWTON_ITERATIONS,
73 slope_guard: EPSILON,
74 step_limit: (end - start) / 4.0,
75 parameter_tolerance: 1e-15 * (end - start),
76 mode: FootMode::Witness,
77 })?;
78 if squared < *best_distance_squared {
79 *best_distance_squared = squared;
80 *best_u = nearest;
81 }
82 Ok(last)
83}
84
85fn bracketed_nearest(curve: &NurbsCurve, point: Vec3, low: f64, high: f64) -> Result<f64, String> {
93 const CONTRACTION: f64 = 0.618_033_988_749_894_9;
96 const CONTRACTIONS: usize = 64;
97 let width = high - low;
98 if !(width > 0.0) {
99 return Ok(low);
100 }
101 let (mut low, mut high) = (low, high);
102 let mut c = high - CONTRACTION * (high - low);
103 let mut d = low + CONTRACTION * (high - low);
104 let mut value_c = curve.evaluate(c)?.sub(point).length_squared();
105 let mut value_d = curve.evaluate(d)?.sub(point).length_squared();
106 for _ in 0..CONTRACTIONS {
107 if high - low <= 1e-15 * width {
108 break;
109 }
110 if value_c < value_d {
111 high = d;
112 d = c;
113 value_d = value_c;
114 c = high - CONTRACTION * (high - low);
115 value_c = curve.evaluate(c)?.sub(point).length_squared();
116 } else {
117 low = c;
118 c = d;
119 value_c = value_d;
120 d = low + CONTRACTION * (high - low);
121 value_d = curve.evaluate(d)?.sub(point).length_squared();
122 }
123 }
124 Ok((low + high) * 0.5)
125}
126
127pub fn project_point_to_curve(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
128 if projection_memo_enabled() {
129 if let Some(key) = straight_projection_key(curve, point) {
130 if let Some(hit) = PROJECTION_MEMO.with(|memo| memo.borrow().get(&key).copied()) {
131 return Ok(hit);
132 }
133 let projection = project_point_to_curve_uncached(curve, point)?;
134 PROJECTION_MEMO.with(|memo| {
135 let mut memo = memo.borrow_mut();
136 if memo.len() >= PROJECTION_MEMO_ENTRIES {
137 memo.clear();
138 }
139 memo.insert(key, projection);
140 });
141 return Ok(projection);
142 }
143 }
144 project_point_to_curve_uncached(curve, point)
145}
146
147const PROJECTION_MEMO_ENTRIES: usize = 4096;
156
157thread_local! {
158 static PROJECTION_MEMO: std::cell::RefCell<rustc_hash::FxHashMap<[u64; 16], CurveProjection>> = Default::default();
159}
160
161pub fn straight_projection_key(curve: &NurbsCurve, point: Vec3) -> Option<[u64; 16]> {
162 if curve.degree != 1 || curve.control_points.len() != 2 || curve.knots.len() != 4 {
163 return None;
164 }
165 let [a, b] = [curve.control_points[0], curve.control_points[1]];
166 let k = &curve.knots;
167 Some([
168 1, k[0].to_bits(), k[1].to_bits(), k[2].to_bits(), k[3].to_bits(),
169 a.x.to_bits(), a.y.to_bits(), a.z.to_bits(), a.w.to_bits(),
170 b.x.to_bits(), b.y.to_bits(), b.z.to_bits(), b.w.to_bits(),
171 point.x.to_bits(), point.y.to_bits(), point.z.to_bits(),
172 ])
173}
174
175fn projection_memo_enabled() -> bool {
176 switch!("BREP_PROJECTION_MEMO", true)
177}
178
179
180type CurveSeeds = std::rc::Rc<SeedSet>;
183
184#[derive(Clone)]
187pub(crate) struct SeedSet {
188 samples: Box<[(f64, Vec3)]>,
189 blocks: Box<[SeedBlock]>,
190}
191
192impl std::ops::Deref for SeedSet {
193 type Target = [(f64, Vec3)];
194 fn deref(&self) -> &Self::Target {
195 &self.samples
196 }
197}
198
199const SEED_BLOCK: usize = 16;
201
202#[derive(Clone, Copy)]
205struct SeedBlock {
206 low: Vec3,
207 high: Vec3,
208}
209
210impl SeedSet {
211 fn new(samples: Vec<(f64, Vec3)>) -> Self {
212 let mut blocks = Vec::with_capacity(samples.len().div_ceil(SEED_BLOCK));
213 let mut first = 0;
214 while first < samples.len() {
215 let last = (first + SEED_BLOCK).min(samples.len());
216 let from = first.saturating_sub(1);
217 let mut low = samples[from].1;
218 let mut high = low;
219 for &(_, q) in &samples[from..last] {
220 low = Vec3::new(low.x.min(q.x), low.y.min(q.y), low.z.min(q.z));
221 high = Vec3::new(high.x.max(q.x), high.y.max(q.y), high.z.max(q.z));
222 }
223 blocks.push(SeedBlock { low, high });
224 first = last;
225 }
226 Self { samples: samples.into_boxed_slice(), blocks: blocks.into_boxed_slice() }
227 }
228}
229
230fn seed_blocks_enabled() -> bool {
234 switch!("BREP_CURVE_SEED_BLOCKS", true)
235}
236
237fn seed_blocks_check() -> bool {
239 switch!("BREP_CURVE_SEED_BLOCKS_CHECK", false)
240}
241
242#[derive(Clone, Copy, Debug, PartialEq)]
245struct SeedScan {
246 best_u: f64,
247 best_distance_squared: f64,
248 witness_distance_squared: f64,
249 witness_low: f64,
250 witness_high: f64,
251}
252
253fn linear_seed_scan(samples: &[(f64, Vec3)], point: Vec3, start: f64) -> SeedScan {
255 let mut scan = SeedScan { best_u: start, best_distance_squared: f64::INFINITY, witness_distance_squared: f64::INFINITY, witness_low: start, witness_high: start };
256 let mut previous: Option<(f64, Vec3)> = None;
257 for &(parameter, sample) in samples {
258 let distance_squared = sample.sub(point).length_squared();
259 if distance_squared < scan.best_distance_squared {
260 scan.best_distance_squared = distance_squared;
261 scan.best_u = parameter;
262 }
263 if let Some((previous_parameter, previous_sample)) = previous {
264 let segment = point_segment_distance_squared(point, previous_sample, sample);
265 if segment < scan.witness_distance_squared {
266 scan.witness_distance_squared = segment;
267 scan.witness_low = previous_parameter;
268 scan.witness_high = parameter;
269 }
270 }
271 previous = Some((parameter, sample));
272 }
273 scan
274}
275
276fn blocked_seed_scan(set: &SeedSet, point: Vec3, start: f64) -> SeedScan {
288 let gap = |low: f64, high: f64, x: f64| if x < low { low - x } else if x > high { x - high } else { 0.0 };
289 thread_local! {
291 static ORDER: std::cell::Cell<Vec<(f64, usize)>> = const { std::cell::Cell::new(Vec::new()) };
292 }
293 let mut order = ORDER.with(|kept| kept.take());
294 order.clear();
295 order.extend(set.blocks.iter().enumerate().map(|(b, block)| {
296 let (dx, dy, dz) = (gap(block.low.x, block.high.x, point.x), gap(block.low.y, block.high.y, point.y), gap(block.low.z, block.high.z, point.z));
297 let cushion = 64.0 * f64::EPSILON * (point.length() + block.low.length() + block.high.length());
298 let reach = ((dx * dx + dy * dy + dz * dz).sqrt() * (1.0 - 1e-9) - cushion).max(0.0);
299 (reach * reach, b)
300 }));
301 order.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
302 let samples = &set.samples;
303 let (mut best, mut best_index) = (f64::INFINITY, usize::MAX);
304 let (mut witness, mut witness_index) = (f64::INFINITY, usize::MAX);
305 for &(bound, b) in &order {
306 if bound > best.max(witness) {
307 break;
308 }
309 let first = b * SEED_BLOCK;
310 let last = (first + SEED_BLOCK).min(samples.len());
311 for i in first..last {
312 let (_, sample) = samples[i];
313 let distance_squared = sample.sub(point).length_squared();
314 if distance_squared < best || (distance_squared == best && best_index != usize::MAX && i < best_index) {
315 best = distance_squared;
316 best_index = i;
317 }
318 if i > 0 {
319 let segment = point_segment_distance_squared(point, samples[i - 1].1, sample);
320 if segment < witness || (segment == witness && witness_index != usize::MAX && i < witness_index) {
321 witness = segment;
322 witness_index = i;
323 }
324 }
325 }
326 }
327 let mut scan = SeedScan { best_u: start, best_distance_squared: f64::INFINITY, witness_distance_squared: f64::INFINITY, witness_low: start, witness_high: start };
328 if best_index != usize::MAX {
329 scan.best_u = samples[best_index].0;
330 scan.best_distance_squared = best;
331 }
332 if witness_index != usize::MAX {
333 scan.witness_distance_squared = witness;
334 scan.witness_low = samples[witness_index - 1].0;
335 scan.witness_high = samples[witness_index].0;
336 }
337 ORDER.with(|kept| kept.set(order));
338 scan
339}
340const CURVE_SEED_BUDGET: usize = 262_144;
341thread_local! {
342 static CURVE_SEEDS: std::cell::RefCell<(rustc_hash::FxHashMap<[u64; 2], CurveSeeds>, usize)> = Default::default();
343}
344
345pub fn clear_curve_seed_cache() {
352 CURVE_SEEDS.with(|memo| *memo.borrow_mut() = Default::default());
353}
354
355fn visit_curve_seeds(curve: &NurbsCurve, start: f64, end: f64, mut visit: impl FnMut(f64, Vec3)) -> Result<(), String> {
356 let mut breaks = vec![start];
357 breaks.extend(interior_knots(&curve.knots, curve.degree));
358 breaks.push(end);
359 let samples_per_span = 4usize.max(curve.degree + 2);
360 for pair in breaks.windows(2) {
361 for index in 0..=samples_per_span {
362 let parameter = pair[0] + (pair[1] - pair[0]) * index as f64 / samples_per_span as f64;
363 visit(parameter, curve.evaluate(parameter)?);
364 }
365 }
366 Ok(())
367}
368
369fn cached_curve_seeds(curve: &NurbsCurve, start: f64, end: f64) -> Result<Option<CurveSeeds>, String> {
374 if !switch!("BREP_CURVE_PROJECTION_SEEDS", true) { return Ok(None); }
375 let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
377 if bound > CURVE_SEED_BUDGET { return Ok(None); }
378 let mut key = crate::identity_hash::TwoLane::new();
379 crate::identity_hash::hash_curve(&mut key, curve);
380 key.f64(start); key.f64(end);
381 let key = key.finish();
382 if let Some(seeds) = CURVE_SEEDS.with(|memo| memo.borrow().0.get(&key).cloned()) {
383 return Ok(Some(seeds));
384 }
385 let mut seeds = Vec::new();
386 visit_curve_seeds(curve, start, end, |u, point| seeds.push((u, point)))?;
387 let seeds: CurveSeeds = std::rc::Rc::new(SeedSet::new(seeds));
388 CURVE_SEEDS.with(|memo| {
389 let mut memo = memo.borrow_mut();
390 if memo.0.len() >= PROJECTION_MEMO_ENTRIES || memo.1 + seeds.len() > CURVE_SEED_BUDGET {
391 memo.0.clear(); memo.1 = 0;
392 }
393 memo.1 += seeds.len();
394 memo.0.insert(key, seeds.clone());
395 });
396 Ok(Some(seeds))
397}
398
399fn project_point_to_curve_uncached(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
400 let [start, end] = curve.domain()?;
401 let seeds = cached_curve_seeds(curve, start, end)?;
402 project_point_to_curve_seeded(curve, point, seeds.as_deref())
403}
404
405#[derive(Clone)]
409pub struct HeldCurve {
410 pub(crate) curve: NurbsCurve,
411 seeds: Option<SeedSet>,
412}
413
414impl std::fmt::Debug for HeldCurve {
415 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
416 f.debug_struct("HeldCurve").field("curve", &self.curve).field("seeds", &self.seeds.as_ref().map(|s| s.samples.len())).finish()
417 }
418}
419
420impl HeldCurve {
421 pub fn new(curve: NurbsCurve) -> Self {
422 let seeds = curve.domain().ok().and_then(|[start, end]| {
423 let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
424 if bound > CURVE_SEED_BUDGET { return None; }
425 let mut samples = Vec::new();
426 visit_curve_seeds(&curve, start, end, |u, point| samples.push((u, point))).ok()?;
427 Some(SeedSet::new(samples))
428 });
429 Self { curve, seeds }
430 }
431
432 pub(crate) fn bare(curve: NurbsCurve) -> Self {
434 Self { curve, seeds: None }
435 }
436
437 pub fn project(&self, point: Vec3) -> Result<CurveProjection, String> {
440 match &self.seeds {
441 Some(seeds) if !(projection_memo_enabled() && straight_projection_key(&self.curve, point).is_some()) => {
442 project_point_to_curve_seeded(&self.curve, point, Some(seeds))
443 }
444 _ => project_point_to_curve(&self.curve, point),
445 }
446 }
447}
448
449fn project_point_to_curve_seeded(curve: &NurbsCurve, point: Vec3, seeds: Option<&SeedSet>) -> Result<CurveProjection, String> {
450 let [start, end] = curve.domain()?;
451 let mut best_u = start;
452 let mut best_distance_squared = f64::INFINITY;
453 let mut start_point = None;
458 let mut end_point = None;
459 let mut previous: Option<(f64, Vec3)> = None;
462 let mut witness_distance_squared = f64::INFINITY;
463 let mut witness_low = start;
464 let mut witness_high = start;
465 let mut visit = |parameter, sample: Vec3| {
466 if start_point.is_none() {
467 start_point = Some(sample);
468 }
469 end_point = Some(sample);
470 let distance_squared = sample.sub(point).length_squared();
471 if distance_squared < best_distance_squared {
472 best_distance_squared = distance_squared;
473 best_u = parameter;
474 }
475 if let Some((previous_parameter, previous_sample)) = previous {
476 let segment = point_segment_distance_squared(point, previous_sample, sample);
477 if segment < witness_distance_squared {
478 witness_distance_squared = segment;
479 witness_low = previous_parameter;
480 witness_high = parameter;
481 }
482 }
483 previous = Some((parameter, sample));
484 };
485 match seeds.filter(|set| !set.samples.is_empty() && (seed_blocks_enabled() || seed_blocks_check())) {
486 Some(set) => {
487 let scan = if seed_blocks_check() {
488 let linear = linear_seed_scan(&set.samples, point, start);
489 let blocked = blocked_seed_scan(set, point, start);
490 let bits = |s: &SeedScan| [s.best_u, s.best_distance_squared, s.witness_distance_squared, s.witness_low, s.witness_high].map(f64::to_bits);
491 if bits(&linear) != bits(&blocked) {
492 panic!("curve seed blocks check: blocked scan {blocked:?} differs from the linear scan {linear:?} at {point:?}");
493 }
494 linear
495 } else {
496 blocked_seed_scan(set, point, start)
497 };
498 best_u = scan.best_u;
499 best_distance_squared = scan.best_distance_squared;
500 witness_distance_squared = scan.witness_distance_squared;
501 witness_low = scan.witness_low;
502 witness_high = scan.witness_high;
503 start_point = Some(set.samples[0].1);
504 end_point = Some(set.samples[set.samples.len() - 1].1);
505 }
506 None => match seeds {
507 Some(seeds) => {
508 for &(parameter, sample) in seeds.iter() { visit(parameter, sample); }
509 }
510 None => visit_curve_seeds(curve, start, end, visit)?,
511 },
512 }
513 const CLOSED_SEAM_TOLERANCE: f64 = 1e-6;
526 let closed = match (start_point, end_point) {
527 (Some(first), Some(last)) => first.sub(last).length() <= CLOSED_SEAM_TOLERANCE,
528 _ => false,
529 };
530
531 let parameter = curve_newton(
532 curve,
533 point,
534 best_u,
535 start,
536 end,
537 closed,
538 &mut best_u,
539 &mut best_distance_squared,
540 )?;
541 for candidate in [start, end, parameter] {
542 let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
543 if distance_squared < best_distance_squared {
544 best_distance_squared = distance_squared;
545 best_u = candidate;
546 }
547 }
548 const WITNESS_FACTOR: f64 = 2.0;
580 if witness_distance_squared * (WITNESS_FACTOR * WITNESS_FACTOR) < best_distance_squared
581 && witness_rescue_enabled()
582 {
583 let bracketed = bracketed_nearest(curve, point, witness_low, witness_high)?;
584 let polished = curve_newton(
585 curve,
586 point,
587 bracketed,
588 start,
589 end,
590 closed,
591 &mut best_u,
592 &mut best_distance_squared,
593 )?;
594 for candidate in [bracketed, polished] {
595 let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
596 if distance_squared < best_distance_squared {
597 best_distance_squared = distance_squared;
598 best_u = candidate;
599 }
600 }
601 }
602 let projected = curve.evaluate(best_u)?;
603 Ok(CurveProjection {
604 u: best_u,
605 point: projected,
606 distance: projected.sub(point).length(),
607 })
608}
609
610fn project_linear_revolution(
611 surface: &NurbsSurface,
612 point: Vec3,
613) -> Result<Option<SurfaceProjection>, String> {
614 let rows = &surface.control_points;
615 if surface.degree_u != 2
616 || surface.degree_v != 1
617 || rows.len() < 5
618 || rows[0].len() != 2
619 || !surface.closed_directions()?.0
620 {
621 return Ok(None);
622 }
623 let base = rows[0][0].point()?.add(rows[4][0].point()?).scale(0.5);
624 let top = rows[0][1].point()?.add(rows[4][1].point()?).scale(0.5);
625 let axis_vector = top.sub(base);
626 let height = axis_vector.length();
627 if height <= EPSILON {
628 return Ok(None);
629 }
630 let axis = axis_vector.normalized()?;
631 let [v0, v1] = surface.domain_v()?;
632 let axial = point.sub(base).dot(axis).clamp(0.0, height);
633 let v = v0 + (v1 - v0) * axial / height;
634 let circle = surface.iso_curve_v(v)?;
635 let projection = project_point_to_curve(&circle, point)?;
636 let [u0, u1] = surface.domain_u()?;
637 let u = projection.u.clamp(u0, u1);
638 let projected = surface.evaluate(u, v)?;
639 Ok(Some(SurfaceProjection {
640 u,
641 v,
642 point: projected,
643 distance: projected.sub(point).length(),
644 }))
645}
646
647#[derive(Clone, Copy)]
648struct NewtonResult {
649 u: f64,
650 v: f64,
651 distance_squared: f64,
652 converged: bool,
653}
654
655fn surface_newton(
656 surface: &NurbsSurface,
657 point: Vec3,
658 seed_u: f64,
659 seed_v: f64,
660 domains: [f64; 4],
661 closed_u: bool,
662 closed_v: bool,
663) -> Result<NewtonResult, String> {
664 surface_newton_impl(surface, point, seed_u, seed_v, domains, closed_u, closed_v,
665 switch!("BREP_PROJECTION_LAZY_DERIVATIVES", false), LINEAR_TOLERANCE)
666}
667
668fn surface_newton_impl(
673 surface: &NurbsSurface,
674 point: Vec3,
675 seed_u: f64,
676 seed_v: f64,
677 domains: [f64; 4],
678 closed_u: bool,
679 closed_v: bool,
680 lazy: bool,
681 linear_tolerance: f64,
682) -> Result<NewtonResult, String> {
683 let [u0, u1, v0, v1] = domains;
684 let mut u = seed_u;
685 let mut v = seed_v;
686 let mut converged = false;
687 let mut best = NewtonResult {
688 u,
689 v,
690 distance_squared: surface.evaluate(u, v)?.sub(point).length_squared(),
691 converged,
692 };
693 let cycle_exit = switch!("BREP_PROJECTION_NEWTON_CYCLE_EXIT", true);
705 let mut trail = [(0u64, 0u64); MAX_NEWTON_ITERATIONS];
706 for iteration in 0..MAX_NEWTON_ITERATIONS {
707 if cycle_exit {
708 let state = (u.to_bits(), v.to_bits());
709 if let Some(first) = trail[..iteration].iter().position(|earlier| *earlier == state) {
710 let period = iteration - first;
711 let (last_u, last_v) = trail[first + (MAX_NEWTON_ITERATIONS - first) % period];
712 u = f64::from_bits(last_u);
713 v = f64::from_bits(last_v);
714 crate::work_counts::add(|c| c.newton_iterations += (MAX_NEWTON_ITERATIONS - iteration) as u64);
715 break;
716 }
717 trail[iteration] = state;
718 }
719 crate::work_counts::add(|c| c.newton_iterations += 1);
720 let derivatives = surface.derivatives_small(u, v, if lazy { 0 } else { 2 })?;
721 let residual = derivatives[0][0].sub(point);
722 let distance_squared = residual.length_squared();
723 if distance_squared < best.distance_squared {
724 best.u = u;
725 best.v = v;
726 best.distance_squared = distance_squared;
727 }
728 let residual_length = distance_squared.sqrt();
729 if residual_length <= linear_tolerance {
730 crate::work_counts::add(|c| { c.newton_unused += 1; c.newton_unused_first += u64::from(iteration == 0); });
731 converged = true;
732 break;
733 }
734 let derivatives = if lazy { surface.derivatives_small(u, v, 2)? } else { derivatives };
735 let f = derivatives[1][0].dot(residual);
736 let g = derivatives[0][1].dot(residual);
737 let tangent_u_length = derivatives[1][0].length();
738 let tangent_v_length = derivatives[0][1].length();
739 let cosine_u = if tangent_u_length * residual_length <= EPSILON {
740 0.0
741 } else {
742 f.abs() / (tangent_u_length * residual_length)
743 };
744 let cosine_v = if tangent_v_length * residual_length <= EPSILON {
745 0.0
746 } else {
747 g.abs() / (tangent_v_length * residual_length)
748 };
749 if cosine_u <= 1e-10 && cosine_v <= 1e-10 {
750 converged = true;
751 break;
752 }
753 let j00 = derivatives[2][0].dot(residual) + derivatives[1][0].length_squared();
754 let j01 = derivatives[1][1].dot(residual) + derivatives[1][0].dot(derivatives[0][1]);
755 let j11 = derivatives[0][2].dot(residual) + derivatives[0][1].length_squared();
756 let determinant = j00 * j11 - j01 * j01;
757 if determinant.abs() <= EPSILON {
758 break;
759 }
760 let mut du = (-f * j11 + g * j01) / determinant;
761 let mut dv = (-g * j00 + f * j01) / determinant;
762 du = du.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
763 dv = dv.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
764 let next_u = fit_parameter(u + du, u0, u1, closed_u);
765 let next_v = fit_parameter(v + dv, v0, v1, closed_v);
766 let stalled =
767 (next_u - u).abs() <= 1e-15 * (u1 - u0) && (next_v - v).abs() <= 1e-15 * (v1 - v0);
768 u = next_u;
769 v = next_v;
770 if stalled {
771 break;
772 }
773 }
774 let final_distance_squared = surface.evaluate(u, v)?.sub(point).length_squared();
775 if final_distance_squared < best.distance_squared {
776 best.u = u;
777 best.v = v;
778 best.distance_squared = final_distance_squared;
779 }
780 best.converged = converged;
781 Ok(best)
782}
783
784pub fn refine_trim_foot(
788 surface: &NurbsSurface, point: Vec3, foot: SurfaceProjection,
789) -> Result<SurfaceProjection, String> {
790 let [u0, u1] = surface.domain_u()?;
791 let [v0, v1] = surface.domain_v()?;
792 let (cu, cv) = surface.closed_directions()?;
793 let result = surface_newton_impl(surface, point, foot.u, foot.v,
794 [u0, u1, v0, v1], cu, cv, false, 1e-11)?;
795 let projected = surface.evaluate(result.u, result.v)?;
796 Ok(SurfaceProjection { u: result.u, v: result.v, point: projected,
797 distance: projected.sub(point).length() })
798}
799
800#[track_caller]
806pub fn project_point_to_surface(
807 surface: &NurbsSurface,
808 point: Vec3,
809) -> Result<SurfaceProjection, String> {
810 crate::work_counts::add(|c| c.projection_global += 1);
811 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_PROJECT, surface);
812 if let Some(analytic) = surface.analytic() {
816 if let Some(projection) = analytic.project(surface, point) {
817 return Ok(projection);
818 }
819 }
820 if let Some(ellipsoid) = surface.affine_sphere() {
821 if let Some(projection) = ellipsoid.project(surface, point) {
822 return Ok(projection);
823 }
824 }
825 if switch!("BREP_EXTRUSION_PROJECTION", true) {
826 if let Some(projection) = surface.linear_extrusion().and_then(|e| e.project(surface,point)) {
827 return Ok(projection);
828 }
829 }
830 project_point_to_surface_general(surface, point)
831}
832
833pub fn project_point_to_surface_local(
840 surface: &NurbsSurface,
841 point: Vec3,
842) -> Result<SurfaceProjection, String> {
843 if let Some(analytic) = surface.analytic() {
844 if let Some(projection) = analytic.project(surface, point) {
845 return Ok(projection);
846 }
847 }
848 if let Some(ellipsoid) = surface.affine_sphere() {
849 if let Some(projection) = ellipsoid.project(surface, point) {
850 return Ok(projection);
851 }
852 }
853 if switch!("BREP_EXTRUSION_PROJECTION", true) {
854 if let Some(projection) = surface.linear_extrusion().and_then(|e| e.project(surface, point)) {
855 return Ok(projection);
856 }
857 }
858 project_point_to_surface_from_nearest_seed(surface, point)
859}
860
861pub fn project_point_to_surface_seeded(
871 surface: &NurbsSurface,
872 point: Vec3,
873 seed_u: f64,
874 seed_v: f64,
875) -> Result<SurfaceProjection, String> {
876 crate::work_counts::add(|c| c.projection_seeded += 1);
877 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
878 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_SEEDED, surface);
879 if let Some(ellipsoid) = surface.affine_sphere() {
883 if let Some(projection) = ellipsoid.project(surface, point) {
884 return Ok(projection);
885 }
886 }
887 let [u0, u1] = surface.domain_u()?;
888 let [v0, v1] = surface.domain_v()?;
889 let (closed_u, closed_v) = surface.closed_directions()?;
890 let result = surface_newton(
891 surface,
892 point,
893 seed_u,
894 seed_v,
895 [u0, u1, v0, v1],
896 closed_u,
897 closed_v,
898 )?;
899 let projected = surface.evaluate(result.u, result.v)?;
900 Ok(SurfaceProjection {
901 u: result.u,
902 v: result.v,
903 point: projected,
904 distance: projected.sub(point).length(),
905 })
906}
907
908#[track_caller]
942pub fn project_point_to_surface_from_seed(
943 surface: &NurbsSurface,
944 point: Vec3,
945 seed: [f64; 2],
946) -> Result<SurfaceProjection, String> {
947 crate::work_counts::add(|c| c.projection_from_seed += 1);
948 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
949 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_SEED, surface);
950 if let Some(analytic) = surface.analytic() {
951 if let Some(projection) = analytic.project(surface, point) {
952 return Ok(projection);
953 }
954 }
955 if let Some(ellipsoid) = surface.affine_sphere() {
956 if let Some(projection) = ellipsoid.project(surface, point) {
957 return Ok(projection);
958 }
959 }
960 let caller = std::panic::Location::caller();
961 if !seeded_answer_admitted(caller) {
962 return project_point_to_surface_general(surface, point);
963 }
964 let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
965 if seed_audit_enabled() {
966 let nearest = project_point_to_surface_general(surface, point)?;
967 if seeded.point.sub(nearest.point).length() > LINEAR_TOLERANCE {
968 seed_audit_record(caller, surface, seed, &seeded, &nearest);
969 }
970 }
971 Ok(seeded)
972}
973
974fn seeded_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
977 static SITES: std::sync::OnceLock<Option<Option<Vec<String>>>> = std::sync::OnceLock::new();
978 let sites = SITES.get_or_init(|| {
979 if std::env::var("BREP_PROJECTION_FROM_SEED").as_deref() == Ok("0") {
980 return None;
981 }
982 Some(std::env::var("BREP_PROJECTION_FROM_SEED_SITES").ok().map(|value| {
983 value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect()
984 }))
985 });
986 match sites {
987 None => false,
988 Some(None) => true,
989 Some(Some(only)) => {
990 let location = format!("{}:{}", caller.file(), caller.line());
991 only.iter().any(|site| location.contains(site.as_str()))
992 }
993 }
994}
995
996fn seed_audit_enabled() -> bool {
997 debug_flag!("BREP_PROJECTION_AUDIT")
998}
999
1000fn seed_audit_record(
1004 caller: &std::panic::Location<'_>,
1005 surface: &NurbsSurface,
1006 seed: [f64; 2],
1007 seeded: &SurfaceProjection,
1008 nearest: &SurfaceProjection,
1009) {
1010 use std::io::Write;
1011 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1012 std::sync::OnceLock::new();
1013 let sink = SINK.get_or_init(|| {
1014 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1015 let path = std::path::Path::new(&directory)
1016 .join(format!("projection-seed-audit-{}.tsv", std::process::id()));
1017 std::fs::OpenOptions::new()
1018 .create(true)
1019 .append(true)
1020 .open(path)
1021 .ok()
1022 .map(std::sync::Mutex::new)
1023 });
1024 if let Some(file) = sink {
1025 if let Ok(mut file) = file.lock() {
1026 let _ = writeln!(
1027 file,
1028 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.6e}\t{}x{} cp {}x{}",
1029 caller.file(),
1030 caller.line(),
1031 seeded.distance,
1032 nearest.distance,
1033 seed[0],
1034 seed[1],
1035 seeded.u,
1036 seeded.v,
1037 nearest.u,
1038 nearest.v,
1039 seeded.point.sub(nearest.point).length(),
1040 surface.degree_u,
1041 surface.degree_v,
1042 surface.control_points.len(),
1043 surface.control_points.first().map(Vec::len).unwrap_or(0),
1044 );
1045 }
1046 }
1047}
1048
1049fn projection_seed_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
1054 if let Some(grid) = surface.projection_grid.get() {
1055 return Ok(grid);
1056 }
1057 tables_within_limit(surface)?;
1058 let [u0, u1] = surface.domain_u()?;
1059 let [v0, v1] = surface.domain_v()?;
1060 let (closed_u, closed_v) = surface.closed_directions()?;
1061 let mut breaks_u = vec![u0];
1062 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
1063 breaks_u.push(u1);
1064 let mut breaks_v = vec![v0];
1065 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
1066 breaks_v.push(v1);
1067 let samples_u = if closed_u {
1068 8usize.max(surface.degree_u * 4)
1069 } else {
1070 3usize.max(surface.degree_u + 1)
1071 };
1072 let samples_v = if closed_v {
1073 8usize.max(surface.degree_v * 4)
1074 } else {
1075 3usize.max(surface.degree_v + 1)
1076 };
1077 let mut grid = Vec::with_capacity((breaks_u.len() - 1) * (breaks_v.len() - 1) * (samples_u + 1) * (samples_v + 1));
1078 for u_pair in breaks_u.windows(2) {
1079 for v_pair in breaks_v.windows(2) {
1080 for i in 0..=samples_u {
1081 for j in 0..=samples_v {
1082 let u = u_pair[0] + (u_pair[1] - u_pair[0]) * i as f64 / samples_u as f64;
1083 let v = v_pair[0] + (v_pair[1] - v_pair[0]) * j as f64 / samples_v as f64;
1084 grid.push((u, v, surface.evaluate(u, v)?));
1085 }
1086 }
1087 }
1088 }
1089 Ok(surface.projection_grid.get_or_init(|| SampleGrid::new(grid)))
1090}
1091
1092fn projection_dense_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
1099 if let Some(grid) = surface.projection_dense_grid.get() {
1100 return Ok(grid);
1101 }
1102 tables_within_limit(surface)?;
1103 let [u0, u1] = surface.domain_u()?;
1104 let [v0, v1] = surface.domain_v()?;
1105 let mut breaks_u = vec![u0];
1106 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
1107 breaks_u.push(u1);
1108 let mut breaks_v = vec![v0];
1109 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
1110 breaks_v.push(v1);
1111 let count_u = 32usize.max((breaks_u.len() - 1) * 8);
1112 let count_v = 16usize.max((breaks_v.len() - 1) * 8);
1113 let mut grid = Vec::with_capacity((count_u + 1) * (count_v + 1));
1114 for i in 0..=count_u {
1115 for j in 0..=count_v {
1116 let u = u0 + (u1 - u0) * i as f64 / count_u as f64;
1117 let v = v0 + (v1 - v0) * j as f64 / count_v as f64;
1118 grid.push((u, v, surface.evaluate(u, v)?));
1119 }
1120 }
1121 Ok(surface.projection_dense_grid.get_or_init(|| SampleGrid::with_tree(grid)))
1122}
1123
1124const SAMPLE_BLOCK: usize = 32;
1126
1127const GROUP_BLOCKS: usize = 32;
1130
1131#[derive(Clone, Debug)]
1136pub struct SampleGrid {
1137 samples: Vec<(f64, f64, Vec3)>,
1138 blocks: Vec<SampleBlock>,
1139 groups: Vec<SampleBlock>,
1144 tree: Vec<Vec<SampleBlock>>,
1150}
1151
1152const TREE_FANOUT: usize = 4;
1154
1155fn union_boxes(boxes: &[SampleBlock]) -> Vec<SampleBlock> {
1157 boxes
1158 .chunks(TREE_FANOUT)
1159 .map(|chunk| {
1160 let mut union = chunk[0];
1161 for block in chunk {
1162 union.low = Vec3::new(union.low.x.min(block.low.x), union.low.y.min(block.low.y), union.low.z.min(block.low.z));
1163 union.high = Vec3::new(union.high.x.max(block.high.x), union.high.y.max(block.high.y), union.high.z.max(block.high.z));
1164 union.prunable &= block.prunable;
1165 }
1166 union
1167 })
1168 .collect()
1169}
1170
1171#[derive(Clone, Copy, Debug)]
1174struct SampleBlock {
1175 low: Vec3,
1176 high: Vec3,
1177 prunable: bool,
1178}
1179
1180impl SampleGrid {
1181 fn new(samples: Vec<(f64, f64, Vec3)>) -> Self {
1182 let blocks = samples
1183 .chunks(SAMPLE_BLOCK)
1184 .map(|chunk| {
1185 let mut low = chunk[0].2;
1186 let mut high = low;
1187 let mut prunable = true;
1188 for &(_, _, p) in chunk {
1189 prunable &= p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
1190 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
1191 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
1192 }
1193 SampleBlock { low, high, prunable }
1194 })
1195 .collect::<Vec<_>>();
1196 let groups = blocks
1197 .chunks(GROUP_BLOCKS)
1198 .map(|chunk| {
1199 let mut group = chunk[0];
1200 for block in chunk {
1201 group.low = Vec3::new(group.low.x.min(block.low.x), group.low.y.min(block.low.y), group.low.z.min(block.low.z));
1202 group.high = Vec3::new(group.high.x.max(block.high.x), group.high.y.max(block.high.y), group.high.z.max(block.high.z));
1203 group.prunable &= block.prunable;
1204 }
1205 group
1206 })
1207 .collect();
1208 Self { samples, blocks, groups, tree: Vec::new() }
1209 }
1210
1211 fn with_tree(samples: Vec<(f64, f64, Vec3)>) -> Self {
1218 let mut grid = Self::new(samples);
1219 if grid.blocks.len() > GROUP_BLOCKS {
1220 grid.tree.push(union_boxes(&grid.blocks));
1221 while grid.tree.last().is_some_and(|level| level.len() > 1) {
1222 let next = union_boxes(grid.tree.last().unwrap());
1223 grid.tree.push(next);
1224 }
1225 }
1226 grid
1227 }
1228}
1229
1230impl SampleBlock {
1231 fn lower_bound(&self, point: Vec3) -> f64 {
1239 let gap = |p: f64, low: f64, high: f64| {
1240 if p < low {
1241 low - p
1242 } else if p > high {
1243 p - high
1244 } else {
1245 0.0
1246 }
1247 };
1248 let x = gap(point.x, self.low.x, self.high.x);
1249 let y = gap(point.y, self.low.y, self.high.y);
1250 let z = gap(point.z, self.low.z, self.high.z);
1251 x * x + y * y + z * z
1252 }
1253}
1254
1255fn pruned_scan() -> bool {
1258 switch!("BREP_PROJECTION_PRUNED_SCAN", true)
1259}
1260
1261fn nearest_sample(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1271 if !grid.tree.is_empty() && scan_tree() && pruned_scan() && bound_first_scan() {
1272 nearest_sample_tree(grid, point, best);
1273 return;
1274 }
1275 nearest_sample_with(grid, point, best, pruned_scan(), bound_first_scan());
1276}
1277
1278fn scan_tree() -> bool {
1290 switch!("BREP_PROJECTION_SCAN_TREE", true)
1291}
1292
1293fn scan_hint() -> bool {
1303 switch!("BREP_PROJECTION_SCAN_HINT", true)
1304}
1305
1306const HINT_SLOTS: usize = 8;
1307
1308thread_local! {
1309 static SCAN_HINTS: std::cell::Cell<[(usize, usize); HINT_SLOTS]> =
1311 const { std::cell::Cell::new([(0, usize::MAX); HINT_SLOTS]) };
1312}
1313
1314fn hint_slot(grid: &SampleGrid) -> (usize, usize) {
1315 let address = grid.samples.as_ptr() as usize;
1316 (address, (address >> 4) % HINT_SLOTS)
1317}
1318
1319fn hinted_bound(grid: &SampleGrid, point: Vec3, mut bound: f64) -> f64 {
1326 if !scan_hint() {
1327 return bound;
1328 }
1329 let (address, slot) = hint_slot(grid);
1330 let (held, run) = SCAN_HINTS.with(|hints| hints.get()[slot]);
1331 if held != address || run >= grid.blocks.len() || !grid.blocks[run].prunable {
1332 return bound;
1333 }
1334 let start = run * SAMPLE_BLOCK;
1335 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1336 for &(_, _, sample) in &grid.samples[start..end] {
1337 let distance_squared = sample.sub(point).length_squared();
1338 if distance_squared < bound {
1339 bound = distance_squared;
1340 }
1341 }
1342 bound
1343}
1344
1345fn remember_hint(grid: &SampleGrid, run: Option<usize>) {
1347 if let Some(run) = run.filter(|_| scan_hint()) {
1348 let (address, slot) = hint_slot(grid);
1349 SCAN_HINTS.with(|hints| {
1350 let mut all = hints.get();
1351 all[slot] = (address, run);
1352 hints.set(all);
1353 });
1354 }
1355}
1356
1357fn nearest_sample_tree(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1368 let top = grid.tree.len() - 1;
1369 let mut bound = best.distance_squared;
1370 let mut node = 0usize;
1372 let mut reached = true;
1373 for level in (0..=top).rev() {
1374 let children = |count: usize| node * TREE_FANOUT..((node + 1) * TREE_FANOUT).min(count);
1375 let below = if level == 0 { &grid.blocks } else { &grid.tree[level - 1] };
1376 match lowest_floor(below, children(below.len()), point) {
1377 Some(child) => node = child,
1378 None => {
1379 reached = false;
1380 break;
1381 }
1382 }
1383 }
1384 if reached {
1385 let start = node * SAMPLE_BLOCK;
1386 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1387 for &(_, _, sample) in &grid.samples[start..end] {
1388 let distance_squared = sample.sub(point).length_squared();
1389 if distance_squared < bound {
1390 bound = distance_squared;
1391 }
1392 }
1393 }
1394 let bound = hinted_bound(grid, point, bound);
1395 let skip = |box_: &SampleBlock, held: f64| {
1396 if !box_.prunable {
1397 return false;
1398 }
1399 let floor = box_.lower_bound(point);
1400 floor >= held || floor > bound
1401 };
1402 let mut answer_run = None;
1403 let mut stack: Vec<(usize, usize)> = Vec::with_capacity(TREE_FANOUT * (top + 2));
1405 stack.push((top + 1, 0));
1406 while let Some((level, index)) = stack.pop() {
1407 if level == 0 {
1408 if skip(&grid.blocks[index], best.distance_squared) {
1409 continue;
1410 }
1411 let start = index * SAMPLE_BLOCK;
1412 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1413 let held = best.distance_squared;
1414 scan_run(&grid.samples[start..end], point, best);
1415 if best.distance_squared < held {
1416 answer_run = Some(index);
1417 }
1418 continue;
1419 }
1420 if skip(&grid.tree[level - 1][index], best.distance_squared) {
1421 continue;
1422 }
1423 let count = if level == 1 { grid.blocks.len() } else { grid.tree[level - 2].len() };
1424 let children = index * TREE_FANOUT..((index + 1) * TREE_FANOUT).min(count);
1425 for child in children.rev() {
1427 stack.push((level - 1, child));
1428 }
1429 }
1430 remember_hint(grid, answer_run);
1431}
1432
1433fn bound_first_scan() -> bool {
1449 switch!("BREP_PROJECTION_BOUND_FIRST", true)
1450}
1451
1452fn nearest_sample_with(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult, pruned: bool, bound_first: bool) {
1462 if !(pruned && bound_first) {
1463 for (block, chunk) in grid.blocks.iter().zip(grid.samples.chunks(SAMPLE_BLOCK)) {
1464 if pruned && block.prunable && block.lower_bound(point) >= best.distance_squared {
1465 continue;
1466 }
1467 scan_run(chunk, point, best);
1468 }
1469 return;
1470 }
1471 let mut bound = best.distance_squared;
1474 let lowest_group = lowest_floor(&grid.groups, 0..grid.groups.len(), point);
1475 if let Some(group) = lowest_group {
1476 let runs = group * GROUP_BLOCKS..((group + 1) * GROUP_BLOCKS).min(grid.blocks.len());
1477 if let Some(run) = lowest_floor(&grid.blocks, runs, point) {
1478 let start = run * SAMPLE_BLOCK;
1479 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1480 for &(_, _, sample) in &grid.samples[start..end] {
1481 let distance_squared = sample.sub(point).length_squared();
1482 if distance_squared < bound {
1483 bound = distance_squared;
1484 }
1485 }
1486 }
1487 }
1488 let bound = hinted_bound(grid, point, bound);
1489 let skip = |box_: &SampleBlock, held: f64| {
1490 if !box_.prunable {
1491 return false;
1492 }
1493 let floor = box_.lower_bound(point);
1494 floor >= held || floor > bound
1495 };
1496 let mut answer_run = None;
1497 for (group_index, group) in grid.groups.iter().enumerate() {
1498 if skip(group, best.distance_squared) {
1499 continue;
1500 }
1501 let first = group_index * GROUP_BLOCKS;
1502 let last = (first + GROUP_BLOCKS).min(grid.blocks.len());
1503 for run in first..last {
1504 if skip(&grid.blocks[run], best.distance_squared) {
1505 continue;
1506 }
1507 let start = run * SAMPLE_BLOCK;
1508 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1509 let held = best.distance_squared;
1510 scan_run(&grid.samples[start..end], point, best);
1511 if best.distance_squared < held {
1512 answer_run = Some(run);
1513 }
1514 }
1515 }
1516 remember_hint(grid, answer_run);
1517}
1518
1519fn scan_run(run: &[(f64, f64, Vec3)], point: Vec3, best: &mut NewtonResult) {
1522 for &(u, v, sample) in run {
1523 let distance_squared = sample.sub(point).length_squared();
1524 if distance_squared < best.distance_squared {
1525 best.u = u;
1526 best.v = v;
1527 best.distance_squared = distance_squared;
1528 }
1529 }
1530}
1531
1532fn lowest_floor(boxes: &[SampleBlock], range: std::ops::Range<usize>, point: Vec3) -> Option<usize> {
1535 let mut lowest: Option<(usize, f64)> = None;
1536 for index in range {
1537 let box_ = &boxes[index];
1538 if !box_.prunable {
1539 continue;
1540 }
1541 let floor = box_.lower_bound(point);
1542 if lowest.is_none_or(|(_, held)| floor < held) {
1543 lowest = Some((index, floor));
1544 }
1545 }
1546 lowest.map(|(index, _)| index)
1547}
1548
1549const RING_EXPONENTS: usize = 22;
1553const RING_INDICES: usize = 33; #[inline]
1556fn ring_slot(side: usize, exponent_index: usize, index: usize) -> usize {
1557 (side * RING_EXPONENTS + exponent_index) * RING_INDICES + index
1558}
1559
1560fn projection_ring_grid(surface: &NurbsSurface) -> Result<&[Vec3], String> {
1567 if let Some(grid) = surface.projection_ring_grid.get() {
1568 return Ok(grid);
1569 }
1570 let [u0, u1] = surface.domain_u()?;
1571 let [v0, v1] = surface.domain_v()?;
1572 let mut grid = vec![Vec3::default(); 4 * RING_EXPONENTS * RING_INDICES];
1573 for exponent in 1..=RING_EXPONENTS as i32 {
1574 let offset = 1.0 / 2f64.powi(exponent);
1575 let e = exponent as usize - 1;
1576 let v_lo = v0 + (v1 - v0) * offset;
1577 let v_hi = v1 - (v1 - v0) * offset;
1578 let u_lo = u0 + (u1 - u0) * offset;
1579 let u_hi = u1 - (u1 - u0) * offset;
1580 for index in 0..=32 {
1581 let u = u0 + (u1 - u0) * index as f64 / 32.0;
1582 grid[ring_slot(0, e, index as usize)] = surface.evaluate(u, v_lo)?;
1583 grid[ring_slot(1, e, index as usize)] = surface.evaluate(u, v_hi)?;
1584 }
1585 for index in 0..=32 {
1586 let v = v0 + (v1 - v0) * index as f64 / 32.0;
1587 grid[ring_slot(2, e, index as usize)] = surface.evaluate(u_lo, v)?;
1588 grid[ring_slot(3, e, index as usize)] = surface.evaluate(u_hi, v)?;
1589 }
1590 }
1591 Ok(surface.projection_ring_grid.get_or_init(|| grid))
1592}
1593
1594fn nearest_seed_answer(
1604 surface: &NurbsSurface,
1605 point: Vec3,
1606 [u0, u1, v0, v1]: [f64; 4],
1607 closed_u: bool,
1608 closed_v: bool,
1609) -> Result<NewtonResult, String> {
1610 let mut best = NewtonResult {
1611 u: u0,
1612 v: v0,
1613 distance_squared: f64::INFINITY,
1614 converged: false,
1615 };
1616 nearest_sample(projection_seed_grid(surface)?, point, &mut best);
1617 if let Some(revolution) = project_linear_revolution(surface, point)? {
1618 if revolution.distance * revolution.distance < best.distance_squared {
1619 best.u = revolution.u;
1620 best.v = revolution.v;
1621 best.distance_squared = revolution.distance * revolution.distance;
1622 }
1623 }
1624 let first_newton = surface_newton(
1625 surface,
1626 point,
1627 best.u,
1628 best.v,
1629 [u0, u1, v0, v1],
1630 closed_u,
1631 closed_v,
1632 )?;
1633 if first_newton.distance_squared < best.distance_squared {
1634 best = first_newton;
1635 }
1636 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1637 let degenerate = su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length());
1638 if degenerate || !first_newton.converged {
1639 let mut grid = best;
1640 nearest_sample(projection_dense_grid(surface)?, point, &mut grid);
1641 if grid.distance_squared < best.distance_squared {
1642 best = grid;
1643 }
1644 let polished = surface_newton(
1645 surface,
1646 point,
1647 grid.u,
1648 grid.v,
1649 [u0, u1, v0, v1],
1650 closed_u,
1651 closed_v,
1652 )?;
1653 if polished.distance_squared < best.distance_squared {
1654 best = polished;
1655 }
1656
1657 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1658 if su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length()) {
1659 let ring_grid = projection_ring_grid(surface)?;
1660 let mut ring = best;
1661 let scan = |side: usize,
1665 exponent_index: usize,
1666 along_u: bool,
1667 fixed: f64,
1668 candidate: &mut NewtonResult| {
1669 for index in 0..=32 {
1670 let moving = if along_u {
1671 u0 + (u1 - u0) * index as f64 / 32.0
1672 } else {
1673 v0 + (v1 - v0) * index as f64 / 32.0
1674 };
1675 let (u, v) = if along_u {
1676 (moving, fixed)
1677 } else {
1678 (fixed, moving)
1679 };
1680 let distance_squared = ring_grid
1681 [ring_slot(side, exponent_index, index as usize)]
1682 .sub(point)
1683 .length_squared();
1684 if distance_squared < candidate.distance_squared {
1685 candidate.u = u;
1686 candidate.v = v;
1687 candidate.distance_squared = distance_squared;
1688 }
1689 }
1690 };
1691 for exponent in 1..=22 {
1692 let offset = 1.0 / 2f64.powi(exponent);
1693 let e = exponent as usize - 1;
1694 if (best.v - v0).abs() <= (v1 - v0) * 0.02 {
1695 scan(0, e, true, v0 + (v1 - v0) * offset, &mut ring);
1696 }
1697 if (best.v - v1).abs() <= (v1 - v0) * 0.02 {
1698 scan(1, e, true, v1 - (v1 - v0) * offset, &mut ring);
1699 }
1700 if (best.u - u0).abs() <= (u1 - u0) * 0.02 {
1701 scan(2, e, false, u0 + (u1 - u0) * offset, &mut ring);
1702 }
1703 if (best.u - u1).abs() <= (u1 - u0) * 0.02 {
1704 scan(3, e, false, u1 - (u1 - u0) * offset, &mut ring);
1705 }
1706 }
1707 if ring.distance_squared < best.distance_squared {
1708 best = ring;
1709 }
1710 let polished = surface_newton(
1711 surface,
1712 point,
1713 ring.u,
1714 ring.v,
1715 [u0, u1, v0, v1],
1716 closed_u,
1717 closed_v,
1718 )?;
1719 if polished.distance_squared < best.distance_squared {
1720 best = polished;
1721 }
1722 }
1723 }
1724 Ok(best)
1725}
1726
1727fn global_stage_enabled() -> bool {
1732 switch!("BREP_PROJECTION_GLOBAL", true)
1733}
1734
1735pub fn global_site_filter_active() -> bool {
1744 static ACTIVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1749 *ACTIVE.get_or_init(|| {
1750 std::env::var_os("BREP_PROJECTION_GLOBAL_SITES").is_some() || std::env::var_os("BREP_PROJECTION_GLOBAL_EXCEPT").is_some()
1751 })
1752}
1753
1754fn global_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
1755 fn list(name: &str) -> Option<Vec<String>> {
1756 std::env::var(name)
1757 .ok()
1758 .map(|value| value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect())
1759 }
1760 static SITES: std::sync::OnceLock<(Option<Vec<String>>, Option<Vec<String>>)> =
1761 std::sync::OnceLock::new();
1762 let (only, except) = SITES.get_or_init(|| {
1763 (list("BREP_PROJECTION_GLOBAL_SITES"), list("BREP_PROJECTION_GLOBAL_EXCEPT"))
1764 });
1765 if only.is_none() && except.is_none() {
1766 return true;
1767 }
1768 let location = format!("{}:{}", caller.file(), caller.line());
1769 let named = |sites: &Vec<String>| sites.iter().any(|site| location.contains(site.as_str()));
1770 only.as_ref().is_none_or(named) && !except.as_ref().is_some_and(named)
1771}
1772
1773fn audit_record(caller: &std::panic::Location<'_>, surface: &NurbsSurface, local: &NewtonResult, global: &NewtonResult) {
1779 use std::io::Write;
1780 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1781 std::sync::OnceLock::new();
1782 let sink = SINK.get_or_init(|| {
1783 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1784 let path = std::path::Path::new(&directory)
1785 .join(format!("projection-audit-{}.tsv", std::process::id()));
1786 std::fs::OpenOptions::new()
1787 .create(true)
1788 .append(true)
1789 .open(path)
1790 .ok()
1791 .map(std::sync::Mutex::new)
1792 });
1793 if let Some(file) = sink {
1794 if let Ok(mut file) = file.lock() {
1795 let _ = writeln!(
1796 file,
1797 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{}x{} cp {}x{}",
1798 caller.file(),
1799 caller.line(),
1800 local.distance_squared.sqrt(),
1801 global.distance_squared.sqrt(),
1802 local.u,
1803 local.v,
1804 global.u,
1805 global.v,
1806 surface.degree_u,
1807 surface.degree_v,
1808 surface.control_points.len(),
1809 surface.control_points.first().map(Vec::len).unwrap_or(0),
1810 );
1811 }
1812 }
1813}
1814
1815#[track_caller]
1891pub fn project_point_to_surface_general(
1892 surface: &NurbsSurface,
1893 point: Vec3,
1894) -> Result<SurfaceProjection, String> {
1895 if !surface_projection_memo_enabled() || !surface_projection_memo_admitted() {
1896 return project_point_to_surface_general_fresh(surface, point);
1897 }
1898 let key = (surface.content_key(), [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()], forced_switches_key());
1899 if let Some(hit) = SURFACE_PROJECTION_MEMO.with(|memo| memo.borrow().get(&key).copied()) {
1900 if surface_projection_memo_check() {
1901 let fresh = project_point_to_surface_general_fresh(surface, point)?;
1902 let bits = |p: &SurfaceProjection| [p.u.to_bits(), p.v.to_bits(), p.point.x.to_bits(), p.point.y.to_bits(), p.point.z.to_bits(), p.distance.to_bits()];
1903 assert_eq!(bits(&hit), bits(&fresh), "surface projection memo check: held {hit:?} vs fresh {fresh:?}");
1904 }
1905 return Ok(hit);
1906 }
1907 let answer = project_point_to_surface_general_fresh(surface, point)?;
1908 SURFACE_PROJECTION_MEMO.with(|memo| {
1909 let mut memo = memo.borrow_mut();
1910 if memo.len() >= SURFACE_PROJECTION_MEMO_ENTRIES {
1911 memo.clear();
1912 }
1913 memo.insert(key, answer);
1914 });
1915 Ok(answer)
1916}
1917
1918fn surface_projection_memo_enabled() -> bool {
1931 switch!("BREP_SURFACE_PROJECTION_MEMO", true)
1932}
1933
1934fn surface_projection_memo_check() -> bool {
1935 switch!("BREP_SURFACE_PROJECTION_MEMO_CHECK", false)
1936}
1937
1938fn surface_projection_memo_admitted() -> bool {
1942 static CALLER_FREE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1943 crate::env_read::read_once_enabled() && *CALLER_FREE.get_or_init(|| {
1944 env_read!("BREP_PROJECTION_GLOBAL_SITES").is_none()
1945 && env_read!("BREP_PROJECTION_GLOBAL_EXCEPT").is_none()
1946 && env_read!("BREP_PROJECTION_AUDIT").is_none()
1947 })
1948}
1949
1950fn forced_switches_key() -> u64 {
1954 0
1955}
1956
1957const SURFACE_PROJECTION_MEMO_ENTRIES: usize = 1 << 14;
1963
1964thread_local! {
1965 static SURFACE_PROJECTION_MEMO: std::cell::RefCell<rustc_hash::FxHashMap<([u64; 2], [u64; 3], u64), SurfaceProjection>> = Default::default();
1966}
1967
1968#[track_caller]
1969fn project_point_to_surface_general_fresh(
1970 surface: &NurbsSurface,
1971 point: Vec3,
1972) -> Result<SurfaceProjection, String> {
1973 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_GENERAL, surface);
1974 let [u0, u1] = surface.domain_u()?;
1975 let [v0, v1] = surface.domain_v()?;
1976 let (closed_u, closed_v) = surface.closed_directions()?;
1977 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1978 let mut best = local;
1979 if global_stage_enabled() {
1980 global_minimum(
1981 surface,
1982 point,
1983 [u0, u1, v0, v1],
1984 (closed_u, closed_v),
1985 &mut best,
1986 &mut GlobalStats::default(),
1987 )?;
1988 if best.u != local.u || best.v != local.v {
1989 let caller = std::panic::Location::caller();
1990 if global_answer_admitted(caller) {
1991 audit_record(caller, surface, &local, &best);
1992 } else {
1993 best = local;
1994 }
1995 }
1996 }
1997 let projected = surface.evaluate(best.u, best.v)?;
1998 Ok(SurfaceProjection {
1999 u: best.u,
2000 v: best.v,
2001 point: projected,
2002 distance: projected.sub(point).length(),
2003 })
2004}
2005
2006pub fn project_point_to_surface_from_nearest_seed(
2016 surface: &NurbsSurface,
2017 point: Vec3,
2018) -> Result<SurfaceProjection, String> {
2019 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_NEAREST_SEED, surface);
2020 if let Some(analytic) = surface.analytic() {
2021 if let Some(projection) = analytic.project(surface, point) {
2022 return Ok(projection);
2023 }
2024 }
2025 if let Some(ellipsoid) = surface.affine_sphere() {
2026 if let Some(projection) = ellipsoid.project(surface, point) {
2027 return Ok(projection);
2028 }
2029 }
2030 let [u0, u1] = surface.domain_u()?;
2031 let [v0, v1] = surface.domain_v()?;
2032 let (closed_u, closed_v) = surface.closed_directions()?;
2033 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
2034 let projected = surface.evaluate(local.u, local.v)?;
2035 Ok(SurfaceProjection {
2036 u: local.u,
2037 v: local.v,
2038 point: projected,
2039 distance: projected.sub(point).length(),
2040 })
2041}
2042
2043#[doc(hidden)]
2046pub fn project_point_to_surface_general_lanes(
2047 surface: &NurbsSurface,
2048 point: Vec3,
2049 run_global: bool,
2050) -> Result<(SurfaceProjection, GlobalStats), String> {
2051 let [u0, u1] = surface.domain_u()?;
2052 let [v0, v1] = surface.domain_v()?;
2053 let (closed_u, closed_v) = surface.closed_directions()?;
2054 let mut best = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
2055 let mut stats = GlobalStats::default();
2056 if run_global {
2057 global_minimum(surface, point, [u0, u1, v0, v1], (closed_u, closed_v), &mut best, &mut stats)?;
2058 }
2059 let projected = surface.evaluate(best.u, best.v)?;
2060 Ok((
2061 SurfaceProjection {
2062 u: best.u,
2063 v: best.v,
2064 point: projected,
2065 distance: projected.sub(point).length(),
2066 },
2067 stats,
2068 ))
2069}
2070
2071#[doc(hidden)]
2074#[derive(Clone, Debug, Default)]
2075pub struct BasinCensus {
2076 pub cells: usize,
2079 pub descents: usize,
2081 pub unconverged: usize,
2083 pub cells_with_two_basins: usize,
2087 pub foot_cells_with_two_basins: usize,
2090 pub least: f64,
2092 pub least_uv: (f64, f64),
2093 pub foot_cell_descents: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)>,
2097}
2098
2099#[doc(hidden)]
2104pub fn project_point_to_surface_basin_census(
2105 surface: &NurbsSurface,
2106 point: Vec3,
2107 answer_distance: f64,
2108 bar: f64,
2109) -> Result<BasinCensus, String> {
2110 let mut census = BasinCensus {
2111 least: f64::INFINITY,
2112 ..BasinCensus::default()
2113 };
2114 let Some(cells) = projection_cells(surface)? else {
2115 return Ok(census);
2116 };
2117 let columns = cells.vs.len() - 1;
2118 let mut spreads: Vec<(usize, f64)> = Vec::new();
2119 let mut runs: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)> = Vec::new();
2120 for (cell, cell_box) in cells.boxes.iter().enumerate() {
2121 if cell_box.lower_bound(point) >= answer_distance {
2122 continue;
2123 }
2124 census.cells += 1;
2125 let (row, column) = (cell / columns, cell % columns);
2126 let rectangle = [cells.us[row], cells.us[row + 1], cells.vs[column], cells.vs[column + 1]];
2127 let middle = ((rectangle[0] + rectangle[1]) * 0.5, (rectangle[2] + rectangle[3]) * 0.5);
2128 let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
2129 for seed in [
2130 (rectangle[0], rectangle[2]),
2131 (rectangle[1], rectangle[2]),
2132 (rectangle[0], rectangle[3]),
2133 (rectangle[1], rectangle[3]),
2134 middle,
2135 ] {
2136 census.descents += 1;
2137 let (found, _) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2138 let distance = found.distance_squared.sqrt();
2139 runs.push((cell, rectangle, seed, (found.u, found.v), distance, found.converged));
2140 if distance < census.least {
2141 census.least = distance;
2142 census.least_uv = (found.u, found.v);
2143 }
2144 if !found.converged {
2145 census.unconverged += 1;
2146 continue;
2147 }
2148 low = low.min(distance.max(LINEAR_TOLERANCE));
2149 high = high.max(distance.max(LINEAR_TOLERANCE));
2150 }
2151 if high - low > bar {
2152 spreads.push((cell, high - low));
2153 }
2154 }
2155 census.cells_with_two_basins = spreads.len();
2156 let (u, v) = census.least_uv;
2157 let foot_cells: Vec<usize> = spreads
2158 .iter()
2159 .map(|&(cell, _)| cell)
2160 .filter(|&cell| {
2161 let (row, column) = (cell / columns, cell % columns);
2162 cells.us[row] <= u && u <= cells.us[row + 1] && cells.vs[column] <= v && v <= cells.vs[column + 1]
2163 })
2164 .collect();
2165 census.foot_cells_with_two_basins = foot_cells.len();
2166 census.foot_cell_descents = runs.into_iter().filter(|run| foot_cells.contains(&run.0)).collect();
2167 Ok(census)
2168}
2169
2170#[doc(hidden)]
2172#[derive(Clone, Copy, Debug, Default)]
2173pub struct GlobalStats {
2174 pub settled_by_floor: bool,
2176 pub candidates: usize,
2178 pub refinements: usize,
2180 pub continuations: usize,
2182 pub replaced: bool,
2184 pub hull_lower_bound: f64,
2187}
2188
2189#[derive(Clone, Debug)]
2192struct CellBox {
2193 axes: [Vec3; 3],
2194 low: [f64; 3],
2195 high: [f64; 3],
2196}
2197
2198impl CellBox {
2199 fn lower_bound(&self, point: Vec3) -> f64 {
2202 let mut squared = 0.0;
2203 for axis in 0..3 {
2204 let coordinate = point.dot(self.axes[axis]);
2205 let excess = (self.low[axis] - coordinate).max(coordinate - self.high[axis]).max(0.0);
2206 squared += excess * excess;
2207 }
2208 squared.sqrt()
2209 }
2210}
2211
2212#[derive(Clone, Copy, Debug)]
2215struct CellTreeNode {
2216 centre: Vec3,
2217 radius: f64,
2218 children: Option<(u32, u32)>,
2219 cell: u32,
2220}
2221
2222#[derive(Clone, Debug)]
2228pub struct ProjectionCells {
2229 us: std::sync::Arc<[f64]>,
2230 vs: std::sync::Arc<[f64]>,
2231 nodes: std::sync::Arc<[Vec3]>,
2233 boxes: std::sync::Arc<[CellBox]>,
2235 tree: std::sync::Arc<[CellTreeNode]>,
2237 node_boxes: std::sync::Arc<[CellBox]>,
2241 node_margin: f64,
2243 scale: f64,
2245 resolution: f64,
2246 split: [usize; 2],
2250 sub_nodes: std::sync::Arc<std::sync::Mutex<rustc_hash::FxHashMap<(u32, u32), Vec3>>>,
2254 sub_boxes: std::sync::Arc<std::sync::Mutex<rustc_hash::FxHashMap<usize, Option<CellBox>>>>,
2259 samples: [usize; 2],
2261}
2262
2263fn lattice_parameters(knots: &[f64], degree: usize, closed: bool) -> Vec<f64> {
2267 lattice_parameters_at(knots, degree, closed, false)
2268}
2269
2270fn lattice_samples(degree: usize, closed: bool, coarse: bool) -> usize {
2275 if closed {
2276 8usize.max(degree * 4)
2277 } else if coarse && degree >= 4 {
2278 COARSE_SAMPLES
2279 } else {
2280 3usize.max(degree + 1)
2281 }
2282}
2283
2284fn coarse_split(degree: usize, closed: bool, coarse: bool) -> usize {
2288 if coarse && !closed && degree >= 4 { (degree + 1).div_ceil(COARSE_SAMPLES) } else { 1 }
2289}
2290
2291fn lattice_parameters_at(knots: &[f64], degree: usize, closed: bool, coarse: bool) -> Vec<f64> {
2292 let [start, end] = crate::curve::knot_domain(knots, degree);
2293 let samples = lattice_samples(degree, closed, coarse);
2294 let mut breaks = vec![start];
2295 breaks.extend(interior_knots(knots, degree));
2296 breaks.push(end);
2297 let mut parameters = Vec::with_capacity((breaks.len() - 1) * samples + 1);
2298 for pair in breaks.windows(2) {
2299 for index in 0..samples {
2300 parameters.push(pair[0] + (pair[1] - pair[0]) * index as f64 / samples as f64);
2301 }
2302 }
2303 parameters.push(end);
2304 parameters
2305}
2306
2307fn refine_to_lattice(net: &mut Vec<Vec<Vec4>>, knots: &mut Vec<f64>, degree: usize, parameters: &[f64]) {
2316 let p = degree;
2317 let n = net.len() - 1;
2318 let mut inserted = Vec::new();
2319 for ¶meter in parameters {
2320 let multiplicity = knots.iter().filter(|&&knot| knot == parameter).count();
2321 for _ in multiplicity..p {
2322 inserted.push(parameter);
2323 }
2324 }
2325 if inserted.is_empty() || p == 0 {
2326 return;
2327 }
2328 inserted.sort_by(f64::total_cmp);
2329 let find_span = |parameter: f64| -> usize {
2330 if parameter >= knots[n + 1] {
2331 return n;
2332 }
2333 (knots.partition_point(|&knot| knot <= parameter) - 1).clamp(p, n)
2334 };
2335 let r = inserted.len() - 1;
2336 let m = n + p + 1;
2337 let a = find_span(inserted[0]);
2338 let b = find_span(inserted[r]) + 1;
2339 let columns = net[0].len();
2340 let blank = vec![
2341 Vec4 {
2342 x: 0.0,
2343 y: 0.0,
2344 z: 0.0,
2345 w: 0.0,
2346 };
2347 columns
2348 ];
2349 let mut refined = vec![blank; n + r + 2];
2350 let mut refined_knots = vec![0.0; m + r + 2];
2351 for j in 0..=a - p {
2352 refined[j] = net[j].clone();
2353 }
2354 for j in b - 1..=n {
2355 refined[j + r + 1] = net[j].clone();
2356 }
2357 refined_knots[..=a].copy_from_slice(&knots[..=a]);
2358 for j in b + p..=m {
2359 refined_knots[j + r + 1] = knots[j];
2360 }
2361 let mut i = b + p - 1;
2362 let mut k = b + p + r;
2363 for j in (0..=r).rev() {
2364 while inserted[j] <= knots[i] && i > a {
2365 refined[k - p - 1] = net[i - p - 1].clone();
2366 refined_knots[k] = knots[i];
2367 k -= 1;
2368 i -= 1;
2369 }
2370 refined[k - p - 1] = refined[k - p].clone();
2371 for l in 1..=p {
2372 let index = k - p + l;
2373 let numerator = refined_knots[k + l] - inserted[j];
2374 if numerator == 0.0 {
2375 refined[index - 1] = refined[index].clone();
2376 } else {
2377 let alpha = numerator / (refined_knots[k + l] - knots[i - p + l]);
2378 let (head, tail) = refined.split_at_mut(index);
2379 for (before, &here) in head[index - 1].iter_mut().zip(&tail[0]) {
2380 *before = before.scale(alpha).add(here.scale(1.0 - alpha));
2381 }
2382 }
2383 }
2384 refined_knots[k] = inserted[j];
2385 k = k.saturating_sub(1);
2386 }
2387 *net = refined;
2388 *knots = refined_knots;
2389}
2390
2391fn supporting_range(knots: &[f64], degree: usize, count: usize, low: f64, high: f64) -> (usize, usize) {
2394 let first_span = knots.partition_point(|&knot| knot <= low).saturating_sub(1);
2395 let last_span = knots.partition_point(|&knot| knot < high).saturating_sub(1);
2396 (
2397 first_span.saturating_sub(degree).min(count - 1),
2398 last_span.max(first_span).min(count - 1),
2399 )
2400}
2401
2402fn unit_or(vector: Vec3, fallback: Vec3) -> Vec3 {
2403 let length = vector.length();
2404 if length > 0.0 && length.is_finite() {
2405 vector.scale(1.0 / length)
2406 } else {
2407 fallback
2408 }
2409}
2410
2411fn enclosing_sphere(a: (Vec3, f64), b: (Vec3, f64)) -> (Vec3, f64) {
2412 let offset = b.0.sub(a.0);
2413 let separation = offset.length();
2414 if separation + b.1 <= a.1 {
2415 return a;
2416 }
2417 if separation + a.1 <= b.1 {
2418 return b;
2419 }
2420 let radius = (separation + a.1 + b.1) * 0.5;
2421 let centre = a.0.add(offset.scale((radius - a.1) / separation));
2422 (centre, radius)
2423}
2424
2425struct NodeBoxInputs<'a> {
2429 boxes: &'a [CellBox],
2430 nodes: &'a [Vec3],
2431 lattice_columns: usize,
2432 margin: f64,
2433}
2434
2435fn framed_box(points: &[Vec3], columns: usize, margin: f64) -> Option<CellBox> {
2439 if columns == 0 || points.len() < columns || points.len() % columns != 0 {
2440 return None;
2441 }
2442 let last = points.len() - columns;
2443 let (c00, c01, c10, c11) = (points[0], points[columns - 1], points[last], points[last + columns - 1]);
2444 let along_u = c10.sub(c00).add(c11.sub(c01));
2445 let along_v = c01.sub(c00).add(c11.sub(c10));
2446 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2447 let fallback = e1.perpendicular().ok()?;
2448 let normal = unit_or(e1.cross(along_v), fallback);
2449 let e2 = unit_or(normal.cross(e1), fallback);
2450 let e3 = e1.cross(e2);
2451 let axes = [e1, e2, e3];
2452 let mut low = [f64::INFINITY; 3];
2453 let mut high = [f64::NEG_INFINITY; 3];
2454 for point in points {
2455 for axis in 0..3 {
2456 let coordinate = point.dot(axes[axis]);
2457 low[axis] = low[axis].min(coordinate);
2458 high[axis] = high[axis].max(coordinate);
2459 }
2460 }
2461 for axis in 0..3 {
2462 low[axis] -= margin;
2463 high[axis] += margin;
2464 }
2465 low.iter().chain(high.iter()).all(|value| value.is_finite()).then_some(CellBox { axes, low, high })
2466}
2467
2468fn enclosing_node_box(corners: [Vec3; 4], children: [&CellBox; 2], margin: f64) -> CellBox {
2473 let unbounded = || CellBox {
2474 axes: [Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0)],
2475 low: [f64::NEG_INFINITY; 3],
2476 high: [f64::INFINITY; 3],
2477 };
2478 let [c00, c10, c01, c11] = corners;
2479 let along_u = c10.sub(c00).add(c11.sub(c01));
2480 let along_v = c01.sub(c00).add(c11.sub(c10));
2481 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2482 let Ok(fallback) = e1.perpendicular() else {
2483 return unbounded();
2484 };
2485 let normal = unit_or(e1.cross(along_v), fallback);
2486 let e2 = unit_or(normal.cross(e1), fallback);
2487 let e3 = e1.cross(e2);
2488 let axes = [e1, e2, e3];
2489 let mut low = [f64::INFINITY; 3];
2490 let mut high = [f64::NEG_INFINITY; 3];
2491 for child in children {
2492 for corner in 0..8 {
2493 let mut point = Vec3::default();
2494 for axis in 0..3 {
2495 let value = if corner >> axis & 1 == 0 { child.low[axis] } else { child.high[axis] };
2496 point = point.add(child.axes[axis].scale(value));
2497 }
2498 for axis in 0..3 {
2499 let coordinate = point.dot(axes[axis]);
2500 low[axis] = low[axis].min(coordinate);
2501 high[axis] = high[axis].max(coordinate);
2502 }
2503 }
2504 }
2505 for axis in 0..3 {
2506 low[axis] -= margin;
2507 high[axis] += margin;
2508 }
2509 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2510 return unbounded();
2511 }
2512 CellBox { axes, low, high }
2513}
2514
2515fn build_cell_tree(
2516 tree: &mut Vec<CellTreeNode>,
2517 node_boxes: &mut Vec<CellBox>,
2518 inputs: &NodeBoxInputs<'_>,
2519 spheres: &[(Vec3, f64)],
2520 columns: usize,
2521 [row_low, row_high, column_low, column_high]: [usize; 4],
2522) -> u32 {
2523 if row_high - row_low == 1 && column_high - column_low == 1 {
2524 let cell = row_low * columns + column_low;
2525 node_boxes.push(inputs.boxes[cell].clone());
2526 tree.push(CellTreeNode {
2527 centre: spheres[cell].0,
2528 radius: spheres[cell].1,
2529 children: None,
2530 cell: cell as u32,
2531 });
2532 return (tree.len() - 1) as u32;
2533 }
2534 let (first, second) = if row_high - row_low >= column_high - column_low {
2535 let middle = (row_low + row_high) / 2;
2536 (
2537 [row_low, middle, column_low, column_high],
2538 [middle, row_high, column_low, column_high],
2539 )
2540 } else {
2541 let middle = (column_low + column_high) / 2;
2542 (
2543 [row_low, row_high, column_low, middle],
2544 [row_low, row_high, middle, column_high],
2545 )
2546 };
2547 let first = build_cell_tree(tree, node_boxes, inputs, spheres, columns, first);
2548 let second = build_cell_tree(tree, node_boxes, inputs, spheres, columns, second);
2549 let a = tree[first as usize];
2550 let b = tree[second as usize];
2551 let lattice = |row: usize, column: usize| inputs.nodes[row * inputs.lattice_columns + column];
2552 node_boxes.push(enclosing_node_box(
2553 [
2554 lattice(row_low, column_low),
2555 lattice(row_high, column_low),
2556 lattice(row_low, column_high),
2557 lattice(row_high, column_high),
2558 ],
2559 [&node_boxes[first as usize], &node_boxes[second as usize]],
2560 inputs.margin,
2561 ));
2562 let (centre, radius) = enclosing_sphere((a.centre, a.radius), (b.centre, b.radius));
2566 tree.push(CellTreeNode {
2567 centre,
2568 radius: radius * (1.0 + 4.0 * f64::EPSILON),
2569 children: Some((first, second)),
2570 cell: u32::MAX,
2571 });
2572 (tree.len() - 1) as u32
2573}
2574
2575fn projection_cells(surface: &NurbsSurface) -> Result<Option<&ProjectionCells>, String> {
2576 if let Some(cells) = surface.projection_cells.get() {
2577 return Ok(cells.as_ref());
2578 }
2579 tables_within_limit(surface)?;
2580 let cells = build_projection_cells_at(surface, coarse_lattice_enabled())?;
2581 Ok(surface.projection_cells.get_or_init(|| cells).as_ref())
2582}
2583
2584const COARSE_SAMPLES: usize = 3;
2590
2591fn coarse_lattice_enabled() -> bool {
2601 coarse_lattice_check() || crate::switch!("BREP_PROJECTION_COARSE_LATTICE", true)
2602}
2603
2604fn coarse_lattice_check() -> bool {
2605 crate::switch!("BREP_PROJECTION_COARSE_LATTICE_CHECK", false)
2606}
2607
2608fn coarse_check_bar(resolution: f64) -> f64 {
2612 LINEAR_TOLERANCE.max(16.0 * resolution)
2613}
2614
2615thread_local! {
2616 static DEFAULT_CELLS_FOR_CHECK: std::cell::RefCell<rustc_hash::FxHashMap<[u64; 2], std::rc::Rc<Option<ProjectionCells>>>> = std::cell::RefCell::new(rustc_hash::FxHashMap::default());
2618}
2619
2620fn default_cells_for_check(surface: &NurbsSurface) -> Result<std::rc::Rc<Option<ProjectionCells>>, String> {
2621 let key = surface.content_key();
2622 if let Some(cells) = DEFAULT_CELLS_FOR_CHECK.with(|map| map.borrow().get(&key).cloned()) {
2623 return Ok(cells);
2624 }
2625 let cells = std::rc::Rc::new(build_projection_cells_at(surface, false)?);
2626 DEFAULT_CELLS_FOR_CHECK.with(|map| {
2627 let mut map = map.borrow_mut();
2628 if map.len() >= 256 { map.clear(); }
2630 map.insert(key, cells.clone());
2631 });
2632 Ok(cells)
2633}
2634
2635pub fn projection_tables_bytes(surface: &NurbsSurface) -> u64 {
2650 let bytes = general_tables_bytes(surface);
2651 let closed_form = || surface.analytic().is_some() || surface.affine_sphere().is_some() || surface.linear_extrusion().is_some();
2655 if bytes >= 1 << 20 && closed_form() { 0 } else { bytes }
2656}
2657
2658pub const PROJECTION_TABLES_LIMIT: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
2663
2664fn tables_within_limit(surface: &NurbsSurface) -> Result<(), String> {
2668 let bytes = general_tables_bytes(surface);
2669 if bytes <= PROJECTION_TABLES_LIMIT {
2670 return Ok(());
2671 }
2672 Err(format!(
2673 "surface too finely divided to project onto: its projection tables take about {} MB (limit {} MB)",
2674 bytes >> 20,
2675 PROJECTION_TABLES_LIMIT >> 20
2676 ))
2677}
2678
2679fn general_tables_bytes(surface: &NurbsSurface) -> u64 {
2682 let Ok((closed_u, closed_v)) = surface.closed_directions() else { return 0 };
2683 let coarse = coarse_lattice_enabled();
2684 let spans = |knots: &[f64], degree: usize| interior_knots(knots, degree).len() as u64 + 1;
2685 let (spans_u, spans_v) = (spans(&surface.knots_u, surface.degree_u), spans(&surface.knots_v, surface.degree_v));
2686 let seed = |closed: bool, degree: usize| if closed { 8usize.max(degree * 4) } else { 3usize.max(degree + 1) } as u64 + 1;
2687 let sample = std::mem::size_of::<(f64, f64, Vec3)>() as u64;
2688 let seed_grid = (spans_u * spans_v).saturating_mul(seed(closed_u, surface.degree_u) * seed(closed_v, surface.degree_v)).saturating_mul(sample);
2689 let dense_grid = (32u64.max(spans_u * 8) + 1).saturating_mul(16u64.max(spans_v * 8) + 1).saturating_mul(sample);
2690 let cells_u = spans_u * lattice_samples(surface.degree_u, closed_u, coarse) as u64;
2691 let cells_v = spans_v * lattice_samples(surface.degree_v, closed_v, coarse) as u64;
2692 let refined = (cells_u * surface.degree_u as u64 + 1).saturating_mul(cells_v * surface.degree_v as u64 + 1);
2693 let net = refined.saturating_mul(2 * std::mem::size_of::<Vec4>() as u64 + std::mem::size_of::<Vec3>() as u64);
2694 let per_cell = 3 * std::mem::size_of::<CellBox>() as u64 + 2 * std::mem::size_of::<CellTreeNode>() as u64 + std::mem::size_of::<(Vec3, f64)>() as u64 + std::mem::size_of::<Vec3>() as u64;
2695 let cells = (cells_u * cells_v).saturating_mul(per_cell);
2696 seed_grid.saturating_add(dense_grid).saturating_add(net).saturating_add(cells)
2697}
2698
2699fn build_projection_cells(surface: &NurbsSurface) -> Result<Option<ProjectionCells>, String> {
2700 build_projection_cells_at(surface, false)
2701}
2702
2703fn build_projection_cells_at(surface: &NurbsSurface, coarse: bool) -> Result<Option<ProjectionCells>, String> {
2704 let (closed_u, closed_v) = surface.closed_directions()?;
2705 let us = lattice_parameters_at(&surface.knots_u, surface.degree_u, closed_u, coarse);
2706 let vs = lattice_parameters_at(&surface.knots_v, surface.degree_v, closed_v, coarse);
2707 if us.len() < 2 || vs.len() < 2 {
2708 return Ok(None);
2709 }
2710 let mut scale = 0.0f64;
2711 for control in surface.control_points.iter().flatten() {
2712 let point = control.point()?;
2713 scale = scale.max(point.x.abs()).max(point.y.abs()).max(point.z.abs());
2714 }
2715 let resolution =
2716 ((surface.degree_u + 1) * (surface.degree_v + 1)) as f64 * f64::EPSILON * scale;
2717
2718 let mut net = surface.control_points.clone();
2720 let mut knots_u = surface.knots_u.clone();
2721 refine_to_lattice(&mut net, &mut knots_u, surface.degree_u, &us);
2722 let columns = net.first().map(Vec::len).unwrap_or(0);
2723 let mut transposed: Vec<Vec<Vec4>> =
2724 (0..columns).map(|column| net.iter().map(|row| row[column]).collect()).collect();
2725 let mut knots_v = surface.knots_v.clone();
2726 refine_to_lattice(&mut transposed, &mut knots_v, surface.degree_v, &vs);
2727 let rows = transposed.first().map(Vec::len).unwrap_or(0);
2728 let columns = transposed.len();
2729 if rows == 0 || columns == 0 {
2730 return Ok(None);
2731 }
2732 let split = [coarse_split(surface.degree_u, closed_u, coarse), coarse_split(surface.degree_v, closed_v, coarse)];
2733 let mut points = vec![Vec3::default(); rows * columns];
2734 for (column, fibre) in transposed.iter().enumerate() {
2735 for (row, control) in fibre.iter().enumerate() {
2736 points[row * columns + column] = control.point()?;
2737 }
2738 }
2739
2740 let mut nodes = Vec::with_capacity(us.len() * vs.len());
2741 for &u in &us {
2742 for &v in &vs {
2743 nodes.push(surface.evaluate(u, v)?);
2744 }
2745 }
2746
2747 let cell_rows = us.len() - 1;
2748 let cell_columns = vs.len() - 1;
2749 let mut boxes = Vec::with_capacity(cell_rows * cell_columns);
2750 let mut spheres = Vec::with_capacity(cell_rows * cell_columns);
2751 for i in 0..cell_rows {
2752 let (row_low, row_high) =
2753 supporting_range(&knots_u, surface.degree_u, rows, us[i], us[i + 1]);
2754 for j in 0..cell_columns {
2755 let (column_low, column_high) =
2756 supporting_range(&knots_v, surface.degree_v, columns, vs[j], vs[j + 1]);
2757 let at = |row: usize, column: usize| points[row * columns + column];
2758 let c00 = at(row_low, column_low);
2759 let c10 = at(row_high, column_low);
2760 let c01 = at(row_low, column_high);
2761 let c11 = at(row_high, column_high);
2762 let along_u = c10.sub(c00).add(c11.sub(c01));
2763 let along_v = c01.sub(c00).add(c11.sub(c10));
2764 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2765 let normal = unit_or(e1.cross(along_v), e1.perpendicular()?);
2766 let e2 = unit_or(normal.cross(e1), e1.perpendicular()?);
2767 let e3 = e1.cross(e2);
2768 let axes = [e1, e2, e3];
2769 let mut low = [f64::INFINITY; 3];
2770 let mut high = [f64::NEG_INFINITY; 3];
2771 for row in row_low..=row_high {
2772 for column in column_low..=column_high {
2773 let point = at(row, column);
2774 for axis in 0..3 {
2775 let coordinate = point.dot(axes[axis]);
2776 low[axis] = low[axis].min(coordinate);
2777 high[axis] = high[axis].max(coordinate);
2778 }
2779 }
2780 }
2781 for axis in 0..3 {
2782 low[axis] -= resolution;
2783 high[axis] += resolution;
2784 }
2785 let mut centre = Vec3::default();
2786 let mut half_diagonal_squared = 0.0;
2787 for axis in 0..3 {
2788 centre = centre.add(axes[axis].scale((low[axis] + high[axis]) * 0.5));
2789 let half = (high[axis] - low[axis]) * 0.5;
2790 half_diagonal_squared += half * half;
2791 }
2792 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2793 return Ok(None);
2794 }
2795 spheres.push((centre, half_diagonal_squared.sqrt() + resolution));
2796 boxes.push(CellBox { axes, low, high });
2797 }
2798 }
2799 let mut tree = Vec::with_capacity(2 * boxes.len());
2800 let mut node_boxes = Vec::with_capacity(2 * boxes.len());
2801 let node_margin = NODE_BOX_MARGIN * scale;
2806 let inputs = NodeBoxInputs { boxes: &boxes, nodes: &nodes, lattice_columns: vs.len(), margin: node_margin };
2807 build_cell_tree(&mut tree, &mut node_boxes, &inputs, &spheres, cell_columns, [0, cell_rows, 0, cell_columns]);
2808 if !(node_margin > 0.0 && node_margin.is_finite()) {
2809 node_boxes = Vec::new();
2810 }
2811 Ok(Some(ProjectionCells {
2812 us: us.into(),
2813 vs: vs.into(),
2814 nodes: nodes.into(),
2815 boxes: boxes.into(),
2816 tree: tree.into(),
2817 node_boxes: node_boxes.into(),
2818 node_margin,
2819 scale,
2820 resolution,
2821 split,
2822 sub_nodes: Default::default(),
2823 sub_boxes: Default::default(),
2824 samples: [
2825 lattice_samples(surface.degree_u, closed_u, coarse),
2826 lattice_samples(surface.degree_v, closed_v, coarse),
2827 ],
2828 }))
2829}
2830
2831fn optimality(
2836 derivatives: &[[Vec3; 3]; 3],
2837 point: Vec3,
2838 (u, v): (f64, f64),
2839 [ua, ub, va, vb]: [f64; 4],
2840 periodic: (bool, bool),
2841) -> Optimality {
2842 let residual = derivatives[0][0].sub(point);
2843 let residual_length = residual.length();
2844 let su = derivatives[1][0];
2845 let sv = derivatives[0][1];
2846 let f = su.dot(residual);
2847 let g = sv.dot(residual);
2848 let metric_u = su.length_squared();
2849 let metric_v = sv.length_squared();
2850 let stationary_u = metric_u.sqrt() * residual_length <= EPSILON
2851 || f.abs() <= 1e-10 * metric_u.sqrt() * residual_length;
2852 let stationary_v = metric_v.sqrt() * residual_length <= EPSILON
2853 || g.abs() <= 1e-10 * metric_v.sqrt() * residual_length;
2854 let pinned_u = !periodic.0 && ((u <= ua && f > 0.0) || (u >= ub && f < 0.0));
2855 let pinned_v = !periodic.1 && ((v <= va && g > 0.0) || (v >= vb && g < 0.0));
2856 let j00 = derivatives[2][0].dot(residual) + metric_u;
2857 let j01 = derivatives[1][1].dot(residual) + su.dot(sv);
2858 let j11 = derivatives[0][2].dot(residual) + metric_v;
2859 let determinant = j00 * j11 - j01 * j01;
2860 let convex = match (!pinned_u, !pinned_v) {
2861 (true, true) => j00 > 0.0 && determinant > 0.0,
2862 (true, false) => j00 > 0.0,
2863 (false, true) => j11 > 0.0,
2864 (false, false) => true,
2865 };
2866 Optimality {
2867 residual_length,
2868 gradient: (f, g),
2869 metric: (metric_u, metric_v),
2870 hessian: (j00, j01, j11),
2871 determinant,
2872 pinned: (pinned_u, pinned_v),
2873 convex,
2874 minimum: residual_length <= LINEAR_TOLERANCE
2875 || ((stationary_u || pinned_u) && (stationary_v || pinned_v) && convex),
2876 }
2877}
2878
2879struct Optimality {
2880 residual_length: f64,
2881 gradient: (f64, f64),
2882 metric: (f64, f64),
2883 hessian: (f64, f64, f64),
2884 determinant: f64,
2885 pinned: (bool, bool),
2886 convex: bool,
2887 minimum: bool,
2888}
2889
2890fn is_verified_minimum(
2891 surface: &NurbsSurface,
2892 point: Vec3,
2893 at: (f64, f64),
2894 rectangle: [f64; 4],
2895 periodic: (bool, bool),
2896) -> Result<bool, String> {
2897 let derivatives = surface.derivatives_small(at.0, at.1, 2)?;
2898 Ok(optimality(&derivatives, point, at, rectangle, periodic).minimum)
2899}
2900
2901fn confined_descent(
2917 surface: &NurbsSurface,
2918 point: Vec3,
2919 seed: (f64, f64),
2920 rectangle: [f64; 4],
2921 periodic: (bool, bool),
2922) -> Result<(NewtonResult, bool), String> {
2923 let [ua, ub, va, vb] = rectangle;
2924 let mut u = fit_parameter(seed.0, ua, ub, periodic.0);
2925 let mut v = fit_parameter(seed.1, va, vb, periodic.1);
2926 let mut converged = false;
2927 let mut current = surface.evaluate(u, v)?.sub(point).length_squared();
2928 for _ in 0..MAX_NEWTON_ITERATIONS {
2929 let derivatives = surface.derivatives_small(u, v, 2)?;
2930 let state = optimality(&derivatives, point, (u, v), rectangle, periodic);
2931 current = state.residual_length * state.residual_length;
2932 if state.minimum {
2933 converged = true;
2934 break;
2935 }
2936 let (f, g) = state.gradient;
2937 let (metric_u, metric_v) = state.metric;
2938 let (j00, j01, j11) = state.hessian;
2939 let determinant = state.determinant;
2940 let (free_u, free_v) = (!state.pinned.0, !state.pinned.1);
2941 let (mut du, mut dv) = match (free_u, free_v) {
2942 (true, true) if state.convex => (
2943 (-f * j11 + g * j01) / determinant,
2944 (-g * j00 + f * j01) / determinant,
2945 ),
2946 (true, false) if state.convex => (-f / j00, 0.0),
2947 (false, true) if state.convex => (0.0, -g / j11),
2948 _ => (
2949 if free_u && metric_u > 0.0 { -f / metric_u } else { 0.0 },
2950 if free_v && metric_v > 0.0 { -g / metric_v } else { 0.0 },
2951 ),
2952 };
2953 if !(du.is_finite() && dv.is_finite()) || (du == 0.0 && dv == 0.0) {
2954 break;
2955 }
2956 let mut moved = false;
2957 let taken = |next: f64, here: f64, low: f64, high: f64, wraps: bool| {
2959 let raw = next - here;
2960 if wraps {
2961 raw - (high - low) * (raw / (high - low)).round()
2962 } else {
2963 raw
2964 }
2965 };
2966 for _ in 0..40 {
2967 let next_u = fit_parameter(u + du, ua, ub, periodic.0);
2968 let next_v = fit_parameter(v + dv, va, vb, periodic.1);
2969 if next_u == u && next_v == v {
2970 break;
2971 }
2972 let trial = surface.evaluate(next_u, next_v)?.sub(point).length_squared();
2973 if trial <= current {
2974 moved = taken(next_u, u, ua, ub, periodic.0).abs() > 1e-15 * (ub - ua)
2975 || taken(next_v, v, va, vb, periodic.1).abs() > 1e-15 * (vb - va);
2976 u = next_u;
2977 v = next_v;
2978 current = trial;
2979 break;
2980 }
2981 du *= 0.5;
2982 dv *= 0.5;
2983 }
2984 if !moved {
2985 break;
2986 }
2987 }
2988 let result = NewtonResult {
2989 u,
2990 v,
2991 distance_squared: current,
2992 converged,
2993 };
2994 let on_edge =
2995 (!periodic.0 && (u <= ua || u >= ub)) || (!periodic.1 && (v <= va || v >= vb));
2996 Ok((result, on_edge))
2997}
2998
2999const NODE_BOX_MARGIN: f64 = 1e-9;
3002
3003fn node_boxes_enabled() -> bool {
3007 switch!("BREP_PROJECTION_NODE_BOXES", true)
3008}
3009
3010fn hull_candidates(cells: &ProjectionCells, point: Vec3, bound: f64, node_boxes: bool) -> (Vec<(f64, usize)>, f64) {
3031 let read_error = 32.0 * f64::EPSILON * (point.x.abs() + point.y.abs() + point.z.abs() + 4.0 * cells.scale);
3032 let boxes = node_boxes && !cells.node_boxes.is_empty() && 4.0 * read_error <= cells.node_margin;
3033 let mut candidates: Vec<(f64, usize)> = Vec::new();
3034 let mut excluded = f64::INFINITY;
3035 let mut stack: Vec<u32> = Vec::with_capacity(64);
3036 stack.push((cells.tree.len() - 1) as u32);
3037 while let Some(index) = stack.pop() {
3038 let node = cells.tree[index as usize];
3039 let sphere_bound = (point.sub(node.centre).length() - node.radius).max(0.0);
3040 if sphere_bound >= bound {
3041 excluded = excluded.min(sphere_bound);
3042 continue;
3043 }
3044 match node.children {
3045 Some((first, second)) => {
3046 if boxes {
3047 let box_bound = cells.node_boxes[index as usize].lower_bound(point);
3048 if box_bound >= bound && box_bound > 2.0 * read_error {
3049 excluded = excluded.min(box_bound);
3050 continue;
3051 }
3052 }
3053 stack.push(first);
3054 stack.push(second);
3055 }
3056 None => {
3057 let cell = node.cell as usize;
3058 let box_bound = cells.boxes[cell].lower_bound(point);
3059 if box_bound < bound {
3060 candidates.push((box_bound, cell));
3061 } else {
3062 excluded = excluded.min(box_bound);
3063 }
3064 }
3065 }
3066 }
3067 (candidates, excluded)
3068}
3069
3070#[allow(clippy::too_many_arguments)]
3073fn global_minimum(
3074 surface: &NurbsSurface,
3075 point: Vec3,
3076 domains: [f64; 4],
3077 periodic: (bool, bool),
3078 best: &mut NewtonResult,
3079 stats: &mut GlobalStats,
3080) -> Result<(), String> {
3081 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
3082 stats.settled_by_floor = true;
3083 return Ok(());
3084 }
3085 let Some(cells) = projection_cells(surface)? else {
3086 return Ok(());
3087 };
3088 if coarse_lattice_check() {
3089 let start = *best;
3090 global_minimum_with(surface, cells, point, domains, periodic, best, stats)?;
3091 if let Some(default) = default_cells_for_check(surface)?.as_ref() {
3092 let mut reference = start;
3093 global_minimum_with(surface, default, point, domains, periodic, &mut reference, &mut GlobalStats::default())?;
3094 let (coarse, fine) = (best.distance_squared.sqrt(), reference.distance_squared.sqrt());
3095 if coarse > fine + coarse_check_bar(default.resolution) {
3096 panic!("BREP_PROJECTION_COARSE_LATTICE_CHECK: the coarse lattice reads {coarse:e} where the default reads {fine:e} for {point:?} (degrees {}x{})", surface.degree_u, surface.degree_v);
3097 }
3098 }
3099 return Ok(());
3100 }
3101 global_minimum_with(surface, cells, point, domains, periodic, best, stats)
3102}
3103
3104#[allow(clippy::too_many_arguments)]
3106fn global_minimum_with(
3107 surface: &NurbsSurface,
3108 cells: &ProjectionCells,
3109 point: Vec3,
3110 domains: [f64; 4],
3111 periodic: (bool, bool),
3112 best: &mut NewtonResult,
3113 stats: &mut GlobalStats,
3114) -> Result<(), String> {
3115 let resolution = cells.resolution;
3116 let columns = cells.vs.len() - 1;
3117 let columns_u = cells.us.len() - 1;
3118 let mut bound = best.distance_squared.sqrt() - resolution;
3119
3120 let (mut candidates, excluded) = hull_candidates(cells, point, bound, node_boxes_enabled());
3123 stats.candidates = candidates.len();
3124 candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
3125 stats.hull_lower_bound = candidates
3126 .first()
3127 .map_or(excluded, |&(least, _)| least.min(excluded));
3128
3129 let cell_of = |u: f64, v: f64| {
3135 let row = (cells.us.partition_point(|&value| value <= u).max(1) - 1).min(columns_u - 1);
3136 let column = (cells.vs.partition_point(|&value| value <= v).max(1) - 1).min(columns - 1);
3137 row * columns + column
3138 };
3139 let mut settled: Vec<usize> = Vec::new();
3140 if is_verified_minimum(surface, point, (best.u, best.v), domains, periodic)? {
3141 settled.push(cell_of(best.u, best.v));
3142 }
3143 for (cell_bound, cell) in candidates {
3144 if cell_bound >= bound {
3145 break;
3146 }
3147 let row = cell / columns;
3148 let column = cell % columns;
3149 let rectangle = [
3150 cells.us[row],
3151 cells.us[row + 1],
3152 cells.vs[column],
3153 cells.vs[column + 1],
3154 ];
3155 if settled.contains(&cell) {
3156 continue;
3157 }
3158 if cells.split == [1, 1] {
3159 let mut seed = (rectangle[0], rectangle[2]);
3160 let mut seed_distance = f64::INFINITY;
3161 for (node_row, node_column) in
3162 [(row, column), (row + 1, column), (row, column + 1), (row + 1, column + 1)]
3163 {
3164 let distance = cells.nodes[node_row * cells.vs.len() + node_column]
3165 .sub(point)
3166 .length_squared();
3167 if distance < seed_distance {
3168 seed_distance = distance;
3169 seed = (cells.us[node_row], cells.vs[node_column]);
3170 }
3171 }
3172 if descend_cell(surface, point, seed, rectangle, domains, periodic, best, &mut bound, resolution, &mut settled, &cell_of, stats)? {
3173 return Ok(());
3174 }
3175 continue;
3176 }
3177 let [split_u, split_v] = cells.split;
3180 let at = |low: f64, high: f64, index: usize, count: usize| if index == count { high } else { low + (high - low) * index as f64 / count as f64 };
3181 for i in 0..split_u {
3182 for j in 0..split_v {
3183 let sub = [
3184 at(rectangle[0], rectangle[1], i, split_u),
3185 at(rectangle[0], rectangle[1], i + 1, split_u),
3186 at(rectangle[2], rectangle[3], j, split_v),
3187 at(rectangle[2], rectangle[3], j + 1, split_v),
3188 ];
3189 let index = (cell * split_u + i) * split_v + j;
3193 let cached = cells.sub_boxes.lock().ok().and_then(|boxes| boxes.get(&index).cloned());
3194 let hull = match cached {
3195 Some(hull) => hull,
3196 None => {
3197 let [su, sv] = cells.samples;
3198 let piece = |cell_index: usize, samples: usize, split: usize, sub: usize| {
3199 let (span, k) = (cell_index / samples, cell_index % samples);
3200 let steps = (samples * split) as f64;
3201 (span, [(k * split + sub) as f64 / steps, (k * split + sub + 1) as f64 / steps])
3202 };
3203 let (span_u, range_u) = piece(row, su, split_u, i);
3204 let (span_v, range_v) = piece(column, sv, split_v, j);
3205 let hull = crate::curve_clear::patch_piece_controls(surface, span_u, span_v, range_u, range_v)
3206 .and_then(|(controls, columns)| framed_box(&controls, columns, 64.0 * resolution));
3207 if let Ok(mut boxes) = cells.sub_boxes.lock() { boxes.insert(index, hull.clone()); }
3208 hull
3209 }
3210 };
3211 if let Some(hull) = hull {
3212 if hull.lower_bound(point) >= bound {
3213 continue;
3214 }
3215 }
3216 let mut seed = (sub[0], sub[2]);
3217 let mut seed_distance = f64::INFINITY;
3218 for (di, dj) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
3219 let (u, v) = (sub[di], sub[2 + dj]);
3220 let key = ((row * split_u + i + di) as u32, (column * split_v + j + dj) as u32);
3221 let cached = cells.sub_nodes.lock().ok().and_then(|nodes| nodes.get(&key).copied());
3222 let node = match cached {
3223 Some(node) => node,
3224 None => {
3225 let node = surface.evaluate(u, v)?;
3226 if let Ok(mut nodes) = cells.sub_nodes.lock() { nodes.insert(key, node); }
3227 node
3228 }
3229 };
3230 let distance = node.sub(point).length_squared();
3231 if distance < seed_distance {
3232 seed_distance = distance;
3233 seed = (u, v);
3234 }
3235 }
3236 if descend_cell(surface, point, seed, sub, domains, periodic, best, &mut bound, resolution, &mut settled, &cell_of, stats)? {
3237 return Ok(());
3238 }
3239 }
3240 }
3241 }
3242 Ok(())
3243}
3244
3245#[allow(clippy::too_many_arguments)]
3250fn descend_cell(
3251 surface: &NurbsSurface,
3252 point: Vec3,
3253 seed: (f64, f64),
3254 rectangle: [f64; 4],
3255 domains: [f64; 4],
3256 periodic: (bool, bool),
3257 best: &mut NewtonResult,
3258 bound: &mut f64,
3259 resolution: f64,
3260 settled: &mut Vec<usize>,
3261 cell_of: &dyn Fn(f64, f64) -> usize,
3262 stats: &mut GlobalStats,
3263) -> Result<bool, String> {
3264 stats.refinements += 1;
3265 let (confined, on_edge) = confined_descent(surface, point, seed, rectangle, (false, false))?;
3266 let mut found = confined;
3267 if on_edge && confined.distance_squared.sqrt() < *bound {
3268 stats.continuations += 1;
3271 let (continued, _) =
3272 confined_descent(surface, point, (confined.u, confined.v), domains, periodic)?;
3273 if continued.distance_squared < found.distance_squared {
3274 found = continued;
3275 }
3276 if continued.converged {
3277 settled.push(cell_of(continued.u, continued.v));
3278 }
3279 }
3280 if found.distance_squared.sqrt() < *bound {
3281 *best = found;
3282 *bound = best.distance_squared.sqrt() - resolution;
3283 stats.replaced = true;
3284 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
3285 return Ok(true);
3286 }
3287 }
3288 Ok(false)
3289}
3290
3291
3292
3293#[derive(Clone, Copy)]
3295pub enum FootDomain {
3296 Clamp,
3297 Wrap,
3298 Extended,
3299}
3300
3301#[derive(Clone, Copy)]
3302pub struct CurveFootPolicy {
3303 pub domain: FootDomain,
3304 pub iterations: usize,
3305 pub slope_guard: f64,
3306 pub step_limit: f64,
3307 pub parameter_tolerance: f64,
3308 pub mode: FootMode,
3309}
3310
3311#[derive(Clone, Copy)]
3313pub enum FootMode {
3314 Monotone,
3315 Witness,
3316 Stationary { positive_slope: bool, relative_step: bool },
3317 Backtracked,
3318 Planar,
3319}
3320
3321fn curve_foot_newton_state(
3324 curve: &NurbsCurve,
3325 point: Vec3,
3326 seed: f64,
3327 bracket: [f64; 2],
3328 policy: CurveFootPolicy,
3329) -> Result<(f64, f64, f64), String> {
3330 let fit = |u| match policy.domain {
3331 FootDomain::Clamp => fit_parameter(u, bracket[0], bracket[1], false),
3332 FootDomain::Wrap => fit_parameter(u, bracket[0], bracket[1], true),
3333 FootDomain::Extended => u,
3334 };
3335 let extended = matches!(policy.domain, FootDomain::Extended) || matches!(policy.mode, FootMode::Backtracked);
3336 let planar = matches!(policy.mode, FootMode::Planar);
3337 let project = |p: Vec3| if planar { Vec3::new(p.x, p.y, 0.0) } else { p };
3338 let point = project(point);
3339 let distance = |u| -> Result<f64, String> {
3340 let p = if extended { curve.derivatives_extended(u, 0)?[0] } else { curve.evaluate(u)? };
3341 Ok(project(p).sub(point).length())
3342 };
3343 let monotone = matches!(policy.mode, FootMode::Monotone | FootMode::Backtracked);
3344 let witness = matches!(policy.mode, FootMode::Witness);
3345 let mut u = if witness { seed } else { fit(seed) };
3346 let mut nearest_u = seed;
3347 let mut nearest_squared = f64::INFINITY;
3348 let mut best = if monotone { distance(u)? } else { f64::INFINITY };
3349 for _ in 0..policy.iterations {
3350 let derivatives = if extended {
3351 let values = curve.derivatives_extended(u, 2)?;
3352 [values[0], values[1], values[2]]
3353 } else if matches!(policy.mode, FootMode::Stationary { .. })
3354 || (planar && !crate::curve::small_curve_derivatives_enabled()) {
3355 let values = curve.derivatives(u, 2)?;
3356 [values[0], values[1], values[2]]
3357 } else {
3358 curve.derivatives_small(u, 2)?
3359 }.map(project);
3360 let offset = derivatives[0].sub(point);
3361 let numerator = offset.dot(derivatives[1]);
3362 let denominator = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
3363 if witness {
3364 let squared = offset.length_squared();
3365 if squared < nearest_squared {
3366 nearest_u = u;
3367 nearest_squared = squared;
3368 }
3369 let residual_length = squared.sqrt();
3370 if residual_length <= LINEAR_TOLERANCE
3371 || numerator.abs() <= EPSILON + 1e-10 * derivatives[1].length() * residual_length {
3372 break;
3373 }
3374 }
3375 let singular = if planar { denominator.abs() < policy.slope_guard }
3376 else { denominator.abs() <= policy.slope_guard };
3377 if singular || (matches!(policy.mode, FootMode::Stationary { positive_slope: true, .. }) && !(denominator > 0.0)) { break; }
3378 let mut step = if matches!(policy.mode, FootMode::Backtracked) && !(denominator > 0.0) {
3379 policy.step_limit.copysign(numerator)
3380 } else {
3381 (numerator / denominator).clamp(-policy.step_limit, policy.step_limit)
3382 };
3383 let mut next = fit(u - step);
3384 let mut next_distance = if monotone { distance(next)? } else { f64::INFINITY };
3385 if matches!(policy.mode, FootMode::Backtracked) {
3386 for _ in 0..30 {
3387 if next_distance < best { break; }
3388 step *= 0.5;
3389 next = fit(u - step);
3390 next_distance = distance(next)?;
3391 }
3392 if !(next_distance < best) { break; }
3393 } else if monotone && next_distance >= best { break; }
3394 let moved = if planar || matches!(policy.domain, FootDomain::Extended) { step }
3395 else if matches!(policy.domain, FootDomain::Wrap) {
3396 let period = bracket[1] - bracket[0];
3397 let raw = next - u;
3398 raw - period * (raw / period).round()
3399 } else { next - u };
3400 let tolerance = if matches!(policy.mode, FootMode::Stationary { relative_step: true, .. }) {
3401 policy.parameter_tolerance * (1.0 + u.abs())
3402 } else { policy.parameter_tolerance };
3403 let small = if planar || matches!(policy.mode, FootMode::Backtracked) { moved.abs() < tolerance }
3404 else { moved.abs() <= tolerance };
3405 if small && matches!(policy.mode, FootMode::Monotone) { break; }
3406 u = next;
3407 best = next_distance;
3408 if small { break; }
3409 }
3410 if witness { return Ok((u, nearest_u, nearest_squared)); }
3411 if !monotone { best = distance(u)?; }
3412 Ok((u, u, best * best))
3413}
3414
3415pub fn curve_foot_newton(
3416 curve: &NurbsCurve, point: Vec3, seed: f64, bracket: [f64; 2], policy: CurveFootPolicy,
3417) -> Result<(f64, f64), String> {
3418 let (_, nearest, squared) = curve_foot_newton_state(curve, point, seed, bracket, policy)?;
3419 Ok((nearest, squared))
3420}
3421
3422
3423
3424
3425