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 let mut order: Vec<(f64, usize)> = set
290 .blocks
291 .iter()
292 .enumerate()
293 .map(|(b, block)| {
294 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));
295 let cushion = 64.0 * f64::EPSILON * (point.length() + block.low.length() + block.high.length());
296 let reach = ((dx * dx + dy * dy + dz * dz).sqrt() * (1.0 - 1e-9) - cushion).max(0.0);
297 (reach * reach, b)
298 })
299 .collect();
300 order.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
301 let samples = &set.samples;
302 let (mut best, mut best_index) = (f64::INFINITY, usize::MAX);
303 let (mut witness, mut witness_index) = (f64::INFINITY, usize::MAX);
304 for (bound, b) in order {
305 if bound > best.max(witness) {
306 break;
307 }
308 let first = b * SEED_BLOCK;
309 let last = (first + SEED_BLOCK).min(samples.len());
310 for i in first..last {
311 let (_, sample) = samples[i];
312 let distance_squared = sample.sub(point).length_squared();
313 if distance_squared < best || (distance_squared == best && best_index != usize::MAX && i < best_index) {
314 best = distance_squared;
315 best_index = i;
316 }
317 if i > 0 {
318 let segment = point_segment_distance_squared(point, samples[i - 1].1, sample);
319 if segment < witness || (segment == witness && witness_index != usize::MAX && i < witness_index) {
320 witness = segment;
321 witness_index = i;
322 }
323 }
324 }
325 }
326 let mut scan = SeedScan { best_u: start, best_distance_squared: f64::INFINITY, witness_distance_squared: f64::INFINITY, witness_low: start, witness_high: start };
327 if best_index != usize::MAX {
328 scan.best_u = samples[best_index].0;
329 scan.best_distance_squared = best;
330 }
331 if witness_index != usize::MAX {
332 scan.witness_distance_squared = witness;
333 scan.witness_low = samples[witness_index - 1].0;
334 scan.witness_high = samples[witness_index].0;
335 }
336 scan
337}
338const CURVE_SEED_BUDGET: usize = 262_144;
339thread_local! {
340 static CURVE_SEEDS: std::cell::RefCell<(rustc_hash::FxHashMap<[u64; 2], CurveSeeds>, usize)> = Default::default();
341}
342
343pub fn clear_curve_seed_cache() {
350 CURVE_SEEDS.with(|memo| *memo.borrow_mut() = Default::default());
351}
352
353fn visit_curve_seeds(curve: &NurbsCurve, start: f64, end: f64, mut visit: impl FnMut(f64, Vec3)) -> Result<(), String> {
354 let mut breaks = vec![start];
355 breaks.extend(interior_knots(&curve.knots, curve.degree));
356 breaks.push(end);
357 let samples_per_span = 4usize.max(curve.degree + 2);
358 for pair in breaks.windows(2) {
359 for index in 0..=samples_per_span {
360 let parameter = pair[0] + (pair[1] - pair[0]) * index as f64 / samples_per_span as f64;
361 visit(parameter, curve.evaluate(parameter)?);
362 }
363 }
364 Ok(())
365}
366
367fn cached_curve_seeds(curve: &NurbsCurve, start: f64, end: f64) -> Result<Option<CurveSeeds>, String> {
372 if !switch!("BREP_CURVE_PROJECTION_SEEDS", true) { return Ok(None); }
373 let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
375 if bound > CURVE_SEED_BUDGET { return Ok(None); }
376 let mut key = crate::identity_hash::TwoLane::new();
377 crate::identity_hash::hash_curve(&mut key, curve);
378 key.f64(start); key.f64(end);
379 let key = key.finish();
380 if let Some(seeds) = CURVE_SEEDS.with(|memo| memo.borrow().0.get(&key).cloned()) {
381 return Ok(Some(seeds));
382 }
383 let mut seeds = Vec::new();
384 visit_curve_seeds(curve, start, end, |u, point| seeds.push((u, point)))?;
385 let seeds: CurveSeeds = std::rc::Rc::new(SeedSet::new(seeds));
386 CURVE_SEEDS.with(|memo| {
387 let mut memo = memo.borrow_mut();
388 if memo.0.len() >= PROJECTION_MEMO_ENTRIES || memo.1 + seeds.len() > CURVE_SEED_BUDGET {
389 memo.0.clear(); memo.1 = 0;
390 }
391 memo.1 += seeds.len();
392 memo.0.insert(key, seeds.clone());
393 });
394 Ok(Some(seeds))
395}
396
397fn project_point_to_curve_uncached(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
398 let [start, end] = curve.domain()?;
399 let seeds = cached_curve_seeds(curve, start, end)?;
400 project_point_to_curve_seeded(curve, point, seeds.as_deref())
401}
402
403#[derive(Clone)]
407pub(crate) struct HeldCurve {
408 pub(crate) curve: NurbsCurve,
409 seeds: Option<SeedSet>,
410}
411
412impl std::fmt::Debug for HeldCurve {
413 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
414 f.debug_struct("HeldCurve").field("curve", &self.curve).field("seeds", &self.seeds.as_ref().map(|s| s.samples.len())).finish()
415 }
416}
417
418impl HeldCurve {
419 pub(crate) fn new(curve: NurbsCurve) -> Self {
420 let seeds = curve.domain().ok().and_then(|[start, end]| {
421 let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
422 if bound > CURVE_SEED_BUDGET { return None; }
423 let mut samples = Vec::new();
424 visit_curve_seeds(&curve, start, end, |u, point| samples.push((u, point))).ok()?;
425 Some(SeedSet::new(samples))
426 });
427 Self { curve, seeds }
428 }
429
430 pub(crate) fn bare(curve: NurbsCurve) -> Self {
432 Self { curve, seeds: None }
433 }
434
435 pub(crate) fn project(&self, point: Vec3) -> Result<CurveProjection, String> {
438 match &self.seeds {
439 Some(seeds) if !(projection_memo_enabled() && straight_projection_key(&self.curve, point).is_some()) => {
440 project_point_to_curve_seeded(&self.curve, point, Some(seeds))
441 }
442 _ => project_point_to_curve(&self.curve, point),
443 }
444 }
445}
446
447fn project_point_to_curve_seeded(curve: &NurbsCurve, point: Vec3, seeds: Option<&SeedSet>) -> Result<CurveProjection, String> {
448 let [start, end] = curve.domain()?;
449 let mut best_u = start;
450 let mut best_distance_squared = f64::INFINITY;
451 let mut start_point = None;
456 let mut end_point = None;
457 let mut previous: Option<(f64, Vec3)> = None;
460 let mut witness_distance_squared = f64::INFINITY;
461 let mut witness_low = start;
462 let mut witness_high = start;
463 let mut visit = |parameter, sample: Vec3| {
464 if start_point.is_none() {
465 start_point = Some(sample);
466 }
467 end_point = Some(sample);
468 let distance_squared = sample.sub(point).length_squared();
469 if distance_squared < best_distance_squared {
470 best_distance_squared = distance_squared;
471 best_u = parameter;
472 }
473 if let Some((previous_parameter, previous_sample)) = previous {
474 let segment = point_segment_distance_squared(point, previous_sample, sample);
475 if segment < witness_distance_squared {
476 witness_distance_squared = segment;
477 witness_low = previous_parameter;
478 witness_high = parameter;
479 }
480 }
481 previous = Some((parameter, sample));
482 };
483 match seeds.filter(|set| !set.samples.is_empty() && (seed_blocks_enabled() || seed_blocks_check())) {
484 Some(set) => {
485 let scan = if seed_blocks_check() {
486 let linear = linear_seed_scan(&set.samples, point, start);
487 let blocked = blocked_seed_scan(set, point, start);
488 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);
489 if bits(&linear) != bits(&blocked) {
490 panic!("curve seed blocks check: blocked scan {blocked:?} differs from the linear scan {linear:?} at {point:?}");
491 }
492 linear
493 } else {
494 blocked_seed_scan(set, point, start)
495 };
496 best_u = scan.best_u;
497 best_distance_squared = scan.best_distance_squared;
498 witness_distance_squared = scan.witness_distance_squared;
499 witness_low = scan.witness_low;
500 witness_high = scan.witness_high;
501 start_point = Some(set.samples[0].1);
502 end_point = Some(set.samples[set.samples.len() - 1].1);
503 }
504 None => match seeds {
505 Some(seeds) => {
506 for &(parameter, sample) in seeds.iter() { visit(parameter, sample); }
507 }
508 None => visit_curve_seeds(curve, start, end, visit)?,
509 },
510 }
511 const CLOSED_SEAM_TOLERANCE: f64 = 1e-6;
524 let closed = match (start_point, end_point) {
525 (Some(first), Some(last)) => first.sub(last).length() <= CLOSED_SEAM_TOLERANCE,
526 _ => false,
527 };
528
529 let parameter = curve_newton(
530 curve,
531 point,
532 best_u,
533 start,
534 end,
535 closed,
536 &mut best_u,
537 &mut best_distance_squared,
538 )?;
539 for candidate in [start, end, parameter] {
540 let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
541 if distance_squared < best_distance_squared {
542 best_distance_squared = distance_squared;
543 best_u = candidate;
544 }
545 }
546 const WITNESS_FACTOR: f64 = 2.0;
578 if witness_distance_squared * (WITNESS_FACTOR * WITNESS_FACTOR) < best_distance_squared
579 && witness_rescue_enabled()
580 {
581 let bracketed = bracketed_nearest(curve, point, witness_low, witness_high)?;
582 let polished = curve_newton(
583 curve,
584 point,
585 bracketed,
586 start,
587 end,
588 closed,
589 &mut best_u,
590 &mut best_distance_squared,
591 )?;
592 for candidate in [bracketed, polished] {
593 let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
594 if distance_squared < best_distance_squared {
595 best_distance_squared = distance_squared;
596 best_u = candidate;
597 }
598 }
599 }
600 let projected = curve.evaluate(best_u)?;
601 Ok(CurveProjection {
602 u: best_u,
603 point: projected,
604 distance: projected.sub(point).length(),
605 })
606}
607
608fn project_linear_revolution(
609 surface: &NurbsSurface,
610 point: Vec3,
611) -> Result<Option<SurfaceProjection>, String> {
612 let rows = &surface.control_points;
613 if surface.degree_u != 2
614 || surface.degree_v != 1
615 || rows.len() < 5
616 || rows[0].len() != 2
617 || !surface.closed_directions()?.0
618 {
619 return Ok(None);
620 }
621 let base = rows[0][0].point()?.add(rows[4][0].point()?).scale(0.5);
622 let top = rows[0][1].point()?.add(rows[4][1].point()?).scale(0.5);
623 let axis_vector = top.sub(base);
624 let height = axis_vector.length();
625 if height <= EPSILON {
626 return Ok(None);
627 }
628 let axis = axis_vector.normalized()?;
629 let [v0, v1] = surface.domain_v()?;
630 let axial = point.sub(base).dot(axis).clamp(0.0, height);
631 let v = v0 + (v1 - v0) * axial / height;
632 let circle = surface.iso_curve_v(v)?;
633 let projection = project_point_to_curve(&circle, point)?;
634 let [u0, u1] = surface.domain_u()?;
635 let u = projection.u.clamp(u0, u1);
636 let projected = surface.evaluate(u, v)?;
637 Ok(Some(SurfaceProjection {
638 u,
639 v,
640 point: projected,
641 distance: projected.sub(point).length(),
642 }))
643}
644
645#[derive(Clone, Copy)]
646struct NewtonResult {
647 u: f64,
648 v: f64,
649 distance_squared: f64,
650 converged: bool,
651}
652
653fn surface_newton(
654 surface: &NurbsSurface,
655 point: Vec3,
656 seed_u: f64,
657 seed_v: f64,
658 domains: [f64; 4],
659 closed_u: bool,
660 closed_v: bool,
661) -> Result<NewtonResult, String> {
662 surface_newton_impl(surface, point, seed_u, seed_v, domains, closed_u, closed_v,
663 switch!("BREP_PROJECTION_LAZY_DERIVATIVES", false), LINEAR_TOLERANCE)
664}
665
666fn surface_newton_impl(
671 surface: &NurbsSurface,
672 point: Vec3,
673 seed_u: f64,
674 seed_v: f64,
675 domains: [f64; 4],
676 closed_u: bool,
677 closed_v: bool,
678 lazy: bool,
679 linear_tolerance: f64,
680) -> Result<NewtonResult, String> {
681 let [u0, u1, v0, v1] = domains;
682 let mut u = seed_u;
683 let mut v = seed_v;
684 let mut converged = false;
685 let mut best = NewtonResult {
686 u,
687 v,
688 distance_squared: surface.evaluate(u, v)?.sub(point).length_squared(),
689 converged,
690 };
691 let cycle_exit = switch!("BREP_PROJECTION_NEWTON_CYCLE_EXIT", true);
703 let mut trail = [(0u64, 0u64); MAX_NEWTON_ITERATIONS];
704 for iteration in 0..MAX_NEWTON_ITERATIONS {
705 if cycle_exit {
706 let state = (u.to_bits(), v.to_bits());
707 if let Some(first) = trail[..iteration].iter().position(|earlier| *earlier == state) {
708 let period = iteration - first;
709 let (last_u, last_v) = trail[first + (MAX_NEWTON_ITERATIONS - first) % period];
710 u = f64::from_bits(last_u);
711 v = f64::from_bits(last_v);
712 crate::work_counts::add(|c| c.newton_iterations += (MAX_NEWTON_ITERATIONS - iteration) as u64);
713 break;
714 }
715 trail[iteration] = state;
716 }
717 crate::work_counts::add(|c| c.newton_iterations += 1);
718 let derivatives = surface.derivatives_small(u, v, if lazy { 0 } else { 2 })?;
719 let residual = derivatives[0][0].sub(point);
720 let distance_squared = residual.length_squared();
721 if distance_squared < best.distance_squared {
722 best.u = u;
723 best.v = v;
724 best.distance_squared = distance_squared;
725 }
726 let residual_length = distance_squared.sqrt();
727 if residual_length <= linear_tolerance {
728 crate::work_counts::add(|c| { c.newton_unused += 1; c.newton_unused_first += u64::from(iteration == 0); });
729 converged = true;
730 break;
731 }
732 let derivatives = if lazy { surface.derivatives_small(u, v, 2)? } else { derivatives };
733 let f = derivatives[1][0].dot(residual);
734 let g = derivatives[0][1].dot(residual);
735 let tangent_u_length = derivatives[1][0].length();
736 let tangent_v_length = derivatives[0][1].length();
737 let cosine_u = if tangent_u_length * residual_length <= EPSILON {
738 0.0
739 } else {
740 f.abs() / (tangent_u_length * residual_length)
741 };
742 let cosine_v = if tangent_v_length * residual_length <= EPSILON {
743 0.0
744 } else {
745 g.abs() / (tangent_v_length * residual_length)
746 };
747 if cosine_u <= 1e-10 && cosine_v <= 1e-10 {
748 converged = true;
749 break;
750 }
751 let j00 = derivatives[2][0].dot(residual) + derivatives[1][0].length_squared();
752 let j01 = derivatives[1][1].dot(residual) + derivatives[1][0].dot(derivatives[0][1]);
753 let j11 = derivatives[0][2].dot(residual) + derivatives[0][1].length_squared();
754 let determinant = j00 * j11 - j01 * j01;
755 if determinant.abs() <= EPSILON {
756 break;
757 }
758 let mut du = (-f * j11 + g * j01) / determinant;
759 let mut dv = (-g * j00 + f * j01) / determinant;
760 du = du.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
761 dv = dv.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
762 let next_u = fit_parameter(u + du, u0, u1, closed_u);
763 let next_v = fit_parameter(v + dv, v0, v1, closed_v);
764 let stalled =
765 (next_u - u).abs() <= 1e-15 * (u1 - u0) && (next_v - v).abs() <= 1e-15 * (v1 - v0);
766 u = next_u;
767 v = next_v;
768 if stalled {
769 break;
770 }
771 }
772 let final_distance_squared = surface.evaluate(u, v)?.sub(point).length_squared();
773 if final_distance_squared < best.distance_squared {
774 best.u = u;
775 best.v = v;
776 best.distance_squared = final_distance_squared;
777 }
778 best.converged = converged;
779 Ok(best)
780}
781
782pub fn refine_trim_foot(
786 surface: &NurbsSurface, point: Vec3, foot: SurfaceProjection,
787) -> Result<SurfaceProjection, String> {
788 let [u0, u1] = surface.domain_u()?;
789 let [v0, v1] = surface.domain_v()?;
790 let (cu, cv) = surface.closed_directions()?;
791 let result = surface_newton_impl(surface, point, foot.u, foot.v,
792 [u0, u1, v0, v1], cu, cv, false, 1e-11)?;
793 let projected = surface.evaluate(result.u, result.v)?;
794 Ok(SurfaceProjection { u: result.u, v: result.v, point: projected,
795 distance: projected.sub(point).length() })
796}
797
798#[track_caller]
804pub fn project_point_to_surface(
805 surface: &NurbsSurface,
806 point: Vec3,
807) -> Result<SurfaceProjection, String> {
808 crate::work_counts::add(|c| c.projection_global += 1);
809 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_PROJECT, surface);
810 if let Some(analytic) = surface.analytic() {
814 if let Some(projection) = analytic.project(surface, point) {
815 return Ok(projection);
816 }
817 }
818 if let Some(ellipsoid) = surface.affine_sphere() {
819 if let Some(projection) = ellipsoid.project(surface, point) {
820 return Ok(projection);
821 }
822 }
823 if switch!("BREP_EXTRUSION_PROJECTION", true) {
824 if let Some(projection) = surface.linear_extrusion().and_then(|e| e.project(surface,point)) {
825 return Ok(projection);
826 }
827 }
828 project_point_to_surface_general(surface, point)
829}
830
831pub fn project_point_to_surface_seeded(
841 surface: &NurbsSurface,
842 point: Vec3,
843 seed_u: f64,
844 seed_v: f64,
845) -> Result<SurfaceProjection, String> {
846 crate::work_counts::add(|c| c.projection_seeded += 1);
847 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
848 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_SEEDED, surface);
849 if let Some(ellipsoid) = surface.affine_sphere() {
853 if let Some(projection) = ellipsoid.project(surface, point) {
854 return Ok(projection);
855 }
856 }
857 let [u0, u1] = surface.domain_u()?;
858 let [v0, v1] = surface.domain_v()?;
859 let (closed_u, closed_v) = surface.closed_directions()?;
860 let result = surface_newton(
861 surface,
862 point,
863 seed_u,
864 seed_v,
865 [u0, u1, v0, v1],
866 closed_u,
867 closed_v,
868 )?;
869 let projected = surface.evaluate(result.u, result.v)?;
870 Ok(SurfaceProjection {
871 u: result.u,
872 v: result.v,
873 point: projected,
874 distance: projected.sub(point).length(),
875 })
876}
877
878#[track_caller]
912pub fn project_point_to_surface_from_seed(
913 surface: &NurbsSurface,
914 point: Vec3,
915 seed: [f64; 2],
916) -> Result<SurfaceProjection, String> {
917 crate::work_counts::add(|c| c.projection_from_seed += 1);
918 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
919 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_SEED, surface);
920 if let Some(analytic) = surface.analytic() {
921 if let Some(projection) = analytic.project(surface, point) {
922 return Ok(projection);
923 }
924 }
925 if let Some(ellipsoid) = surface.affine_sphere() {
926 if let Some(projection) = ellipsoid.project(surface, point) {
927 return Ok(projection);
928 }
929 }
930 let caller = std::panic::Location::caller();
931 if !seeded_answer_admitted(caller) {
932 return project_point_to_surface_general(surface, point);
933 }
934 let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
935 if seed_audit_enabled() {
936 let nearest = project_point_to_surface_general(surface, point)?;
937 if seeded.point.sub(nearest.point).length() > LINEAR_TOLERANCE {
938 seed_audit_record(caller, surface, seed, &seeded, &nearest);
939 }
940 }
941 Ok(seeded)
942}
943
944fn seeded_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
947 static SITES: std::sync::OnceLock<Option<Option<Vec<String>>>> = std::sync::OnceLock::new();
948 let sites = SITES.get_or_init(|| {
949 if std::env::var("BREP_PROJECTION_FROM_SEED").as_deref() == Ok("0") {
950 return None;
951 }
952 Some(std::env::var("BREP_PROJECTION_FROM_SEED_SITES").ok().map(|value| {
953 value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect()
954 }))
955 });
956 match sites {
957 None => false,
958 Some(None) => true,
959 Some(Some(only)) => {
960 let location = format!("{}:{}", caller.file(), caller.line());
961 only.iter().any(|site| location.contains(site.as_str()))
962 }
963 }
964}
965
966fn seed_audit_enabled() -> bool {
967 debug_flag!("BREP_PROJECTION_AUDIT")
968}
969
970fn seed_audit_record(
974 caller: &std::panic::Location<'_>,
975 surface: &NurbsSurface,
976 seed: [f64; 2],
977 seeded: &SurfaceProjection,
978 nearest: &SurfaceProjection,
979) {
980 use std::io::Write;
981 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
982 std::sync::OnceLock::new();
983 let sink = SINK.get_or_init(|| {
984 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
985 let path = std::path::Path::new(&directory)
986 .join(format!("projection-seed-audit-{}.tsv", std::process::id()));
987 std::fs::OpenOptions::new()
988 .create(true)
989 .append(true)
990 .open(path)
991 .ok()
992 .map(std::sync::Mutex::new)
993 });
994 if let Some(file) = sink {
995 if let Ok(mut file) = file.lock() {
996 let _ = writeln!(
997 file,
998 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.6e}\t{}x{} cp {}x{}",
999 caller.file(),
1000 caller.line(),
1001 seeded.distance,
1002 nearest.distance,
1003 seed[0],
1004 seed[1],
1005 seeded.u,
1006 seeded.v,
1007 nearest.u,
1008 nearest.v,
1009 seeded.point.sub(nearest.point).length(),
1010 surface.degree_u,
1011 surface.degree_v,
1012 surface.control_points.len(),
1013 surface.control_points.first().map(Vec::len).unwrap_or(0),
1014 );
1015 }
1016 }
1017}
1018
1019fn projection_seed_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
1024 if let Some(grid) = surface.projection_grid.get() {
1025 return Ok(grid);
1026 }
1027 let [u0, u1] = surface.domain_u()?;
1028 let [v0, v1] = surface.domain_v()?;
1029 let (closed_u, closed_v) = surface.closed_directions()?;
1030 let mut breaks_u = vec![u0];
1031 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
1032 breaks_u.push(u1);
1033 let mut breaks_v = vec![v0];
1034 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
1035 breaks_v.push(v1);
1036 let samples_u = if closed_u {
1037 8usize.max(surface.degree_u * 4)
1038 } else {
1039 3usize.max(surface.degree_u + 1)
1040 };
1041 let samples_v = if closed_v {
1042 8usize.max(surface.degree_v * 4)
1043 } else {
1044 3usize.max(surface.degree_v + 1)
1045 };
1046 let mut grid = Vec::new();
1047 for u_pair in breaks_u.windows(2) {
1048 for v_pair in breaks_v.windows(2) {
1049 for i in 0..=samples_u {
1050 for j in 0..=samples_v {
1051 let u = u_pair[0] + (u_pair[1] - u_pair[0]) * i as f64 / samples_u as f64;
1052 let v = v_pair[0] + (v_pair[1] - v_pair[0]) * j as f64 / samples_v as f64;
1053 grid.push((u, v, surface.evaluate(u, v)?));
1054 }
1055 }
1056 }
1057 }
1058 Ok(surface.projection_grid.get_or_init(|| SampleGrid::new(grid)))
1059}
1060
1061fn projection_dense_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
1068 if let Some(grid) = surface.projection_dense_grid.get() {
1069 return Ok(grid);
1070 }
1071 let [u0, u1] = surface.domain_u()?;
1072 let [v0, v1] = surface.domain_v()?;
1073 let mut breaks_u = vec![u0];
1074 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
1075 breaks_u.push(u1);
1076 let mut breaks_v = vec![v0];
1077 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
1078 breaks_v.push(v1);
1079 let count_u = 32usize.max((breaks_u.len() - 1) * 8);
1080 let count_v = 16usize.max((breaks_v.len() - 1) * 8);
1081 let mut grid = Vec::with_capacity((count_u + 1) * (count_v + 1));
1082 for i in 0..=count_u {
1083 for j in 0..=count_v {
1084 let u = u0 + (u1 - u0) * i as f64 / count_u as f64;
1085 let v = v0 + (v1 - v0) * j as f64 / count_v as f64;
1086 grid.push((u, v, surface.evaluate(u, v)?));
1087 }
1088 }
1089 Ok(surface.projection_dense_grid.get_or_init(|| SampleGrid::with_tree(grid)))
1090}
1091
1092const SAMPLE_BLOCK: usize = 32;
1094
1095const GROUP_BLOCKS: usize = 32;
1098
1099#[derive(Clone, Debug)]
1104pub struct SampleGrid {
1105 samples: Vec<(f64, f64, Vec3)>,
1106 blocks: Vec<SampleBlock>,
1107 groups: Vec<SampleBlock>,
1112 tree: Vec<Vec<SampleBlock>>,
1118}
1119
1120const TREE_FANOUT: usize = 4;
1122
1123fn union_boxes(boxes: &[SampleBlock]) -> Vec<SampleBlock> {
1125 boxes
1126 .chunks(TREE_FANOUT)
1127 .map(|chunk| {
1128 let mut union = chunk[0];
1129 for block in chunk {
1130 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));
1131 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));
1132 union.prunable &= block.prunable;
1133 }
1134 union
1135 })
1136 .collect()
1137}
1138
1139#[derive(Clone, Copy, Debug)]
1142struct SampleBlock {
1143 low: Vec3,
1144 high: Vec3,
1145 prunable: bool,
1146}
1147
1148impl SampleGrid {
1149 fn new(samples: Vec<(f64, f64, Vec3)>) -> Self {
1150 let blocks = samples
1151 .chunks(SAMPLE_BLOCK)
1152 .map(|chunk| {
1153 let mut low = chunk[0].2;
1154 let mut high = low;
1155 let mut prunable = true;
1156 for &(_, _, p) in chunk {
1157 prunable &= p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
1158 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
1159 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
1160 }
1161 SampleBlock { low, high, prunable }
1162 })
1163 .collect::<Vec<_>>();
1164 let groups = blocks
1165 .chunks(GROUP_BLOCKS)
1166 .map(|chunk| {
1167 let mut group = chunk[0];
1168 for block in chunk {
1169 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));
1170 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));
1171 group.prunable &= block.prunable;
1172 }
1173 group
1174 })
1175 .collect();
1176 Self { samples, blocks, groups, tree: Vec::new() }
1177 }
1178
1179 fn with_tree(samples: Vec<(f64, f64, Vec3)>) -> Self {
1186 let mut grid = Self::new(samples);
1187 if grid.blocks.len() > GROUP_BLOCKS {
1188 grid.tree.push(union_boxes(&grid.blocks));
1189 while grid.tree.last().is_some_and(|level| level.len() > 1) {
1190 let next = union_boxes(grid.tree.last().unwrap());
1191 grid.tree.push(next);
1192 }
1193 }
1194 grid
1195 }
1196}
1197
1198impl SampleBlock {
1199 fn lower_bound(&self, point: Vec3) -> f64 {
1207 let gap = |p: f64, low: f64, high: f64| {
1208 if p < low {
1209 low - p
1210 } else if p > high {
1211 p - high
1212 } else {
1213 0.0
1214 }
1215 };
1216 let x = gap(point.x, self.low.x, self.high.x);
1217 let y = gap(point.y, self.low.y, self.high.y);
1218 let z = gap(point.z, self.low.z, self.high.z);
1219 x * x + y * y + z * z
1220 }
1221}
1222
1223fn pruned_scan() -> bool {
1226 switch!("BREP_PROJECTION_PRUNED_SCAN", true)
1227}
1228
1229fn nearest_sample(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1239 if !grid.tree.is_empty() && scan_tree() && pruned_scan() && bound_first_scan() {
1240 nearest_sample_tree(grid, point, best);
1241 return;
1242 }
1243 nearest_sample_with(grid, point, best, pruned_scan(), bound_first_scan());
1244}
1245
1246fn scan_tree() -> bool {
1258 switch!("BREP_PROJECTION_SCAN_TREE", true)
1259}
1260
1261fn scan_hint() -> bool {
1271 switch!("BREP_PROJECTION_SCAN_HINT", true)
1272}
1273
1274const HINT_SLOTS: usize = 8;
1275
1276thread_local! {
1277 static SCAN_HINTS: std::cell::Cell<[(usize, usize); HINT_SLOTS]> =
1279 const { std::cell::Cell::new([(0, usize::MAX); HINT_SLOTS]) };
1280}
1281
1282fn hint_slot(grid: &SampleGrid) -> (usize, usize) {
1283 let address = grid.samples.as_ptr() as usize;
1284 (address, (address >> 4) % HINT_SLOTS)
1285}
1286
1287fn hinted_bound(grid: &SampleGrid, point: Vec3, mut bound: f64) -> f64 {
1294 if !scan_hint() {
1295 return bound;
1296 }
1297 let (address, slot) = hint_slot(grid);
1298 let (held, run) = SCAN_HINTS.with(|hints| hints.get()[slot]);
1299 if held != address || run >= grid.blocks.len() || !grid.blocks[run].prunable {
1300 return bound;
1301 }
1302 let start = run * SAMPLE_BLOCK;
1303 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1304 for &(_, _, sample) in &grid.samples[start..end] {
1305 let distance_squared = sample.sub(point).length_squared();
1306 if distance_squared < bound {
1307 bound = distance_squared;
1308 }
1309 }
1310 bound
1311}
1312
1313fn remember_hint(grid: &SampleGrid, run: Option<usize>) {
1315 if let Some(run) = run.filter(|_| scan_hint()) {
1316 let (address, slot) = hint_slot(grid);
1317 SCAN_HINTS.with(|hints| {
1318 let mut all = hints.get();
1319 all[slot] = (address, run);
1320 hints.set(all);
1321 });
1322 }
1323}
1324
1325fn nearest_sample_tree(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1336 let top = grid.tree.len() - 1;
1337 let mut bound = best.distance_squared;
1338 let mut node = 0usize;
1340 let mut reached = true;
1341 for level in (0..=top).rev() {
1342 let children = |count: usize| node * TREE_FANOUT..((node + 1) * TREE_FANOUT).min(count);
1343 let below = if level == 0 { &grid.blocks } else { &grid.tree[level - 1] };
1344 match lowest_floor(below, children(below.len()), point) {
1345 Some(child) => node = child,
1346 None => {
1347 reached = false;
1348 break;
1349 }
1350 }
1351 }
1352 if reached {
1353 let start = node * SAMPLE_BLOCK;
1354 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1355 for &(_, _, sample) in &grid.samples[start..end] {
1356 let distance_squared = sample.sub(point).length_squared();
1357 if distance_squared < bound {
1358 bound = distance_squared;
1359 }
1360 }
1361 }
1362 let bound = hinted_bound(grid, point, bound);
1363 let skip = |box_: &SampleBlock, held: f64| {
1364 if !box_.prunable {
1365 return false;
1366 }
1367 let floor = box_.lower_bound(point);
1368 floor >= held || floor > bound
1369 };
1370 let mut answer_run = None;
1371 let mut stack: Vec<(usize, usize)> = Vec::with_capacity(TREE_FANOUT * (top + 2));
1373 stack.push((top + 1, 0));
1374 while let Some((level, index)) = stack.pop() {
1375 if level == 0 {
1376 if skip(&grid.blocks[index], best.distance_squared) {
1377 continue;
1378 }
1379 let start = index * SAMPLE_BLOCK;
1380 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1381 let held = best.distance_squared;
1382 scan_run(&grid.samples[start..end], point, best);
1383 if best.distance_squared < held {
1384 answer_run = Some(index);
1385 }
1386 continue;
1387 }
1388 if skip(&grid.tree[level - 1][index], best.distance_squared) {
1389 continue;
1390 }
1391 let count = if level == 1 { grid.blocks.len() } else { grid.tree[level - 2].len() };
1392 let children = index * TREE_FANOUT..((index + 1) * TREE_FANOUT).min(count);
1393 for child in children.rev() {
1395 stack.push((level - 1, child));
1396 }
1397 }
1398 remember_hint(grid, answer_run);
1399}
1400
1401fn bound_first_scan() -> bool {
1417 switch!("BREP_PROJECTION_BOUND_FIRST", true)
1418}
1419
1420fn nearest_sample_with(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult, pruned: bool, bound_first: bool) {
1430 if !(pruned && bound_first) {
1431 for (block, chunk) in grid.blocks.iter().zip(grid.samples.chunks(SAMPLE_BLOCK)) {
1432 if pruned && block.prunable && block.lower_bound(point) >= best.distance_squared {
1433 continue;
1434 }
1435 scan_run(chunk, point, best);
1436 }
1437 return;
1438 }
1439 let mut bound = best.distance_squared;
1442 let lowest_group = lowest_floor(&grid.groups, 0..grid.groups.len(), point);
1443 if let Some(group) = lowest_group {
1444 let runs = group * GROUP_BLOCKS..((group + 1) * GROUP_BLOCKS).min(grid.blocks.len());
1445 if let Some(run) = lowest_floor(&grid.blocks, runs, point) {
1446 let start = run * SAMPLE_BLOCK;
1447 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1448 for &(_, _, sample) in &grid.samples[start..end] {
1449 let distance_squared = sample.sub(point).length_squared();
1450 if distance_squared < bound {
1451 bound = distance_squared;
1452 }
1453 }
1454 }
1455 }
1456 let bound = hinted_bound(grid, point, bound);
1457 let skip = |box_: &SampleBlock, held: f64| {
1458 if !box_.prunable {
1459 return false;
1460 }
1461 let floor = box_.lower_bound(point);
1462 floor >= held || floor > bound
1463 };
1464 let mut answer_run = None;
1465 for (group_index, group) in grid.groups.iter().enumerate() {
1466 if skip(group, best.distance_squared) {
1467 continue;
1468 }
1469 let first = group_index * GROUP_BLOCKS;
1470 let last = (first + GROUP_BLOCKS).min(grid.blocks.len());
1471 for run in first..last {
1472 if skip(&grid.blocks[run], best.distance_squared) {
1473 continue;
1474 }
1475 let start = run * SAMPLE_BLOCK;
1476 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1477 let held = best.distance_squared;
1478 scan_run(&grid.samples[start..end], point, best);
1479 if best.distance_squared < held {
1480 answer_run = Some(run);
1481 }
1482 }
1483 }
1484 remember_hint(grid, answer_run);
1485}
1486
1487fn scan_run(run: &[(f64, f64, Vec3)], point: Vec3, best: &mut NewtonResult) {
1490 for &(u, v, sample) in run {
1491 let distance_squared = sample.sub(point).length_squared();
1492 if distance_squared < best.distance_squared {
1493 best.u = u;
1494 best.v = v;
1495 best.distance_squared = distance_squared;
1496 }
1497 }
1498}
1499
1500fn lowest_floor(boxes: &[SampleBlock], range: std::ops::Range<usize>, point: Vec3) -> Option<usize> {
1503 let mut lowest: Option<(usize, f64)> = None;
1504 for index in range {
1505 let box_ = &boxes[index];
1506 if !box_.prunable {
1507 continue;
1508 }
1509 let floor = box_.lower_bound(point);
1510 if lowest.is_none_or(|(_, held)| floor < held) {
1511 lowest = Some((index, floor));
1512 }
1513 }
1514 lowest.map(|(index, _)| index)
1515}
1516
1517const RING_EXPONENTS: usize = 22;
1521const RING_INDICES: usize = 33; #[inline]
1524fn ring_slot(side: usize, exponent_index: usize, index: usize) -> usize {
1525 (side * RING_EXPONENTS + exponent_index) * RING_INDICES + index
1526}
1527
1528fn projection_ring_grid(surface: &NurbsSurface) -> Result<&[Vec3], String> {
1535 if let Some(grid) = surface.projection_ring_grid.get() {
1536 return Ok(grid);
1537 }
1538 let [u0, u1] = surface.domain_u()?;
1539 let [v0, v1] = surface.domain_v()?;
1540 let mut grid = vec![Vec3::default(); 4 * RING_EXPONENTS * RING_INDICES];
1541 for exponent in 1..=RING_EXPONENTS as i32 {
1542 let offset = 1.0 / 2f64.powi(exponent);
1543 let e = exponent as usize - 1;
1544 let v_lo = v0 + (v1 - v0) * offset;
1545 let v_hi = v1 - (v1 - v0) * offset;
1546 let u_lo = u0 + (u1 - u0) * offset;
1547 let u_hi = u1 - (u1 - u0) * offset;
1548 for index in 0..=32 {
1549 let u = u0 + (u1 - u0) * index as f64 / 32.0;
1550 grid[ring_slot(0, e, index as usize)] = surface.evaluate(u, v_lo)?;
1551 grid[ring_slot(1, e, index as usize)] = surface.evaluate(u, v_hi)?;
1552 }
1553 for index in 0..=32 {
1554 let v = v0 + (v1 - v0) * index as f64 / 32.0;
1555 grid[ring_slot(2, e, index as usize)] = surface.evaluate(u_lo, v)?;
1556 grid[ring_slot(3, e, index as usize)] = surface.evaluate(u_hi, v)?;
1557 }
1558 }
1559 Ok(surface.projection_ring_grid.get_or_init(|| grid))
1560}
1561
1562fn nearest_seed_answer(
1572 surface: &NurbsSurface,
1573 point: Vec3,
1574 [u0, u1, v0, v1]: [f64; 4],
1575 closed_u: bool,
1576 closed_v: bool,
1577) -> Result<NewtonResult, String> {
1578 let mut best = NewtonResult {
1579 u: u0,
1580 v: v0,
1581 distance_squared: f64::INFINITY,
1582 converged: false,
1583 };
1584 nearest_sample(projection_seed_grid(surface)?, point, &mut best);
1585 if let Some(revolution) = project_linear_revolution(surface, point)? {
1586 if revolution.distance * revolution.distance < best.distance_squared {
1587 best.u = revolution.u;
1588 best.v = revolution.v;
1589 best.distance_squared = revolution.distance * revolution.distance;
1590 }
1591 }
1592 let first_newton = surface_newton(
1593 surface,
1594 point,
1595 best.u,
1596 best.v,
1597 [u0, u1, v0, v1],
1598 closed_u,
1599 closed_v,
1600 )?;
1601 if first_newton.distance_squared < best.distance_squared {
1602 best = first_newton;
1603 }
1604 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1605 let degenerate = su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length());
1606 if degenerate || !first_newton.converged {
1607 let mut grid = best;
1608 nearest_sample(projection_dense_grid(surface)?, point, &mut grid);
1609 if grid.distance_squared < best.distance_squared {
1610 best = grid;
1611 }
1612 let polished = surface_newton(
1613 surface,
1614 point,
1615 grid.u,
1616 grid.v,
1617 [u0, u1, v0, v1],
1618 closed_u,
1619 closed_v,
1620 )?;
1621 if polished.distance_squared < best.distance_squared {
1622 best = polished;
1623 }
1624
1625 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1626 if su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length()) {
1627 let ring_grid = projection_ring_grid(surface)?;
1628 let mut ring = best;
1629 let scan = |side: usize,
1633 exponent_index: usize,
1634 along_u: bool,
1635 fixed: f64,
1636 candidate: &mut NewtonResult| {
1637 for index in 0..=32 {
1638 let moving = if along_u {
1639 u0 + (u1 - u0) * index as f64 / 32.0
1640 } else {
1641 v0 + (v1 - v0) * index as f64 / 32.0
1642 };
1643 let (u, v) = if along_u {
1644 (moving, fixed)
1645 } else {
1646 (fixed, moving)
1647 };
1648 let distance_squared = ring_grid
1649 [ring_slot(side, exponent_index, index as usize)]
1650 .sub(point)
1651 .length_squared();
1652 if distance_squared < candidate.distance_squared {
1653 candidate.u = u;
1654 candidate.v = v;
1655 candidate.distance_squared = distance_squared;
1656 }
1657 }
1658 };
1659 for exponent in 1..=22 {
1660 let offset = 1.0 / 2f64.powi(exponent);
1661 let e = exponent as usize - 1;
1662 if (best.v - v0).abs() <= (v1 - v0) * 0.02 {
1663 scan(0, e, true, v0 + (v1 - v0) * offset, &mut ring);
1664 }
1665 if (best.v - v1).abs() <= (v1 - v0) * 0.02 {
1666 scan(1, e, true, v1 - (v1 - v0) * offset, &mut ring);
1667 }
1668 if (best.u - u0).abs() <= (u1 - u0) * 0.02 {
1669 scan(2, e, false, u0 + (u1 - u0) * offset, &mut ring);
1670 }
1671 if (best.u - u1).abs() <= (u1 - u0) * 0.02 {
1672 scan(3, e, false, u1 - (u1 - u0) * offset, &mut ring);
1673 }
1674 }
1675 if ring.distance_squared < best.distance_squared {
1676 best = ring;
1677 }
1678 let polished = surface_newton(
1679 surface,
1680 point,
1681 ring.u,
1682 ring.v,
1683 [u0, u1, v0, v1],
1684 closed_u,
1685 closed_v,
1686 )?;
1687 if polished.distance_squared < best.distance_squared {
1688 best = polished;
1689 }
1690 }
1691 }
1692 Ok(best)
1693}
1694
1695fn global_stage_enabled() -> bool {
1700 switch!("BREP_PROJECTION_GLOBAL", true)
1701}
1702
1703pub fn global_site_filter_active() -> bool {
1712 static ACTIVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1717 *ACTIVE.get_or_init(|| {
1718 std::env::var_os("BREP_PROJECTION_GLOBAL_SITES").is_some() || std::env::var_os("BREP_PROJECTION_GLOBAL_EXCEPT").is_some()
1719 })
1720}
1721
1722fn global_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
1723 fn list(name: &str) -> Option<Vec<String>> {
1724 std::env::var(name)
1725 .ok()
1726 .map(|value| value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect())
1727 }
1728 static SITES: std::sync::OnceLock<(Option<Vec<String>>, Option<Vec<String>>)> =
1729 std::sync::OnceLock::new();
1730 let (only, except) = SITES.get_or_init(|| {
1731 (list("BREP_PROJECTION_GLOBAL_SITES"), list("BREP_PROJECTION_GLOBAL_EXCEPT"))
1732 });
1733 if only.is_none() && except.is_none() {
1734 return true;
1735 }
1736 let location = format!("{}:{}", caller.file(), caller.line());
1737 let named = |sites: &Vec<String>| sites.iter().any(|site| location.contains(site.as_str()));
1738 only.as_ref().is_none_or(named) && !except.as_ref().is_some_and(named)
1739}
1740
1741fn audit_record(caller: &std::panic::Location<'_>, surface: &NurbsSurface, local: &NewtonResult, global: &NewtonResult) {
1747 use std::io::Write;
1748 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1749 std::sync::OnceLock::new();
1750 let sink = SINK.get_or_init(|| {
1751 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1752 let path = std::path::Path::new(&directory)
1753 .join(format!("projection-audit-{}.tsv", std::process::id()));
1754 std::fs::OpenOptions::new()
1755 .create(true)
1756 .append(true)
1757 .open(path)
1758 .ok()
1759 .map(std::sync::Mutex::new)
1760 });
1761 if let Some(file) = sink {
1762 if let Ok(mut file) = file.lock() {
1763 let _ = writeln!(
1764 file,
1765 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{}x{} cp {}x{}",
1766 caller.file(),
1767 caller.line(),
1768 local.distance_squared.sqrt(),
1769 global.distance_squared.sqrt(),
1770 local.u,
1771 local.v,
1772 global.u,
1773 global.v,
1774 surface.degree_u,
1775 surface.degree_v,
1776 surface.control_points.len(),
1777 surface.control_points.first().map(Vec::len).unwrap_or(0),
1778 );
1779 }
1780 }
1781}
1782
1783#[track_caller]
1859pub fn project_point_to_surface_general(
1860 surface: &NurbsSurface,
1861 point: Vec3,
1862) -> Result<SurfaceProjection, String> {
1863 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_GENERAL, surface);
1864 let [u0, u1] = surface.domain_u()?;
1865 let [v0, v1] = surface.domain_v()?;
1866 let (closed_u, closed_v) = surface.closed_directions()?;
1867 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1868 let mut best = local;
1869 if global_stage_enabled() {
1870 global_minimum(
1871 surface,
1872 point,
1873 [u0, u1, v0, v1],
1874 (closed_u, closed_v),
1875 &mut best,
1876 &mut GlobalStats::default(),
1877 )?;
1878 if best.u != local.u || best.v != local.v {
1879 let caller = std::panic::Location::caller();
1880 if global_answer_admitted(caller) {
1881 audit_record(caller, surface, &local, &best);
1882 } else {
1883 best = local;
1884 }
1885 }
1886 }
1887 let projected = surface.evaluate(best.u, best.v)?;
1888 Ok(SurfaceProjection {
1889 u: best.u,
1890 v: best.v,
1891 point: projected,
1892 distance: projected.sub(point).length(),
1893 })
1894}
1895
1896pub fn project_point_to_surface_from_nearest_seed(
1906 surface: &NurbsSurface,
1907 point: Vec3,
1908) -> Result<SurfaceProjection, String> {
1909 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_NEAREST_SEED, surface);
1910 if let Some(analytic) = surface.analytic() {
1911 if let Some(projection) = analytic.project(surface, point) {
1912 return Ok(projection);
1913 }
1914 }
1915 if let Some(ellipsoid) = surface.affine_sphere() {
1916 if let Some(projection) = ellipsoid.project(surface, point) {
1917 return Ok(projection);
1918 }
1919 }
1920 let [u0, u1] = surface.domain_u()?;
1921 let [v0, v1] = surface.domain_v()?;
1922 let (closed_u, closed_v) = surface.closed_directions()?;
1923 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1924 let projected = surface.evaluate(local.u, local.v)?;
1925 Ok(SurfaceProjection {
1926 u: local.u,
1927 v: local.v,
1928 point: projected,
1929 distance: projected.sub(point).length(),
1930 })
1931}
1932
1933#[doc(hidden)]
1936pub fn project_point_to_surface_general_lanes(
1937 surface: &NurbsSurface,
1938 point: Vec3,
1939 run_global: bool,
1940) -> Result<(SurfaceProjection, GlobalStats), String> {
1941 let [u0, u1] = surface.domain_u()?;
1942 let [v0, v1] = surface.domain_v()?;
1943 let (closed_u, closed_v) = surface.closed_directions()?;
1944 let mut best = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1945 let mut stats = GlobalStats::default();
1946 if run_global {
1947 global_minimum(surface, point, [u0, u1, v0, v1], (closed_u, closed_v), &mut best, &mut stats)?;
1948 }
1949 let projected = surface.evaluate(best.u, best.v)?;
1950 Ok((
1951 SurfaceProjection {
1952 u: best.u,
1953 v: best.v,
1954 point: projected,
1955 distance: projected.sub(point).length(),
1956 },
1957 stats,
1958 ))
1959}
1960
1961#[doc(hidden)]
1964#[derive(Clone, Debug, Default)]
1965pub struct BasinCensus {
1966 pub cells: usize,
1969 pub descents: usize,
1971 pub unconverged: usize,
1973 pub cells_with_two_basins: usize,
1977 pub foot_cells_with_two_basins: usize,
1980 pub least: f64,
1982 pub least_uv: (f64, f64),
1983 pub foot_cell_descents: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)>,
1987}
1988
1989#[doc(hidden)]
1994pub fn project_point_to_surface_basin_census(
1995 surface: &NurbsSurface,
1996 point: Vec3,
1997 answer_distance: f64,
1998 bar: f64,
1999) -> Result<BasinCensus, String> {
2000 let mut census = BasinCensus {
2001 least: f64::INFINITY,
2002 ..BasinCensus::default()
2003 };
2004 let Some(cells) = projection_cells(surface)? else {
2005 return Ok(census);
2006 };
2007 let columns = cells.vs.len() - 1;
2008 let mut spreads: Vec<(usize, f64)> = Vec::new();
2009 let mut runs: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)> = Vec::new();
2010 for (cell, cell_box) in cells.boxes.iter().enumerate() {
2011 if cell_box.lower_bound(point) >= answer_distance {
2012 continue;
2013 }
2014 census.cells += 1;
2015 let (row, column) = (cell / columns, cell % columns);
2016 let rectangle = [cells.us[row], cells.us[row + 1], cells.vs[column], cells.vs[column + 1]];
2017 let middle = ((rectangle[0] + rectangle[1]) * 0.5, (rectangle[2] + rectangle[3]) * 0.5);
2018 let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
2019 for seed in [
2020 (rectangle[0], rectangle[2]),
2021 (rectangle[1], rectangle[2]),
2022 (rectangle[0], rectangle[3]),
2023 (rectangle[1], rectangle[3]),
2024 middle,
2025 ] {
2026 census.descents += 1;
2027 let (found, _) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2028 let distance = found.distance_squared.sqrt();
2029 runs.push((cell, rectangle, seed, (found.u, found.v), distance, found.converged));
2030 if distance < census.least {
2031 census.least = distance;
2032 census.least_uv = (found.u, found.v);
2033 }
2034 if !found.converged {
2035 census.unconverged += 1;
2036 continue;
2037 }
2038 low = low.min(distance.max(LINEAR_TOLERANCE));
2039 high = high.max(distance.max(LINEAR_TOLERANCE));
2040 }
2041 if high - low > bar {
2042 spreads.push((cell, high - low));
2043 }
2044 }
2045 census.cells_with_two_basins = spreads.len();
2046 let (u, v) = census.least_uv;
2047 let foot_cells: Vec<usize> = spreads
2048 .iter()
2049 .map(|&(cell, _)| cell)
2050 .filter(|&cell| {
2051 let (row, column) = (cell / columns, cell % columns);
2052 cells.us[row] <= u && u <= cells.us[row + 1] && cells.vs[column] <= v && v <= cells.vs[column + 1]
2053 })
2054 .collect();
2055 census.foot_cells_with_two_basins = foot_cells.len();
2056 census.foot_cell_descents = runs.into_iter().filter(|run| foot_cells.contains(&run.0)).collect();
2057 Ok(census)
2058}
2059
2060#[doc(hidden)]
2062#[derive(Clone, Copy, Debug, Default)]
2063pub struct GlobalStats {
2064 pub settled_by_floor: bool,
2066 pub candidates: usize,
2068 pub refinements: usize,
2070 pub continuations: usize,
2072 pub replaced: bool,
2074 pub hull_lower_bound: f64,
2077}
2078
2079#[derive(Clone, Debug)]
2082struct CellBox {
2083 axes: [Vec3; 3],
2084 low: [f64; 3],
2085 high: [f64; 3],
2086}
2087
2088impl CellBox {
2089 fn lower_bound(&self, point: Vec3) -> f64 {
2092 let mut squared = 0.0;
2093 for axis in 0..3 {
2094 let coordinate = point.dot(self.axes[axis]);
2095 let excess = (self.low[axis] - coordinate).max(coordinate - self.high[axis]).max(0.0);
2096 squared += excess * excess;
2097 }
2098 squared.sqrt()
2099 }
2100}
2101
2102#[derive(Clone, Copy, Debug)]
2105struct CellTreeNode {
2106 centre: Vec3,
2107 radius: f64,
2108 children: Option<(u32, u32)>,
2109 cell: u32,
2110}
2111
2112#[derive(Clone, Debug)]
2115pub struct ProjectionCells {
2116 us: Vec<f64>,
2117 vs: Vec<f64>,
2118 nodes: Vec<Vec3>,
2120 boxes: Vec<CellBox>,
2122 tree: Vec<CellTreeNode>,
2124 node_boxes: Vec<CellBox>,
2128 node_margin: f64,
2130 scale: f64,
2132 resolution: f64,
2133}
2134
2135fn lattice_parameters(knots: &[f64], degree: usize, closed: bool) -> Vec<f64> {
2139 let [start, end] = crate::curve::knot_domain(knots, degree);
2140 let samples = if closed {
2141 8usize.max(degree * 4)
2142 } else {
2143 3usize.max(degree + 1)
2144 };
2145 let mut breaks = vec![start];
2146 breaks.extend(interior_knots(knots, degree));
2147 breaks.push(end);
2148 let mut parameters = Vec::with_capacity((breaks.len() - 1) * samples + 1);
2149 for pair in breaks.windows(2) {
2150 for index in 0..samples {
2151 parameters.push(pair[0] + (pair[1] - pair[0]) * index as f64 / samples as f64);
2152 }
2153 }
2154 parameters.push(end);
2155 parameters
2156}
2157
2158fn refine_to_lattice(net: &mut Vec<Vec<Vec4>>, knots: &mut Vec<f64>, degree: usize, parameters: &[f64]) {
2167 let p = degree;
2168 let n = net.len() - 1;
2169 let mut inserted = Vec::new();
2170 for ¶meter in parameters {
2171 let multiplicity = knots.iter().filter(|&&knot| knot == parameter).count();
2172 for _ in multiplicity..p {
2173 inserted.push(parameter);
2174 }
2175 }
2176 if inserted.is_empty() || p == 0 {
2177 return;
2178 }
2179 inserted.sort_by(f64::total_cmp);
2180 let find_span = |parameter: f64| -> usize {
2181 if parameter >= knots[n + 1] {
2182 return n;
2183 }
2184 (knots.partition_point(|&knot| knot <= parameter) - 1).clamp(p, n)
2185 };
2186 let r = inserted.len() - 1;
2187 let m = n + p + 1;
2188 let a = find_span(inserted[0]);
2189 let b = find_span(inserted[r]) + 1;
2190 let columns = net[0].len();
2191 let blank = vec![
2192 Vec4 {
2193 x: 0.0,
2194 y: 0.0,
2195 z: 0.0,
2196 w: 0.0,
2197 };
2198 columns
2199 ];
2200 let mut refined = vec![blank; n + r + 2];
2201 let mut refined_knots = vec![0.0; m + r + 2];
2202 for j in 0..=a - p {
2203 refined[j] = net[j].clone();
2204 }
2205 for j in b - 1..=n {
2206 refined[j + r + 1] = net[j].clone();
2207 }
2208 refined_knots[..=a].copy_from_slice(&knots[..=a]);
2209 for j in b + p..=m {
2210 refined_knots[j + r + 1] = knots[j];
2211 }
2212 let mut i = b + p - 1;
2213 let mut k = b + p + r;
2214 for j in (0..=r).rev() {
2215 while inserted[j] <= knots[i] && i > a {
2216 refined[k - p - 1] = net[i - p - 1].clone();
2217 refined_knots[k] = knots[i];
2218 k -= 1;
2219 i -= 1;
2220 }
2221 refined[k - p - 1] = refined[k - p].clone();
2222 for l in 1..=p {
2223 let index = k - p + l;
2224 let numerator = refined_knots[k + l] - inserted[j];
2225 if numerator == 0.0 {
2226 refined[index - 1] = refined[index].clone();
2227 } else {
2228 let alpha = numerator / (refined_knots[k + l] - knots[i - p + l]);
2229 let (head, tail) = refined.split_at_mut(index);
2230 for (before, &here) in head[index - 1].iter_mut().zip(&tail[0]) {
2231 *before = before.scale(alpha).add(here.scale(1.0 - alpha));
2232 }
2233 }
2234 }
2235 refined_knots[k] = inserted[j];
2236 k = k.saturating_sub(1);
2237 }
2238 *net = refined;
2239 *knots = refined_knots;
2240}
2241
2242fn supporting_range(knots: &[f64], degree: usize, count: usize, low: f64, high: f64) -> (usize, usize) {
2245 let first_span = knots.partition_point(|&knot| knot <= low).saturating_sub(1);
2246 let last_span = knots.partition_point(|&knot| knot < high).saturating_sub(1);
2247 (
2248 first_span.saturating_sub(degree).min(count - 1),
2249 last_span.max(first_span).min(count - 1),
2250 )
2251}
2252
2253fn unit_or(vector: Vec3, fallback: Vec3) -> Vec3 {
2254 let length = vector.length();
2255 if length > 0.0 && length.is_finite() {
2256 vector.scale(1.0 / length)
2257 } else {
2258 fallback
2259 }
2260}
2261
2262fn enclosing_sphere(a: (Vec3, f64), b: (Vec3, f64)) -> (Vec3, f64) {
2263 let offset = b.0.sub(a.0);
2264 let separation = offset.length();
2265 if separation + b.1 <= a.1 {
2266 return a;
2267 }
2268 if separation + a.1 <= b.1 {
2269 return b;
2270 }
2271 let radius = (separation + a.1 + b.1) * 0.5;
2272 let centre = a.0.add(offset.scale((radius - a.1) / separation));
2273 (centre, radius)
2274}
2275
2276struct NodeBoxInputs<'a> {
2280 boxes: &'a [CellBox],
2281 nodes: &'a [Vec3],
2282 lattice_columns: usize,
2283 margin: f64,
2284}
2285
2286fn enclosing_node_box(corners: [Vec3; 4], children: [&CellBox; 2], margin: f64) -> CellBox {
2291 let unbounded = || CellBox {
2292 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)],
2293 low: [f64::NEG_INFINITY; 3],
2294 high: [f64::INFINITY; 3],
2295 };
2296 let [c00, c10, c01, c11] = corners;
2297 let along_u = c10.sub(c00).add(c11.sub(c01));
2298 let along_v = c01.sub(c00).add(c11.sub(c10));
2299 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2300 let Ok(fallback) = e1.perpendicular() else {
2301 return unbounded();
2302 };
2303 let normal = unit_or(e1.cross(along_v), fallback);
2304 let e2 = unit_or(normal.cross(e1), fallback);
2305 let e3 = e1.cross(e2);
2306 let axes = [e1, e2, e3];
2307 let mut low = [f64::INFINITY; 3];
2308 let mut high = [f64::NEG_INFINITY; 3];
2309 for child in children {
2310 for corner in 0..8 {
2311 let mut point = Vec3::default();
2312 for axis in 0..3 {
2313 let value = if corner >> axis & 1 == 0 { child.low[axis] } else { child.high[axis] };
2314 point = point.add(child.axes[axis].scale(value));
2315 }
2316 for axis in 0..3 {
2317 let coordinate = point.dot(axes[axis]);
2318 low[axis] = low[axis].min(coordinate);
2319 high[axis] = high[axis].max(coordinate);
2320 }
2321 }
2322 }
2323 for axis in 0..3 {
2324 low[axis] -= margin;
2325 high[axis] += margin;
2326 }
2327 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2328 return unbounded();
2329 }
2330 CellBox { axes, low, high }
2331}
2332
2333fn build_cell_tree(
2334 tree: &mut Vec<CellTreeNode>,
2335 node_boxes: &mut Vec<CellBox>,
2336 inputs: &NodeBoxInputs<'_>,
2337 spheres: &[(Vec3, f64)],
2338 columns: usize,
2339 [row_low, row_high, column_low, column_high]: [usize; 4],
2340) -> u32 {
2341 if row_high - row_low == 1 && column_high - column_low == 1 {
2342 let cell = row_low * columns + column_low;
2343 node_boxes.push(inputs.boxes[cell].clone());
2344 tree.push(CellTreeNode {
2345 centre: spheres[cell].0,
2346 radius: spheres[cell].1,
2347 children: None,
2348 cell: cell as u32,
2349 });
2350 return (tree.len() - 1) as u32;
2351 }
2352 let (first, second) = if row_high - row_low >= column_high - column_low {
2353 let middle = (row_low + row_high) / 2;
2354 (
2355 [row_low, middle, column_low, column_high],
2356 [middle, row_high, column_low, column_high],
2357 )
2358 } else {
2359 let middle = (column_low + column_high) / 2;
2360 (
2361 [row_low, row_high, column_low, middle],
2362 [row_low, row_high, middle, column_high],
2363 )
2364 };
2365 let first = build_cell_tree(tree, node_boxes, inputs, spheres, columns, first);
2366 let second = build_cell_tree(tree, node_boxes, inputs, spheres, columns, second);
2367 let a = tree[first as usize];
2368 let b = tree[second as usize];
2369 let lattice = |row: usize, column: usize| inputs.nodes[row * inputs.lattice_columns + column];
2370 node_boxes.push(enclosing_node_box(
2371 [
2372 lattice(row_low, column_low),
2373 lattice(row_high, column_low),
2374 lattice(row_low, column_high),
2375 lattice(row_high, column_high),
2376 ],
2377 [&node_boxes[first as usize], &node_boxes[second as usize]],
2378 inputs.margin,
2379 ));
2380 let (centre, radius) = enclosing_sphere((a.centre, a.radius), (b.centre, b.radius));
2384 tree.push(CellTreeNode {
2385 centre,
2386 radius: radius * (1.0 + 4.0 * f64::EPSILON),
2387 children: Some((first, second)),
2388 cell: u32::MAX,
2389 });
2390 (tree.len() - 1) as u32
2391}
2392
2393fn projection_cells(surface: &NurbsSurface) -> Result<Option<&ProjectionCells>, String> {
2394 if let Some(cells) = surface.projection_cells.get() {
2395 return Ok(cells.as_ref());
2396 }
2397 let cells = build_projection_cells(surface)?;
2398 Ok(surface.projection_cells.get_or_init(|| cells).as_ref())
2399}
2400
2401fn build_projection_cells(surface: &NurbsSurface) -> Result<Option<ProjectionCells>, String> {
2402 let (closed_u, closed_v) = surface.closed_directions()?;
2403 let us = lattice_parameters(&surface.knots_u, surface.degree_u, closed_u);
2404 let vs = lattice_parameters(&surface.knots_v, surface.degree_v, closed_v);
2405 if us.len() < 2 || vs.len() < 2 {
2406 return Ok(None);
2407 }
2408 let mut scale = 0.0f64;
2409 for control in surface.control_points.iter().flatten() {
2410 let point = control.point()?;
2411 scale = scale.max(point.x.abs()).max(point.y.abs()).max(point.z.abs());
2412 }
2413 let resolution =
2414 ((surface.degree_u + 1) * (surface.degree_v + 1)) as f64 * f64::EPSILON * scale;
2415
2416 let mut net = surface.control_points.clone();
2418 let mut knots_u = surface.knots_u.clone();
2419 refine_to_lattice(&mut net, &mut knots_u, surface.degree_u, &us);
2420 let columns = net.first().map(Vec::len).unwrap_or(0);
2421 let mut transposed: Vec<Vec<Vec4>> =
2422 (0..columns).map(|column| net.iter().map(|row| row[column]).collect()).collect();
2423 let mut knots_v = surface.knots_v.clone();
2424 refine_to_lattice(&mut transposed, &mut knots_v, surface.degree_v, &vs);
2425 let rows = transposed.first().map(Vec::len).unwrap_or(0);
2426 let columns = transposed.len();
2427 if rows == 0 || columns == 0 {
2428 return Ok(None);
2429 }
2430 let mut points = vec![Vec3::default(); rows * columns];
2431 for (column, fibre) in transposed.iter().enumerate() {
2432 for (row, control) in fibre.iter().enumerate() {
2433 points[row * columns + column] = control.point()?;
2434 }
2435 }
2436
2437 let mut nodes = Vec::with_capacity(us.len() * vs.len());
2438 for &u in &us {
2439 for &v in &vs {
2440 nodes.push(surface.evaluate(u, v)?);
2441 }
2442 }
2443
2444 let cell_rows = us.len() - 1;
2445 let cell_columns = vs.len() - 1;
2446 let mut boxes = Vec::with_capacity(cell_rows * cell_columns);
2447 let mut spheres = Vec::with_capacity(cell_rows * cell_columns);
2448 for i in 0..cell_rows {
2449 let (row_low, row_high) =
2450 supporting_range(&knots_u, surface.degree_u, rows, us[i], us[i + 1]);
2451 for j in 0..cell_columns {
2452 let (column_low, column_high) =
2453 supporting_range(&knots_v, surface.degree_v, columns, vs[j], vs[j + 1]);
2454 let at = |row: usize, column: usize| points[row * columns + column];
2455 let c00 = at(row_low, column_low);
2456 let c10 = at(row_high, column_low);
2457 let c01 = at(row_low, column_high);
2458 let c11 = at(row_high, column_high);
2459 let along_u = c10.sub(c00).add(c11.sub(c01));
2460 let along_v = c01.sub(c00).add(c11.sub(c10));
2461 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2462 let normal = unit_or(e1.cross(along_v), e1.perpendicular()?);
2463 let e2 = unit_or(normal.cross(e1), e1.perpendicular()?);
2464 let e3 = e1.cross(e2);
2465 let axes = [e1, e2, e3];
2466 let mut low = [f64::INFINITY; 3];
2467 let mut high = [f64::NEG_INFINITY; 3];
2468 for row in row_low..=row_high {
2469 for column in column_low..=column_high {
2470 let point = at(row, column);
2471 for axis in 0..3 {
2472 let coordinate = point.dot(axes[axis]);
2473 low[axis] = low[axis].min(coordinate);
2474 high[axis] = high[axis].max(coordinate);
2475 }
2476 }
2477 }
2478 for axis in 0..3 {
2479 low[axis] -= resolution;
2480 high[axis] += resolution;
2481 }
2482 let mut centre = Vec3::default();
2483 let mut half_diagonal_squared = 0.0;
2484 for axis in 0..3 {
2485 centre = centre.add(axes[axis].scale((low[axis] + high[axis]) * 0.5));
2486 let half = (high[axis] - low[axis]) * 0.5;
2487 half_diagonal_squared += half * half;
2488 }
2489 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2490 return Ok(None);
2491 }
2492 spheres.push((centre, half_diagonal_squared.sqrt() + resolution));
2493 boxes.push(CellBox { axes, low, high });
2494 }
2495 }
2496 let mut tree = Vec::with_capacity(2 * boxes.len());
2497 let mut node_boxes = Vec::with_capacity(2 * boxes.len());
2498 let node_margin = NODE_BOX_MARGIN * scale;
2503 let inputs = NodeBoxInputs { boxes: &boxes, nodes: &nodes, lattice_columns: vs.len(), margin: node_margin };
2504 build_cell_tree(&mut tree, &mut node_boxes, &inputs, &spheres, cell_columns, [0, cell_rows, 0, cell_columns]);
2505 if !(node_margin > 0.0 && node_margin.is_finite()) {
2506 node_boxes = Vec::new();
2507 }
2508 Ok(Some(ProjectionCells {
2509 us,
2510 vs,
2511 nodes,
2512 boxes,
2513 tree,
2514 node_boxes,
2515 node_margin,
2516 scale,
2517 resolution,
2518 }))
2519}
2520
2521fn optimality(
2526 derivatives: &[[Vec3; 3]; 3],
2527 point: Vec3,
2528 (u, v): (f64, f64),
2529 [ua, ub, va, vb]: [f64; 4],
2530 periodic: (bool, bool),
2531) -> Optimality {
2532 let residual = derivatives[0][0].sub(point);
2533 let residual_length = residual.length();
2534 let su = derivatives[1][0];
2535 let sv = derivatives[0][1];
2536 let f = su.dot(residual);
2537 let g = sv.dot(residual);
2538 let metric_u = su.length_squared();
2539 let metric_v = sv.length_squared();
2540 let stationary_u = metric_u.sqrt() * residual_length <= EPSILON
2541 || f.abs() <= 1e-10 * metric_u.sqrt() * residual_length;
2542 let stationary_v = metric_v.sqrt() * residual_length <= EPSILON
2543 || g.abs() <= 1e-10 * metric_v.sqrt() * residual_length;
2544 let pinned_u = !periodic.0 && ((u <= ua && f > 0.0) || (u >= ub && f < 0.0));
2545 let pinned_v = !periodic.1 && ((v <= va && g > 0.0) || (v >= vb && g < 0.0));
2546 let j00 = derivatives[2][0].dot(residual) + metric_u;
2547 let j01 = derivatives[1][1].dot(residual) + su.dot(sv);
2548 let j11 = derivatives[0][2].dot(residual) + metric_v;
2549 let determinant = j00 * j11 - j01 * j01;
2550 let convex = match (!pinned_u, !pinned_v) {
2551 (true, true) => j00 > 0.0 && determinant > 0.0,
2552 (true, false) => j00 > 0.0,
2553 (false, true) => j11 > 0.0,
2554 (false, false) => true,
2555 };
2556 Optimality {
2557 residual_length,
2558 gradient: (f, g),
2559 metric: (metric_u, metric_v),
2560 hessian: (j00, j01, j11),
2561 determinant,
2562 pinned: (pinned_u, pinned_v),
2563 convex,
2564 minimum: residual_length <= LINEAR_TOLERANCE
2565 || ((stationary_u || pinned_u) && (stationary_v || pinned_v) && convex),
2566 }
2567}
2568
2569struct Optimality {
2570 residual_length: f64,
2571 gradient: (f64, f64),
2572 metric: (f64, f64),
2573 hessian: (f64, f64, f64),
2574 determinant: f64,
2575 pinned: (bool, bool),
2576 convex: bool,
2577 minimum: bool,
2578}
2579
2580fn is_verified_minimum(
2581 surface: &NurbsSurface,
2582 point: Vec3,
2583 at: (f64, f64),
2584 rectangle: [f64; 4],
2585 periodic: (bool, bool),
2586) -> Result<bool, String> {
2587 let derivatives = surface.derivatives_small(at.0, at.1, 2)?;
2588 Ok(optimality(&derivatives, point, at, rectangle, periodic).minimum)
2589}
2590
2591fn confined_descent(
2607 surface: &NurbsSurface,
2608 point: Vec3,
2609 seed: (f64, f64),
2610 rectangle: [f64; 4],
2611 periodic: (bool, bool),
2612) -> Result<(NewtonResult, bool), String> {
2613 let [ua, ub, va, vb] = rectangle;
2614 let mut u = fit_parameter(seed.0, ua, ub, periodic.0);
2615 let mut v = fit_parameter(seed.1, va, vb, periodic.1);
2616 let mut converged = false;
2617 let mut current = surface.evaluate(u, v)?.sub(point).length_squared();
2618 for _ in 0..MAX_NEWTON_ITERATIONS {
2619 let derivatives = surface.derivatives_small(u, v, 2)?;
2620 let state = optimality(&derivatives, point, (u, v), rectangle, periodic);
2621 current = state.residual_length * state.residual_length;
2622 if state.minimum {
2623 converged = true;
2624 break;
2625 }
2626 let (f, g) = state.gradient;
2627 let (metric_u, metric_v) = state.metric;
2628 let (j00, j01, j11) = state.hessian;
2629 let determinant = state.determinant;
2630 let (free_u, free_v) = (!state.pinned.0, !state.pinned.1);
2631 let (mut du, mut dv) = match (free_u, free_v) {
2632 (true, true) if state.convex => (
2633 (-f * j11 + g * j01) / determinant,
2634 (-g * j00 + f * j01) / determinant,
2635 ),
2636 (true, false) if state.convex => (-f / j00, 0.0),
2637 (false, true) if state.convex => (0.0, -g / j11),
2638 _ => (
2639 if free_u && metric_u > 0.0 { -f / metric_u } else { 0.0 },
2640 if free_v && metric_v > 0.0 { -g / metric_v } else { 0.0 },
2641 ),
2642 };
2643 if !(du.is_finite() && dv.is_finite()) || (du == 0.0 && dv == 0.0) {
2644 break;
2645 }
2646 let mut moved = false;
2647 let taken = |next: f64, here: f64, low: f64, high: f64, wraps: bool| {
2649 let raw = next - here;
2650 if wraps {
2651 raw - (high - low) * (raw / (high - low)).round()
2652 } else {
2653 raw
2654 }
2655 };
2656 for _ in 0..40 {
2657 let next_u = fit_parameter(u + du, ua, ub, periodic.0);
2658 let next_v = fit_parameter(v + dv, va, vb, periodic.1);
2659 if next_u == u && next_v == v {
2660 break;
2661 }
2662 let trial = surface.evaluate(next_u, next_v)?.sub(point).length_squared();
2663 if trial <= current {
2664 moved = taken(next_u, u, ua, ub, periodic.0).abs() > 1e-15 * (ub - ua)
2665 || taken(next_v, v, va, vb, periodic.1).abs() > 1e-15 * (vb - va);
2666 u = next_u;
2667 v = next_v;
2668 current = trial;
2669 break;
2670 }
2671 du *= 0.5;
2672 dv *= 0.5;
2673 }
2674 if !moved {
2675 break;
2676 }
2677 }
2678 let result = NewtonResult {
2679 u,
2680 v,
2681 distance_squared: current,
2682 converged,
2683 };
2684 let on_edge =
2685 (!periodic.0 && (u <= ua || u >= ub)) || (!periodic.1 && (v <= va || v >= vb));
2686 Ok((result, on_edge))
2687}
2688
2689const NODE_BOX_MARGIN: f64 = 1e-9;
2692
2693fn node_boxes_enabled() -> bool {
2697 switch!("BREP_PROJECTION_NODE_BOXES", true)
2698}
2699
2700fn hull_candidates(cells: &ProjectionCells, point: Vec3, bound: f64, node_boxes: bool) -> (Vec<(f64, usize)>, f64) {
2721 let read_error = 32.0 * f64::EPSILON * (point.x.abs() + point.y.abs() + point.z.abs() + 4.0 * cells.scale);
2722 let boxes = node_boxes && !cells.node_boxes.is_empty() && 4.0 * read_error <= cells.node_margin;
2723 let mut candidates: Vec<(f64, usize)> = Vec::new();
2724 let mut excluded = f64::INFINITY;
2725 let mut stack: Vec<u32> = Vec::with_capacity(64);
2726 stack.push((cells.tree.len() - 1) as u32);
2727 while let Some(index) = stack.pop() {
2728 let node = cells.tree[index as usize];
2729 let sphere_bound = (point.sub(node.centre).length() - node.radius).max(0.0);
2730 if sphere_bound >= bound {
2731 excluded = excluded.min(sphere_bound);
2732 continue;
2733 }
2734 match node.children {
2735 Some((first, second)) => {
2736 if boxes {
2737 let box_bound = cells.node_boxes[index as usize].lower_bound(point);
2738 if box_bound >= bound && box_bound > 2.0 * read_error {
2739 excluded = excluded.min(box_bound);
2740 continue;
2741 }
2742 }
2743 stack.push(first);
2744 stack.push(second);
2745 }
2746 None => {
2747 let cell = node.cell as usize;
2748 let box_bound = cells.boxes[cell].lower_bound(point);
2749 if box_bound < bound {
2750 candidates.push((box_bound, cell));
2751 } else {
2752 excluded = excluded.min(box_bound);
2753 }
2754 }
2755 }
2756 }
2757 (candidates, excluded)
2758}
2759
2760#[allow(clippy::too_many_arguments)]
2763fn global_minimum(
2764 surface: &NurbsSurface,
2765 point: Vec3,
2766 domains: [f64; 4],
2767 periodic: (bool, bool),
2768 best: &mut NewtonResult,
2769 stats: &mut GlobalStats,
2770) -> Result<(), String> {
2771 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2772 stats.settled_by_floor = true;
2773 return Ok(());
2774 }
2775 let Some(cells) = projection_cells(surface)? else {
2776 return Ok(());
2777 };
2778 let resolution = cells.resolution;
2779 let columns = cells.vs.len() - 1;
2780 let columns_u = cells.us.len() - 1;
2781 let mut bound = best.distance_squared.sqrt() - resolution;
2782
2783 let (mut candidates, excluded) = hull_candidates(cells, point, bound, node_boxes_enabled());
2786 stats.candidates = candidates.len();
2787 candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
2788 stats.hull_lower_bound = candidates
2789 .first()
2790 .map_or(excluded, |&(least, _)| least.min(excluded));
2791
2792 let cell_of = |u: f64, v: f64| {
2798 let row = (cells.us.partition_point(|&value| value <= u).max(1) - 1).min(columns_u - 1);
2799 let column = (cells.vs.partition_point(|&value| value <= v).max(1) - 1).min(columns - 1);
2800 row * columns + column
2801 };
2802 let mut settled: Vec<usize> = Vec::new();
2803 if is_verified_minimum(surface, point, (best.u, best.v), domains, periodic)? {
2804 settled.push(cell_of(best.u, best.v));
2805 }
2806 for (cell_bound, cell) in candidates {
2807 if cell_bound >= bound {
2808 break;
2809 }
2810 let row = cell / columns;
2811 let column = cell % columns;
2812 let rectangle = [
2813 cells.us[row],
2814 cells.us[row + 1],
2815 cells.vs[column],
2816 cells.vs[column + 1],
2817 ];
2818 if settled.contains(&cell) {
2819 continue;
2820 }
2821 let mut seed = (rectangle[0], rectangle[2]);
2822 let mut seed_distance = f64::INFINITY;
2823 for (node_row, node_column) in
2824 [(row, column), (row + 1, column), (row, column + 1), (row + 1, column + 1)]
2825 {
2826 let distance = cells.nodes[node_row * cells.vs.len() + node_column]
2827 .sub(point)
2828 .length_squared();
2829 if distance < seed_distance {
2830 seed_distance = distance;
2831 seed = (cells.us[node_row], cells.vs[node_column]);
2832 }
2833 }
2834 stats.refinements += 1;
2835 let (confined, on_edge) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2836 let mut found = confined;
2837 if on_edge && confined.distance_squared.sqrt() < bound {
2838 stats.continuations += 1;
2841 let (continued, _) =
2842 confined_descent(surface, point, (confined.u, confined.v), domains, periodic)?;
2843 if continued.distance_squared < found.distance_squared {
2844 found = continued;
2845 }
2846 if continued.converged {
2847 settled.push(cell_of(continued.u, continued.v));
2848 }
2849 }
2850 if found.distance_squared.sqrt() < bound {
2851 *best = found;
2852 bound = best.distance_squared.sqrt() - resolution;
2853 stats.replaced = true;
2854 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2855 return Ok(());
2856 }
2857 }
2858 }
2859 Ok(())
2860}
2861
2862
2863
2864#[derive(Clone, Copy)]
2866pub enum FootDomain {
2867 Clamp,
2868 Wrap,
2869 Extended,
2870}
2871
2872#[derive(Clone, Copy)]
2873pub struct CurveFootPolicy {
2874 pub domain: FootDomain,
2875 pub iterations: usize,
2876 pub slope_guard: f64,
2877 pub step_limit: f64,
2878 pub parameter_tolerance: f64,
2879 pub mode: FootMode,
2880}
2881
2882#[derive(Clone, Copy)]
2884pub enum FootMode {
2885 Monotone,
2886 Witness,
2887 Stationary { positive_slope: bool, relative_step: bool },
2888 Backtracked,
2889 Planar,
2890}
2891
2892fn curve_foot_newton_state(
2895 curve: &NurbsCurve,
2896 point: Vec3,
2897 seed: f64,
2898 bracket: [f64; 2],
2899 policy: CurveFootPolicy,
2900) -> Result<(f64, f64, f64), String> {
2901 let fit = |u| match policy.domain {
2902 FootDomain::Clamp => fit_parameter(u, bracket[0], bracket[1], false),
2903 FootDomain::Wrap => fit_parameter(u, bracket[0], bracket[1], true),
2904 FootDomain::Extended => u,
2905 };
2906 let extended = matches!(policy.domain, FootDomain::Extended) || matches!(policy.mode, FootMode::Backtracked);
2907 let planar = matches!(policy.mode, FootMode::Planar);
2908 let project = |p: Vec3| if planar { Vec3::new(p.x, p.y, 0.0) } else { p };
2909 let point = project(point);
2910 let distance = |u| -> Result<f64, String> {
2911 let p = if extended { curve.derivatives_extended(u, 0)?[0] } else { curve.evaluate(u)? };
2912 Ok(project(p).sub(point).length())
2913 };
2914 let monotone = matches!(policy.mode, FootMode::Monotone | FootMode::Backtracked);
2915 let witness = matches!(policy.mode, FootMode::Witness);
2916 let mut u = if witness { seed } else { fit(seed) };
2917 let mut nearest_u = seed;
2918 let mut nearest_squared = f64::INFINITY;
2919 let mut best = if monotone { distance(u)? } else { f64::INFINITY };
2920 for _ in 0..policy.iterations {
2921 let derivatives = if extended {
2922 let values = curve.derivatives_extended(u, 2)?;
2923 [values[0], values[1], values[2]]
2924 } else if matches!(policy.mode, FootMode::Stationary { .. })
2925 || (planar && !crate::curve::small_curve_derivatives_enabled()) {
2926 let values = curve.derivatives(u, 2)?;
2927 [values[0], values[1], values[2]]
2928 } else {
2929 curve.derivatives_small(u, 2)?
2930 }.map(project);
2931 let offset = derivatives[0].sub(point);
2932 let numerator = offset.dot(derivatives[1]);
2933 let denominator = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
2934 if witness {
2935 let squared = offset.length_squared();
2936 if squared < nearest_squared {
2937 nearest_u = u;
2938 nearest_squared = squared;
2939 }
2940 let residual_length = squared.sqrt();
2941 if residual_length <= LINEAR_TOLERANCE
2942 || numerator.abs() <= EPSILON + 1e-10 * derivatives[1].length() * residual_length {
2943 break;
2944 }
2945 }
2946 let singular = if planar { denominator.abs() < policy.slope_guard }
2947 else { denominator.abs() <= policy.slope_guard };
2948 if singular || (matches!(policy.mode, FootMode::Stationary { positive_slope: true, .. }) && !(denominator > 0.0)) { break; }
2949 let mut step = if matches!(policy.mode, FootMode::Backtracked) && !(denominator > 0.0) {
2950 policy.step_limit.copysign(numerator)
2951 } else {
2952 (numerator / denominator).clamp(-policy.step_limit, policy.step_limit)
2953 };
2954 let mut next = fit(u - step);
2955 let mut next_distance = if monotone { distance(next)? } else { f64::INFINITY };
2956 if matches!(policy.mode, FootMode::Backtracked) {
2957 for _ in 0..30 {
2958 if next_distance < best { break; }
2959 step *= 0.5;
2960 next = fit(u - step);
2961 next_distance = distance(next)?;
2962 }
2963 if !(next_distance < best) { break; }
2964 } else if monotone && next_distance >= best { break; }
2965 let moved = if planar || matches!(policy.domain, FootDomain::Extended) { step }
2966 else if matches!(policy.domain, FootDomain::Wrap) {
2967 let period = bracket[1] - bracket[0];
2968 let raw = next - u;
2969 raw - period * (raw / period).round()
2970 } else { next - u };
2971 let tolerance = if matches!(policy.mode, FootMode::Stationary { relative_step: true, .. }) {
2972 policy.parameter_tolerance * (1.0 + u.abs())
2973 } else { policy.parameter_tolerance };
2974 let small = if planar || matches!(policy.mode, FootMode::Backtracked) { moved.abs() < tolerance }
2975 else { moved.abs() <= tolerance };
2976 if small && matches!(policy.mode, FootMode::Monotone) { break; }
2977 u = next;
2978 best = next_distance;
2979 if small { break; }
2980 }
2981 if witness { return Ok((u, nearest_u, nearest_squared)); }
2982 if !monotone { best = distance(u)?; }
2983 Ok((u, u, best * best))
2984}
2985
2986pub fn curve_foot_newton(
2987 curve: &NurbsCurve, point: Vec3, seed: f64, bracket: [f64; 2], policy: CurveFootPolicy,
2988) -> Result<(f64, f64), String> {
2989 let (_, nearest, squared) = curve_foot_newton_state(curve, point, seed, bracket, policy)?;
2990 Ok((nearest, squared))
2991}
2992
2993
2994
2995