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 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 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 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_local(
838 surface: &NurbsSurface,
839 point: Vec3,
840) -> Result<SurfaceProjection, String> {
841 if let Some(analytic) = surface.analytic() {
842 if let Some(projection) = analytic.project(surface, point) {
843 return Ok(projection);
844 }
845 }
846 if let Some(ellipsoid) = surface.affine_sphere() {
847 if let Some(projection) = ellipsoid.project(surface, point) {
848 return Ok(projection);
849 }
850 }
851 if switch!("BREP_EXTRUSION_PROJECTION", true) {
852 if let Some(projection) = surface.linear_extrusion().and_then(|e| e.project(surface, point)) {
853 return Ok(projection);
854 }
855 }
856 project_point_to_surface_from_nearest_seed(surface, point)
857}
858
859pub fn project_point_to_surface_seeded(
869 surface: &NurbsSurface,
870 point: Vec3,
871 seed_u: f64,
872 seed_v: f64,
873) -> Result<SurfaceProjection, String> {
874 crate::work_counts::add(|c| c.projection_seeded += 1);
875 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
876 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_SEEDED, surface);
877 if let Some(ellipsoid) = surface.affine_sphere() {
881 if let Some(projection) = ellipsoid.project(surface, point) {
882 return Ok(projection);
883 }
884 }
885 let [u0, u1] = surface.domain_u()?;
886 let [v0, v1] = surface.domain_v()?;
887 let (closed_u, closed_v) = surface.closed_directions()?;
888 let result = surface_newton(
889 surface,
890 point,
891 seed_u,
892 seed_v,
893 [u0, u1, v0, v1],
894 closed_u,
895 closed_v,
896 )?;
897 let projected = surface.evaluate(result.u, result.v)?;
898 Ok(SurfaceProjection {
899 u: result.u,
900 v: result.v,
901 point: projected,
902 distance: projected.sub(point).length(),
903 })
904}
905
906#[track_caller]
940pub fn project_point_to_surface_from_seed(
941 surface: &NurbsSurface,
942 point: Vec3,
943 seed: [f64; 2],
944) -> Result<SurfaceProjection, String> {
945 crate::work_counts::add(|c| c.projection_from_seed += 1);
946 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
947 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_SEED, surface);
948 if let Some(analytic) = surface.analytic() {
949 if let Some(projection) = analytic.project(surface, point) {
950 return Ok(projection);
951 }
952 }
953 if let Some(ellipsoid) = surface.affine_sphere() {
954 if let Some(projection) = ellipsoid.project(surface, point) {
955 return Ok(projection);
956 }
957 }
958 let caller = std::panic::Location::caller();
959 if !seeded_answer_admitted(caller) {
960 return project_point_to_surface_general(surface, point);
961 }
962 let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
963 if seed_audit_enabled() {
964 let nearest = project_point_to_surface_general(surface, point)?;
965 if seeded.point.sub(nearest.point).length() > LINEAR_TOLERANCE {
966 seed_audit_record(caller, surface, seed, &seeded, &nearest);
967 }
968 }
969 Ok(seeded)
970}
971
972fn seeded_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
975 static SITES: std::sync::OnceLock<Option<Option<Vec<String>>>> = std::sync::OnceLock::new();
976 let sites = SITES.get_or_init(|| {
977 if std::env::var("BREP_PROJECTION_FROM_SEED").as_deref() == Ok("0") {
978 return None;
979 }
980 Some(std::env::var("BREP_PROJECTION_FROM_SEED_SITES").ok().map(|value| {
981 value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect()
982 }))
983 });
984 match sites {
985 None => false,
986 Some(None) => true,
987 Some(Some(only)) => {
988 let location = format!("{}:{}", caller.file(), caller.line());
989 only.iter().any(|site| location.contains(site.as_str()))
990 }
991 }
992}
993
994fn seed_audit_enabled() -> bool {
995 debug_flag!("BREP_PROJECTION_AUDIT")
996}
997
998fn seed_audit_record(
1002 caller: &std::panic::Location<'_>,
1003 surface: &NurbsSurface,
1004 seed: [f64; 2],
1005 seeded: &SurfaceProjection,
1006 nearest: &SurfaceProjection,
1007) {
1008 use std::io::Write;
1009 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1010 std::sync::OnceLock::new();
1011 let sink = SINK.get_or_init(|| {
1012 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1013 let path = std::path::Path::new(&directory)
1014 .join(format!("projection-seed-audit-{}.tsv", std::process::id()));
1015 std::fs::OpenOptions::new()
1016 .create(true)
1017 .append(true)
1018 .open(path)
1019 .ok()
1020 .map(std::sync::Mutex::new)
1021 });
1022 if let Some(file) = sink {
1023 if let Ok(mut file) = file.lock() {
1024 let _ = writeln!(
1025 file,
1026 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.6e}\t{}x{} cp {}x{}",
1027 caller.file(),
1028 caller.line(),
1029 seeded.distance,
1030 nearest.distance,
1031 seed[0],
1032 seed[1],
1033 seeded.u,
1034 seeded.v,
1035 nearest.u,
1036 nearest.v,
1037 seeded.point.sub(nearest.point).length(),
1038 surface.degree_u,
1039 surface.degree_v,
1040 surface.control_points.len(),
1041 surface.control_points.first().map(Vec::len).unwrap_or(0),
1042 );
1043 }
1044 }
1045}
1046
1047fn projection_seed_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
1052 if let Some(grid) = surface.projection_grid.get() {
1053 return Ok(grid);
1054 }
1055 let [u0, u1] = surface.domain_u()?;
1056 let [v0, v1] = surface.domain_v()?;
1057 let (closed_u, closed_v) = surface.closed_directions()?;
1058 let mut breaks_u = vec![u0];
1059 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
1060 breaks_u.push(u1);
1061 let mut breaks_v = vec![v0];
1062 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
1063 breaks_v.push(v1);
1064 let samples_u = if closed_u {
1065 8usize.max(surface.degree_u * 4)
1066 } else {
1067 3usize.max(surface.degree_u + 1)
1068 };
1069 let samples_v = if closed_v {
1070 8usize.max(surface.degree_v * 4)
1071 } else {
1072 3usize.max(surface.degree_v + 1)
1073 };
1074 let mut grid = Vec::new();
1075 for u_pair in breaks_u.windows(2) {
1076 for v_pair in breaks_v.windows(2) {
1077 for i in 0..=samples_u {
1078 for j in 0..=samples_v {
1079 let u = u_pair[0] + (u_pair[1] - u_pair[0]) * i as f64 / samples_u as f64;
1080 let v = v_pair[0] + (v_pair[1] - v_pair[0]) * j as f64 / samples_v as f64;
1081 grid.push((u, v, surface.evaluate(u, v)?));
1082 }
1083 }
1084 }
1085 }
1086 Ok(surface.projection_grid.get_or_init(|| SampleGrid::new(grid)))
1087}
1088
1089fn projection_dense_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
1096 if let Some(grid) = surface.projection_dense_grid.get() {
1097 return Ok(grid);
1098 }
1099 let [u0, u1] = surface.domain_u()?;
1100 let [v0, v1] = surface.domain_v()?;
1101 let mut breaks_u = vec![u0];
1102 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
1103 breaks_u.push(u1);
1104 let mut breaks_v = vec![v0];
1105 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
1106 breaks_v.push(v1);
1107 let count_u = 32usize.max((breaks_u.len() - 1) * 8);
1108 let count_v = 16usize.max((breaks_v.len() - 1) * 8);
1109 let mut grid = Vec::with_capacity((count_u + 1) * (count_v + 1));
1110 for i in 0..=count_u {
1111 for j in 0..=count_v {
1112 let u = u0 + (u1 - u0) * i as f64 / count_u as f64;
1113 let v = v0 + (v1 - v0) * j as f64 / count_v as f64;
1114 grid.push((u, v, surface.evaluate(u, v)?));
1115 }
1116 }
1117 Ok(surface.projection_dense_grid.get_or_init(|| SampleGrid::with_tree(grid)))
1118}
1119
1120const SAMPLE_BLOCK: usize = 32;
1122
1123const GROUP_BLOCKS: usize = 32;
1126
1127#[derive(Clone, Debug)]
1132pub struct SampleGrid {
1133 samples: Vec<(f64, f64, Vec3)>,
1134 blocks: Vec<SampleBlock>,
1135 groups: Vec<SampleBlock>,
1140 tree: Vec<Vec<SampleBlock>>,
1146}
1147
1148const TREE_FANOUT: usize = 4;
1150
1151fn union_boxes(boxes: &[SampleBlock]) -> Vec<SampleBlock> {
1153 boxes
1154 .chunks(TREE_FANOUT)
1155 .map(|chunk| {
1156 let mut union = chunk[0];
1157 for block in chunk {
1158 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));
1159 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));
1160 union.prunable &= block.prunable;
1161 }
1162 union
1163 })
1164 .collect()
1165}
1166
1167#[derive(Clone, Copy, Debug)]
1170struct SampleBlock {
1171 low: Vec3,
1172 high: Vec3,
1173 prunable: bool,
1174}
1175
1176impl SampleGrid {
1177 fn new(samples: Vec<(f64, f64, Vec3)>) -> Self {
1178 let blocks = samples
1179 .chunks(SAMPLE_BLOCK)
1180 .map(|chunk| {
1181 let mut low = chunk[0].2;
1182 let mut high = low;
1183 let mut prunable = true;
1184 for &(_, _, p) in chunk {
1185 prunable &= p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
1186 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
1187 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
1188 }
1189 SampleBlock { low, high, prunable }
1190 })
1191 .collect::<Vec<_>>();
1192 let groups = blocks
1193 .chunks(GROUP_BLOCKS)
1194 .map(|chunk| {
1195 let mut group = chunk[0];
1196 for block in chunk {
1197 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));
1198 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));
1199 group.prunable &= block.prunable;
1200 }
1201 group
1202 })
1203 .collect();
1204 Self { samples, blocks, groups, tree: Vec::new() }
1205 }
1206
1207 fn with_tree(samples: Vec<(f64, f64, Vec3)>) -> Self {
1214 let mut grid = Self::new(samples);
1215 if grid.blocks.len() > GROUP_BLOCKS {
1216 grid.tree.push(union_boxes(&grid.blocks));
1217 while grid.tree.last().is_some_and(|level| level.len() > 1) {
1218 let next = union_boxes(grid.tree.last().unwrap());
1219 grid.tree.push(next);
1220 }
1221 }
1222 grid
1223 }
1224}
1225
1226impl SampleBlock {
1227 fn lower_bound(&self, point: Vec3) -> f64 {
1235 let gap = |p: f64, low: f64, high: f64| {
1236 if p < low {
1237 low - p
1238 } else if p > high {
1239 p - high
1240 } else {
1241 0.0
1242 }
1243 };
1244 let x = gap(point.x, self.low.x, self.high.x);
1245 let y = gap(point.y, self.low.y, self.high.y);
1246 let z = gap(point.z, self.low.z, self.high.z);
1247 x * x + y * y + z * z
1248 }
1249}
1250
1251fn pruned_scan() -> bool {
1254 switch!("BREP_PROJECTION_PRUNED_SCAN", true)
1255}
1256
1257fn nearest_sample(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1267 if !grid.tree.is_empty() && scan_tree() && pruned_scan() && bound_first_scan() {
1268 nearest_sample_tree(grid, point, best);
1269 return;
1270 }
1271 nearest_sample_with(grid, point, best, pruned_scan(), bound_first_scan());
1272}
1273
1274fn scan_tree() -> bool {
1286 switch!("BREP_PROJECTION_SCAN_TREE", true)
1287}
1288
1289fn scan_hint() -> bool {
1299 switch!("BREP_PROJECTION_SCAN_HINT", true)
1300}
1301
1302const HINT_SLOTS: usize = 8;
1303
1304thread_local! {
1305 static SCAN_HINTS: std::cell::Cell<[(usize, usize); HINT_SLOTS]> =
1307 const { std::cell::Cell::new([(0, usize::MAX); HINT_SLOTS]) };
1308}
1309
1310fn hint_slot(grid: &SampleGrid) -> (usize, usize) {
1311 let address = grid.samples.as_ptr() as usize;
1312 (address, (address >> 4) % HINT_SLOTS)
1313}
1314
1315fn hinted_bound(grid: &SampleGrid, point: Vec3, mut bound: f64) -> f64 {
1322 if !scan_hint() {
1323 return bound;
1324 }
1325 let (address, slot) = hint_slot(grid);
1326 let (held, run) = SCAN_HINTS.with(|hints| hints.get()[slot]);
1327 if held != address || run >= grid.blocks.len() || !grid.blocks[run].prunable {
1328 return bound;
1329 }
1330 let start = run * SAMPLE_BLOCK;
1331 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1332 for &(_, _, sample) in &grid.samples[start..end] {
1333 let distance_squared = sample.sub(point).length_squared();
1334 if distance_squared < bound {
1335 bound = distance_squared;
1336 }
1337 }
1338 bound
1339}
1340
1341fn remember_hint(grid: &SampleGrid, run: Option<usize>) {
1343 if let Some(run) = run.filter(|_| scan_hint()) {
1344 let (address, slot) = hint_slot(grid);
1345 SCAN_HINTS.with(|hints| {
1346 let mut all = hints.get();
1347 all[slot] = (address, run);
1348 hints.set(all);
1349 });
1350 }
1351}
1352
1353fn nearest_sample_tree(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1364 let top = grid.tree.len() - 1;
1365 let mut bound = best.distance_squared;
1366 let mut node = 0usize;
1368 let mut reached = true;
1369 for level in (0..=top).rev() {
1370 let children = |count: usize| node * TREE_FANOUT..((node + 1) * TREE_FANOUT).min(count);
1371 let below = if level == 0 { &grid.blocks } else { &grid.tree[level - 1] };
1372 match lowest_floor(below, children(below.len()), point) {
1373 Some(child) => node = child,
1374 None => {
1375 reached = false;
1376 break;
1377 }
1378 }
1379 }
1380 if reached {
1381 let start = node * SAMPLE_BLOCK;
1382 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1383 for &(_, _, sample) in &grid.samples[start..end] {
1384 let distance_squared = sample.sub(point).length_squared();
1385 if distance_squared < bound {
1386 bound = distance_squared;
1387 }
1388 }
1389 }
1390 let bound = hinted_bound(grid, point, bound);
1391 let skip = |box_: &SampleBlock, held: f64| {
1392 if !box_.prunable {
1393 return false;
1394 }
1395 let floor = box_.lower_bound(point);
1396 floor >= held || floor > bound
1397 };
1398 let mut answer_run = None;
1399 let mut stack: Vec<(usize, usize)> = Vec::with_capacity(TREE_FANOUT * (top + 2));
1401 stack.push((top + 1, 0));
1402 while let Some((level, index)) = stack.pop() {
1403 if level == 0 {
1404 if skip(&grid.blocks[index], best.distance_squared) {
1405 continue;
1406 }
1407 let start = index * SAMPLE_BLOCK;
1408 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1409 let held = best.distance_squared;
1410 scan_run(&grid.samples[start..end], point, best);
1411 if best.distance_squared < held {
1412 answer_run = Some(index);
1413 }
1414 continue;
1415 }
1416 if skip(&grid.tree[level - 1][index], best.distance_squared) {
1417 continue;
1418 }
1419 let count = if level == 1 { grid.blocks.len() } else { grid.tree[level - 2].len() };
1420 let children = index * TREE_FANOUT..((index + 1) * TREE_FANOUT).min(count);
1421 for child in children.rev() {
1423 stack.push((level - 1, child));
1424 }
1425 }
1426 remember_hint(grid, answer_run);
1427}
1428
1429fn bound_first_scan() -> bool {
1445 switch!("BREP_PROJECTION_BOUND_FIRST", true)
1446}
1447
1448fn nearest_sample_with(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult, pruned: bool, bound_first: bool) {
1458 if !(pruned && bound_first) {
1459 for (block, chunk) in grid.blocks.iter().zip(grid.samples.chunks(SAMPLE_BLOCK)) {
1460 if pruned && block.prunable && block.lower_bound(point) >= best.distance_squared {
1461 continue;
1462 }
1463 scan_run(chunk, point, best);
1464 }
1465 return;
1466 }
1467 let mut bound = best.distance_squared;
1470 let lowest_group = lowest_floor(&grid.groups, 0..grid.groups.len(), point);
1471 if let Some(group) = lowest_group {
1472 let runs = group * GROUP_BLOCKS..((group + 1) * GROUP_BLOCKS).min(grid.blocks.len());
1473 if let Some(run) = lowest_floor(&grid.blocks, runs, point) {
1474 let start = run * SAMPLE_BLOCK;
1475 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1476 for &(_, _, sample) in &grid.samples[start..end] {
1477 let distance_squared = sample.sub(point).length_squared();
1478 if distance_squared < bound {
1479 bound = distance_squared;
1480 }
1481 }
1482 }
1483 }
1484 let bound = hinted_bound(grid, point, bound);
1485 let skip = |box_: &SampleBlock, held: f64| {
1486 if !box_.prunable {
1487 return false;
1488 }
1489 let floor = box_.lower_bound(point);
1490 floor >= held || floor > bound
1491 };
1492 let mut answer_run = None;
1493 for (group_index, group) in grid.groups.iter().enumerate() {
1494 if skip(group, best.distance_squared) {
1495 continue;
1496 }
1497 let first = group_index * GROUP_BLOCKS;
1498 let last = (first + GROUP_BLOCKS).min(grid.blocks.len());
1499 for run in first..last {
1500 if skip(&grid.blocks[run], best.distance_squared) {
1501 continue;
1502 }
1503 let start = run * SAMPLE_BLOCK;
1504 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1505 let held = best.distance_squared;
1506 scan_run(&grid.samples[start..end], point, best);
1507 if best.distance_squared < held {
1508 answer_run = Some(run);
1509 }
1510 }
1511 }
1512 remember_hint(grid, answer_run);
1513}
1514
1515fn scan_run(run: &[(f64, f64, Vec3)], point: Vec3, best: &mut NewtonResult) {
1518 for &(u, v, sample) in run {
1519 let distance_squared = sample.sub(point).length_squared();
1520 if distance_squared < best.distance_squared {
1521 best.u = u;
1522 best.v = v;
1523 best.distance_squared = distance_squared;
1524 }
1525 }
1526}
1527
1528fn lowest_floor(boxes: &[SampleBlock], range: std::ops::Range<usize>, point: Vec3) -> Option<usize> {
1531 let mut lowest: Option<(usize, f64)> = None;
1532 for index in range {
1533 let box_ = &boxes[index];
1534 if !box_.prunable {
1535 continue;
1536 }
1537 let floor = box_.lower_bound(point);
1538 if lowest.is_none_or(|(_, held)| floor < held) {
1539 lowest = Some((index, floor));
1540 }
1541 }
1542 lowest.map(|(index, _)| index)
1543}
1544
1545const RING_EXPONENTS: usize = 22;
1549const RING_INDICES: usize = 33; #[inline]
1552fn ring_slot(side: usize, exponent_index: usize, index: usize) -> usize {
1553 (side * RING_EXPONENTS + exponent_index) * RING_INDICES + index
1554}
1555
1556fn projection_ring_grid(surface: &NurbsSurface) -> Result<&[Vec3], String> {
1563 if let Some(grid) = surface.projection_ring_grid.get() {
1564 return Ok(grid);
1565 }
1566 let [u0, u1] = surface.domain_u()?;
1567 let [v0, v1] = surface.domain_v()?;
1568 let mut grid = vec![Vec3::default(); 4 * RING_EXPONENTS * RING_INDICES];
1569 for exponent in 1..=RING_EXPONENTS as i32 {
1570 let offset = 1.0 / 2f64.powi(exponent);
1571 let e = exponent as usize - 1;
1572 let v_lo = v0 + (v1 - v0) * offset;
1573 let v_hi = v1 - (v1 - v0) * offset;
1574 let u_lo = u0 + (u1 - u0) * offset;
1575 let u_hi = u1 - (u1 - u0) * offset;
1576 for index in 0..=32 {
1577 let u = u0 + (u1 - u0) * index as f64 / 32.0;
1578 grid[ring_slot(0, e, index as usize)] = surface.evaluate(u, v_lo)?;
1579 grid[ring_slot(1, e, index as usize)] = surface.evaluate(u, v_hi)?;
1580 }
1581 for index in 0..=32 {
1582 let v = v0 + (v1 - v0) * index as f64 / 32.0;
1583 grid[ring_slot(2, e, index as usize)] = surface.evaluate(u_lo, v)?;
1584 grid[ring_slot(3, e, index as usize)] = surface.evaluate(u_hi, v)?;
1585 }
1586 }
1587 Ok(surface.projection_ring_grid.get_or_init(|| grid))
1588}
1589
1590fn nearest_seed_answer(
1600 surface: &NurbsSurface,
1601 point: Vec3,
1602 [u0, u1, v0, v1]: [f64; 4],
1603 closed_u: bool,
1604 closed_v: bool,
1605) -> Result<NewtonResult, String> {
1606 let mut best = NewtonResult {
1607 u: u0,
1608 v: v0,
1609 distance_squared: f64::INFINITY,
1610 converged: false,
1611 };
1612 nearest_sample(projection_seed_grid(surface)?, point, &mut best);
1613 if let Some(revolution) = project_linear_revolution(surface, point)? {
1614 if revolution.distance * revolution.distance < best.distance_squared {
1615 best.u = revolution.u;
1616 best.v = revolution.v;
1617 best.distance_squared = revolution.distance * revolution.distance;
1618 }
1619 }
1620 let first_newton = surface_newton(
1621 surface,
1622 point,
1623 best.u,
1624 best.v,
1625 [u0, u1, v0, v1],
1626 closed_u,
1627 closed_v,
1628 )?;
1629 if first_newton.distance_squared < best.distance_squared {
1630 best = first_newton;
1631 }
1632 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1633 let degenerate = su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length());
1634 if degenerate || !first_newton.converged {
1635 let mut grid = best;
1636 nearest_sample(projection_dense_grid(surface)?, point, &mut grid);
1637 if grid.distance_squared < best.distance_squared {
1638 best = grid;
1639 }
1640 let polished = surface_newton(
1641 surface,
1642 point,
1643 grid.u,
1644 grid.v,
1645 [u0, u1, v0, v1],
1646 closed_u,
1647 closed_v,
1648 )?;
1649 if polished.distance_squared < best.distance_squared {
1650 best = polished;
1651 }
1652
1653 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1654 if su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length()) {
1655 let ring_grid = projection_ring_grid(surface)?;
1656 let mut ring = best;
1657 let scan = |side: usize,
1661 exponent_index: usize,
1662 along_u: bool,
1663 fixed: f64,
1664 candidate: &mut NewtonResult| {
1665 for index in 0..=32 {
1666 let moving = if along_u {
1667 u0 + (u1 - u0) * index as f64 / 32.0
1668 } else {
1669 v0 + (v1 - v0) * index as f64 / 32.0
1670 };
1671 let (u, v) = if along_u {
1672 (moving, fixed)
1673 } else {
1674 (fixed, moving)
1675 };
1676 let distance_squared = ring_grid
1677 [ring_slot(side, exponent_index, index as usize)]
1678 .sub(point)
1679 .length_squared();
1680 if distance_squared < candidate.distance_squared {
1681 candidate.u = u;
1682 candidate.v = v;
1683 candidate.distance_squared = distance_squared;
1684 }
1685 }
1686 };
1687 for exponent in 1..=22 {
1688 let offset = 1.0 / 2f64.powi(exponent);
1689 let e = exponent as usize - 1;
1690 if (best.v - v0).abs() <= (v1 - v0) * 0.02 {
1691 scan(0, e, true, v0 + (v1 - v0) * offset, &mut ring);
1692 }
1693 if (best.v - v1).abs() <= (v1 - v0) * 0.02 {
1694 scan(1, e, true, v1 - (v1 - v0) * offset, &mut ring);
1695 }
1696 if (best.u - u0).abs() <= (u1 - u0) * 0.02 {
1697 scan(2, e, false, u0 + (u1 - u0) * offset, &mut ring);
1698 }
1699 if (best.u - u1).abs() <= (u1 - u0) * 0.02 {
1700 scan(3, e, false, u1 - (u1 - u0) * offset, &mut ring);
1701 }
1702 }
1703 if ring.distance_squared < best.distance_squared {
1704 best = ring;
1705 }
1706 let polished = surface_newton(
1707 surface,
1708 point,
1709 ring.u,
1710 ring.v,
1711 [u0, u1, v0, v1],
1712 closed_u,
1713 closed_v,
1714 )?;
1715 if polished.distance_squared < best.distance_squared {
1716 best = polished;
1717 }
1718 }
1719 }
1720 Ok(best)
1721}
1722
1723fn global_stage_enabled() -> bool {
1728 switch!("BREP_PROJECTION_GLOBAL", true)
1729}
1730
1731pub fn global_site_filter_active() -> bool {
1740 static ACTIVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1745 *ACTIVE.get_or_init(|| {
1746 std::env::var_os("BREP_PROJECTION_GLOBAL_SITES").is_some() || std::env::var_os("BREP_PROJECTION_GLOBAL_EXCEPT").is_some()
1747 })
1748}
1749
1750fn global_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
1751 fn list(name: &str) -> Option<Vec<String>> {
1752 std::env::var(name)
1753 .ok()
1754 .map(|value| value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect())
1755 }
1756 static SITES: std::sync::OnceLock<(Option<Vec<String>>, Option<Vec<String>>)> =
1757 std::sync::OnceLock::new();
1758 let (only, except) = SITES.get_or_init(|| {
1759 (list("BREP_PROJECTION_GLOBAL_SITES"), list("BREP_PROJECTION_GLOBAL_EXCEPT"))
1760 });
1761 if only.is_none() && except.is_none() {
1762 return true;
1763 }
1764 let location = format!("{}:{}", caller.file(), caller.line());
1765 let named = |sites: &Vec<String>| sites.iter().any(|site| location.contains(site.as_str()));
1766 only.as_ref().is_none_or(named) && !except.as_ref().is_some_and(named)
1767}
1768
1769fn audit_record(caller: &std::panic::Location<'_>, surface: &NurbsSurface, local: &NewtonResult, global: &NewtonResult) {
1775 use std::io::Write;
1776 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1777 std::sync::OnceLock::new();
1778 let sink = SINK.get_or_init(|| {
1779 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1780 let path = std::path::Path::new(&directory)
1781 .join(format!("projection-audit-{}.tsv", std::process::id()));
1782 std::fs::OpenOptions::new()
1783 .create(true)
1784 .append(true)
1785 .open(path)
1786 .ok()
1787 .map(std::sync::Mutex::new)
1788 });
1789 if let Some(file) = sink {
1790 if let Ok(mut file) = file.lock() {
1791 let _ = writeln!(
1792 file,
1793 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{}x{} cp {}x{}",
1794 caller.file(),
1795 caller.line(),
1796 local.distance_squared.sqrt(),
1797 global.distance_squared.sqrt(),
1798 local.u,
1799 local.v,
1800 global.u,
1801 global.v,
1802 surface.degree_u,
1803 surface.degree_v,
1804 surface.control_points.len(),
1805 surface.control_points.first().map(Vec::len).unwrap_or(0),
1806 );
1807 }
1808 }
1809}
1810
1811#[track_caller]
1887pub fn project_point_to_surface_general(
1888 surface: &NurbsSurface,
1889 point: Vec3,
1890) -> Result<SurfaceProjection, String> {
1891 if !surface_projection_memo_enabled() || !surface_projection_memo_admitted() {
1892 return project_point_to_surface_general_fresh(surface, point);
1893 }
1894 let key = (surface.content_key(), [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()], forced_switches_key());
1895 if let Some(hit) = SURFACE_PROJECTION_MEMO.with(|memo| memo.borrow().get(&key).copied()) {
1896 if surface_projection_memo_check() {
1897 let fresh = project_point_to_surface_general_fresh(surface, point)?;
1898 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()];
1899 assert_eq!(bits(&hit), bits(&fresh), "surface projection memo check: held {hit:?} vs fresh {fresh:?}");
1900 }
1901 return Ok(hit);
1902 }
1903 let answer = project_point_to_surface_general_fresh(surface, point)?;
1904 SURFACE_PROJECTION_MEMO.with(|memo| {
1905 let mut memo = memo.borrow_mut();
1906 if memo.len() >= SURFACE_PROJECTION_MEMO_ENTRIES {
1907 memo.clear();
1908 }
1909 memo.insert(key, answer);
1910 });
1911 Ok(answer)
1912}
1913
1914fn surface_projection_memo_enabled() -> bool {
1927 switch!("BREP_SURFACE_PROJECTION_MEMO", true)
1928}
1929
1930fn surface_projection_memo_check() -> bool {
1931 switch!("BREP_SURFACE_PROJECTION_MEMO_CHECK", false)
1932}
1933
1934fn surface_projection_memo_admitted() -> bool {
1938 static CALLER_FREE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1939 crate::env_read::read_once_enabled() && *CALLER_FREE.get_or_init(|| {
1940 env_read!("BREP_PROJECTION_GLOBAL_SITES").is_none()
1941 && env_read!("BREP_PROJECTION_GLOBAL_EXCEPT").is_none()
1942 && env_read!("BREP_PROJECTION_AUDIT").is_none()
1943 })
1944}
1945
1946fn forced_switches_key() -> u64 {
1950 0
1951}
1952
1953const SURFACE_PROJECTION_MEMO_ENTRIES: usize = 1 << 14;
1959
1960thread_local! {
1961 static SURFACE_PROJECTION_MEMO: std::cell::RefCell<rustc_hash::FxHashMap<([u64; 2], [u64; 3], u64), SurfaceProjection>> = Default::default();
1962}
1963
1964#[track_caller]
1965fn project_point_to_surface_general_fresh(
1966 surface: &NurbsSurface,
1967 point: Vec3,
1968) -> Result<SurfaceProjection, String> {
1969 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_GENERAL, surface);
1970 let [u0, u1] = surface.domain_u()?;
1971 let [v0, v1] = surface.domain_v()?;
1972 let (closed_u, closed_v) = surface.closed_directions()?;
1973 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1974 let mut best = local;
1975 if global_stage_enabled() {
1976 global_minimum(
1977 surface,
1978 point,
1979 [u0, u1, v0, v1],
1980 (closed_u, closed_v),
1981 &mut best,
1982 &mut GlobalStats::default(),
1983 )?;
1984 if best.u != local.u || best.v != local.v {
1985 let caller = std::panic::Location::caller();
1986 if global_answer_admitted(caller) {
1987 audit_record(caller, surface, &local, &best);
1988 } else {
1989 best = local;
1990 }
1991 }
1992 }
1993 let projected = surface.evaluate(best.u, best.v)?;
1994 Ok(SurfaceProjection {
1995 u: best.u,
1996 v: best.v,
1997 point: projected,
1998 distance: projected.sub(point).length(),
1999 })
2000}
2001
2002pub fn project_point_to_surface_from_nearest_seed(
2012 surface: &NurbsSurface,
2013 point: Vec3,
2014) -> Result<SurfaceProjection, String> {
2015 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_NEAREST_SEED, surface);
2016 if let Some(analytic) = surface.analytic() {
2017 if let Some(projection) = analytic.project(surface, point) {
2018 return Ok(projection);
2019 }
2020 }
2021 if let Some(ellipsoid) = surface.affine_sphere() {
2022 if let Some(projection) = ellipsoid.project(surface, point) {
2023 return Ok(projection);
2024 }
2025 }
2026 let [u0, u1] = surface.domain_u()?;
2027 let [v0, v1] = surface.domain_v()?;
2028 let (closed_u, closed_v) = surface.closed_directions()?;
2029 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
2030 let projected = surface.evaluate(local.u, local.v)?;
2031 Ok(SurfaceProjection {
2032 u: local.u,
2033 v: local.v,
2034 point: projected,
2035 distance: projected.sub(point).length(),
2036 })
2037}
2038
2039#[doc(hidden)]
2042pub fn project_point_to_surface_general_lanes(
2043 surface: &NurbsSurface,
2044 point: Vec3,
2045 run_global: bool,
2046) -> Result<(SurfaceProjection, GlobalStats), String> {
2047 let [u0, u1] = surface.domain_u()?;
2048 let [v0, v1] = surface.domain_v()?;
2049 let (closed_u, closed_v) = surface.closed_directions()?;
2050 let mut best = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
2051 let mut stats = GlobalStats::default();
2052 if run_global {
2053 global_minimum(surface, point, [u0, u1, v0, v1], (closed_u, closed_v), &mut best, &mut stats)?;
2054 }
2055 let projected = surface.evaluate(best.u, best.v)?;
2056 Ok((
2057 SurfaceProjection {
2058 u: best.u,
2059 v: best.v,
2060 point: projected,
2061 distance: projected.sub(point).length(),
2062 },
2063 stats,
2064 ))
2065}
2066
2067#[doc(hidden)]
2070#[derive(Clone, Debug, Default)]
2071pub struct BasinCensus {
2072 pub cells: usize,
2075 pub descents: usize,
2077 pub unconverged: usize,
2079 pub cells_with_two_basins: usize,
2083 pub foot_cells_with_two_basins: usize,
2086 pub least: f64,
2088 pub least_uv: (f64, f64),
2089 pub foot_cell_descents: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)>,
2093}
2094
2095#[doc(hidden)]
2100pub fn project_point_to_surface_basin_census(
2101 surface: &NurbsSurface,
2102 point: Vec3,
2103 answer_distance: f64,
2104 bar: f64,
2105) -> Result<BasinCensus, String> {
2106 let mut census = BasinCensus {
2107 least: f64::INFINITY,
2108 ..BasinCensus::default()
2109 };
2110 let Some(cells) = projection_cells(surface)? else {
2111 return Ok(census);
2112 };
2113 let columns = cells.vs.len() - 1;
2114 let mut spreads: Vec<(usize, f64)> = Vec::new();
2115 let mut runs: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)> = Vec::new();
2116 for (cell, cell_box) in cells.boxes.iter().enumerate() {
2117 if cell_box.lower_bound(point) >= answer_distance {
2118 continue;
2119 }
2120 census.cells += 1;
2121 let (row, column) = (cell / columns, cell % columns);
2122 let rectangle = [cells.us[row], cells.us[row + 1], cells.vs[column], cells.vs[column + 1]];
2123 let middle = ((rectangle[0] + rectangle[1]) * 0.5, (rectangle[2] + rectangle[3]) * 0.5);
2124 let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
2125 for seed in [
2126 (rectangle[0], rectangle[2]),
2127 (rectangle[1], rectangle[2]),
2128 (rectangle[0], rectangle[3]),
2129 (rectangle[1], rectangle[3]),
2130 middle,
2131 ] {
2132 census.descents += 1;
2133 let (found, _) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2134 let distance = found.distance_squared.sqrt();
2135 runs.push((cell, rectangle, seed, (found.u, found.v), distance, found.converged));
2136 if distance < census.least {
2137 census.least = distance;
2138 census.least_uv = (found.u, found.v);
2139 }
2140 if !found.converged {
2141 census.unconverged += 1;
2142 continue;
2143 }
2144 low = low.min(distance.max(LINEAR_TOLERANCE));
2145 high = high.max(distance.max(LINEAR_TOLERANCE));
2146 }
2147 if high - low > bar {
2148 spreads.push((cell, high - low));
2149 }
2150 }
2151 census.cells_with_two_basins = spreads.len();
2152 let (u, v) = census.least_uv;
2153 let foot_cells: Vec<usize> = spreads
2154 .iter()
2155 .map(|&(cell, _)| cell)
2156 .filter(|&cell| {
2157 let (row, column) = (cell / columns, cell % columns);
2158 cells.us[row] <= u && u <= cells.us[row + 1] && cells.vs[column] <= v && v <= cells.vs[column + 1]
2159 })
2160 .collect();
2161 census.foot_cells_with_two_basins = foot_cells.len();
2162 census.foot_cell_descents = runs.into_iter().filter(|run| foot_cells.contains(&run.0)).collect();
2163 Ok(census)
2164}
2165
2166#[doc(hidden)]
2168#[derive(Clone, Copy, Debug, Default)]
2169pub struct GlobalStats {
2170 pub settled_by_floor: bool,
2172 pub candidates: usize,
2174 pub refinements: usize,
2176 pub continuations: usize,
2178 pub replaced: bool,
2180 pub hull_lower_bound: f64,
2183}
2184
2185#[derive(Clone, Debug)]
2188struct CellBox {
2189 axes: [Vec3; 3],
2190 low: [f64; 3],
2191 high: [f64; 3],
2192}
2193
2194impl CellBox {
2195 fn lower_bound(&self, point: Vec3) -> f64 {
2198 let mut squared = 0.0;
2199 for axis in 0..3 {
2200 let coordinate = point.dot(self.axes[axis]);
2201 let excess = (self.low[axis] - coordinate).max(coordinate - self.high[axis]).max(0.0);
2202 squared += excess * excess;
2203 }
2204 squared.sqrt()
2205 }
2206}
2207
2208#[derive(Clone, Copy, Debug)]
2211struct CellTreeNode {
2212 centre: Vec3,
2213 radius: f64,
2214 children: Option<(u32, u32)>,
2215 cell: u32,
2216}
2217
2218#[derive(Clone, Debug)]
2224pub struct ProjectionCells {
2225 us: std::sync::Arc<[f64]>,
2226 vs: std::sync::Arc<[f64]>,
2227 nodes: std::sync::Arc<[Vec3]>,
2229 boxes: std::sync::Arc<[CellBox]>,
2231 tree: std::sync::Arc<[CellTreeNode]>,
2233 node_boxes: std::sync::Arc<[CellBox]>,
2237 node_margin: f64,
2239 scale: f64,
2241 resolution: f64,
2242 split: [usize; 2],
2246 sub_nodes: std::sync::Arc<std::sync::Mutex<rustc_hash::FxHashMap<(u32, u32), Vec3>>>,
2250 sub_boxes: std::sync::Arc<std::sync::Mutex<rustc_hash::FxHashMap<usize, Option<CellBox>>>>,
2255 samples: [usize; 2],
2257}
2258
2259fn lattice_parameters(knots: &[f64], degree: usize, closed: bool) -> Vec<f64> {
2263 lattice_parameters_at(knots, degree, closed, false)
2264}
2265
2266fn lattice_samples(degree: usize, closed: bool, coarse: bool) -> usize {
2271 if closed {
2272 8usize.max(degree * 4)
2273 } else if coarse && degree >= 4 {
2274 COARSE_SAMPLES
2275 } else {
2276 3usize.max(degree + 1)
2277 }
2278}
2279
2280fn coarse_split(degree: usize, closed: bool, coarse: bool) -> usize {
2284 if coarse && !closed && degree >= 4 { (degree + 1).div_ceil(COARSE_SAMPLES) } else { 1 }
2285}
2286
2287fn lattice_parameters_at(knots: &[f64], degree: usize, closed: bool, coarse: bool) -> Vec<f64> {
2288 let [start, end] = crate::curve::knot_domain(knots, degree);
2289 let samples = lattice_samples(degree, closed, coarse);
2290 let mut breaks = vec![start];
2291 breaks.extend(interior_knots(knots, degree));
2292 breaks.push(end);
2293 let mut parameters = Vec::with_capacity((breaks.len() - 1) * samples + 1);
2294 for pair in breaks.windows(2) {
2295 for index in 0..samples {
2296 parameters.push(pair[0] + (pair[1] - pair[0]) * index as f64 / samples as f64);
2297 }
2298 }
2299 parameters.push(end);
2300 parameters
2301}
2302
2303fn refine_to_lattice(net: &mut Vec<Vec<Vec4>>, knots: &mut Vec<f64>, degree: usize, parameters: &[f64]) {
2312 let p = degree;
2313 let n = net.len() - 1;
2314 let mut inserted = Vec::new();
2315 for ¶meter in parameters {
2316 let multiplicity = knots.iter().filter(|&&knot| knot == parameter).count();
2317 for _ in multiplicity..p {
2318 inserted.push(parameter);
2319 }
2320 }
2321 if inserted.is_empty() || p == 0 {
2322 return;
2323 }
2324 inserted.sort_by(f64::total_cmp);
2325 let find_span = |parameter: f64| -> usize {
2326 if parameter >= knots[n + 1] {
2327 return n;
2328 }
2329 (knots.partition_point(|&knot| knot <= parameter) - 1).clamp(p, n)
2330 };
2331 let r = inserted.len() - 1;
2332 let m = n + p + 1;
2333 let a = find_span(inserted[0]);
2334 let b = find_span(inserted[r]) + 1;
2335 let columns = net[0].len();
2336 let blank = vec![
2337 Vec4 {
2338 x: 0.0,
2339 y: 0.0,
2340 z: 0.0,
2341 w: 0.0,
2342 };
2343 columns
2344 ];
2345 let mut refined = vec![blank; n + r + 2];
2346 let mut refined_knots = vec![0.0; m + r + 2];
2347 for j in 0..=a - p {
2348 refined[j] = net[j].clone();
2349 }
2350 for j in b - 1..=n {
2351 refined[j + r + 1] = net[j].clone();
2352 }
2353 refined_knots[..=a].copy_from_slice(&knots[..=a]);
2354 for j in b + p..=m {
2355 refined_knots[j + r + 1] = knots[j];
2356 }
2357 let mut i = b + p - 1;
2358 let mut k = b + p + r;
2359 for j in (0..=r).rev() {
2360 while inserted[j] <= knots[i] && i > a {
2361 refined[k - p - 1] = net[i - p - 1].clone();
2362 refined_knots[k] = knots[i];
2363 k -= 1;
2364 i -= 1;
2365 }
2366 refined[k - p - 1] = refined[k - p].clone();
2367 for l in 1..=p {
2368 let index = k - p + l;
2369 let numerator = refined_knots[k + l] - inserted[j];
2370 if numerator == 0.0 {
2371 refined[index - 1] = refined[index].clone();
2372 } else {
2373 let alpha = numerator / (refined_knots[k + l] - knots[i - p + l]);
2374 let (head, tail) = refined.split_at_mut(index);
2375 for (before, &here) in head[index - 1].iter_mut().zip(&tail[0]) {
2376 *before = before.scale(alpha).add(here.scale(1.0 - alpha));
2377 }
2378 }
2379 }
2380 refined_knots[k] = inserted[j];
2381 k = k.saturating_sub(1);
2382 }
2383 *net = refined;
2384 *knots = refined_knots;
2385}
2386
2387fn supporting_range(knots: &[f64], degree: usize, count: usize, low: f64, high: f64) -> (usize, usize) {
2390 let first_span = knots.partition_point(|&knot| knot <= low).saturating_sub(1);
2391 let last_span = knots.partition_point(|&knot| knot < high).saturating_sub(1);
2392 (
2393 first_span.saturating_sub(degree).min(count - 1),
2394 last_span.max(first_span).min(count - 1),
2395 )
2396}
2397
2398fn unit_or(vector: Vec3, fallback: Vec3) -> Vec3 {
2399 let length = vector.length();
2400 if length > 0.0 && length.is_finite() {
2401 vector.scale(1.0 / length)
2402 } else {
2403 fallback
2404 }
2405}
2406
2407fn enclosing_sphere(a: (Vec3, f64), b: (Vec3, f64)) -> (Vec3, f64) {
2408 let offset = b.0.sub(a.0);
2409 let separation = offset.length();
2410 if separation + b.1 <= a.1 {
2411 return a;
2412 }
2413 if separation + a.1 <= b.1 {
2414 return b;
2415 }
2416 let radius = (separation + a.1 + b.1) * 0.5;
2417 let centre = a.0.add(offset.scale((radius - a.1) / separation));
2418 (centre, radius)
2419}
2420
2421struct NodeBoxInputs<'a> {
2425 boxes: &'a [CellBox],
2426 nodes: &'a [Vec3],
2427 lattice_columns: usize,
2428 margin: f64,
2429}
2430
2431fn framed_box(points: &[Vec3], columns: usize, margin: f64) -> Option<CellBox> {
2435 if columns == 0 || points.len() < columns || points.len() % columns != 0 {
2436 return None;
2437 }
2438 let last = points.len() - columns;
2439 let (c00, c01, c10, c11) = (points[0], points[columns - 1], points[last], points[last + columns - 1]);
2440 let along_u = c10.sub(c00).add(c11.sub(c01));
2441 let along_v = c01.sub(c00).add(c11.sub(c10));
2442 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2443 let fallback = e1.perpendicular().ok()?;
2444 let normal = unit_or(e1.cross(along_v), fallback);
2445 let e2 = unit_or(normal.cross(e1), fallback);
2446 let e3 = e1.cross(e2);
2447 let axes = [e1, e2, e3];
2448 let mut low = [f64::INFINITY; 3];
2449 let mut high = [f64::NEG_INFINITY; 3];
2450 for point in points {
2451 for axis in 0..3 {
2452 let coordinate = point.dot(axes[axis]);
2453 low[axis] = low[axis].min(coordinate);
2454 high[axis] = high[axis].max(coordinate);
2455 }
2456 }
2457 for axis in 0..3 {
2458 low[axis] -= margin;
2459 high[axis] += margin;
2460 }
2461 low.iter().chain(high.iter()).all(|value| value.is_finite()).then_some(CellBox { axes, low, high })
2462}
2463
2464fn enclosing_node_box(corners: [Vec3; 4], children: [&CellBox; 2], margin: f64) -> CellBox {
2469 let unbounded = || CellBox {
2470 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)],
2471 low: [f64::NEG_INFINITY; 3],
2472 high: [f64::INFINITY; 3],
2473 };
2474 let [c00, c10, c01, c11] = corners;
2475 let along_u = c10.sub(c00).add(c11.sub(c01));
2476 let along_v = c01.sub(c00).add(c11.sub(c10));
2477 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2478 let Ok(fallback) = e1.perpendicular() else {
2479 return unbounded();
2480 };
2481 let normal = unit_or(e1.cross(along_v), fallback);
2482 let e2 = unit_or(normal.cross(e1), fallback);
2483 let e3 = e1.cross(e2);
2484 let axes = [e1, e2, e3];
2485 let mut low = [f64::INFINITY; 3];
2486 let mut high = [f64::NEG_INFINITY; 3];
2487 for child in children {
2488 for corner in 0..8 {
2489 let mut point = Vec3::default();
2490 for axis in 0..3 {
2491 let value = if corner >> axis & 1 == 0 { child.low[axis] } else { child.high[axis] };
2492 point = point.add(child.axes[axis].scale(value));
2493 }
2494 for axis in 0..3 {
2495 let coordinate = point.dot(axes[axis]);
2496 low[axis] = low[axis].min(coordinate);
2497 high[axis] = high[axis].max(coordinate);
2498 }
2499 }
2500 }
2501 for axis in 0..3 {
2502 low[axis] -= margin;
2503 high[axis] += margin;
2504 }
2505 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2506 return unbounded();
2507 }
2508 CellBox { axes, low, high }
2509}
2510
2511fn build_cell_tree(
2512 tree: &mut Vec<CellTreeNode>,
2513 node_boxes: &mut Vec<CellBox>,
2514 inputs: &NodeBoxInputs<'_>,
2515 spheres: &[(Vec3, f64)],
2516 columns: usize,
2517 [row_low, row_high, column_low, column_high]: [usize; 4],
2518) -> u32 {
2519 if row_high - row_low == 1 && column_high - column_low == 1 {
2520 let cell = row_low * columns + column_low;
2521 node_boxes.push(inputs.boxes[cell].clone());
2522 tree.push(CellTreeNode {
2523 centre: spheres[cell].0,
2524 radius: spheres[cell].1,
2525 children: None,
2526 cell: cell as u32,
2527 });
2528 return (tree.len() - 1) as u32;
2529 }
2530 let (first, second) = if row_high - row_low >= column_high - column_low {
2531 let middle = (row_low + row_high) / 2;
2532 (
2533 [row_low, middle, column_low, column_high],
2534 [middle, row_high, column_low, column_high],
2535 )
2536 } else {
2537 let middle = (column_low + column_high) / 2;
2538 (
2539 [row_low, row_high, column_low, middle],
2540 [row_low, row_high, middle, column_high],
2541 )
2542 };
2543 let first = build_cell_tree(tree, node_boxes, inputs, spheres, columns, first);
2544 let second = build_cell_tree(tree, node_boxes, inputs, spheres, columns, second);
2545 let a = tree[first as usize];
2546 let b = tree[second as usize];
2547 let lattice = |row: usize, column: usize| inputs.nodes[row * inputs.lattice_columns + column];
2548 node_boxes.push(enclosing_node_box(
2549 [
2550 lattice(row_low, column_low),
2551 lattice(row_high, column_low),
2552 lattice(row_low, column_high),
2553 lattice(row_high, column_high),
2554 ],
2555 [&node_boxes[first as usize], &node_boxes[second as usize]],
2556 inputs.margin,
2557 ));
2558 let (centre, radius) = enclosing_sphere((a.centre, a.radius), (b.centre, b.radius));
2562 tree.push(CellTreeNode {
2563 centre,
2564 radius: radius * (1.0 + 4.0 * f64::EPSILON),
2565 children: Some((first, second)),
2566 cell: u32::MAX,
2567 });
2568 (tree.len() - 1) as u32
2569}
2570
2571fn projection_cells(surface: &NurbsSurface) -> Result<Option<&ProjectionCells>, String> {
2572 if let Some(cells) = surface.projection_cells.get() {
2573 return Ok(cells.as_ref());
2574 }
2575 let cells = build_projection_cells_at(surface, coarse_lattice_enabled())?;
2576 Ok(surface.projection_cells.get_or_init(|| cells).as_ref())
2577}
2578
2579const COARSE_SAMPLES: usize = 3;
2585
2586fn coarse_lattice_enabled() -> bool {
2596 coarse_lattice_check() || crate::switch!("BREP_PROJECTION_COARSE_LATTICE", true)
2597}
2598
2599fn coarse_lattice_check() -> bool {
2600 crate::switch!("BREP_PROJECTION_COARSE_LATTICE_CHECK", false)
2601}
2602
2603fn coarse_check_bar(resolution: f64) -> f64 {
2607 LINEAR_TOLERANCE.max(16.0 * resolution)
2608}
2609
2610thread_local! {
2611 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());
2613}
2614
2615fn default_cells_for_check(surface: &NurbsSurface) -> Result<std::rc::Rc<Option<ProjectionCells>>, String> {
2616 let key = surface.content_key();
2617 if let Some(cells) = DEFAULT_CELLS_FOR_CHECK.with(|map| map.borrow().get(&key).cloned()) {
2618 return Ok(cells);
2619 }
2620 let cells = std::rc::Rc::new(build_projection_cells_at(surface, false)?);
2621 DEFAULT_CELLS_FOR_CHECK.with(|map| {
2622 let mut map = map.borrow_mut();
2623 if map.len() >= 256 { map.clear(); }
2625 map.insert(key, cells.clone());
2626 });
2627 Ok(cells)
2628}
2629
2630fn build_projection_cells(surface: &NurbsSurface) -> Result<Option<ProjectionCells>, String> {
2631 build_projection_cells_at(surface, false)
2632}
2633
2634fn build_projection_cells_at(surface: &NurbsSurface, coarse: bool) -> Result<Option<ProjectionCells>, String> {
2635 let (closed_u, closed_v) = surface.closed_directions()?;
2636 let us = lattice_parameters_at(&surface.knots_u, surface.degree_u, closed_u, coarse);
2637 let vs = lattice_parameters_at(&surface.knots_v, surface.degree_v, closed_v, coarse);
2638 if us.len() < 2 || vs.len() < 2 {
2639 return Ok(None);
2640 }
2641 let mut scale = 0.0f64;
2642 for control in surface.control_points.iter().flatten() {
2643 let point = control.point()?;
2644 scale = scale.max(point.x.abs()).max(point.y.abs()).max(point.z.abs());
2645 }
2646 let resolution =
2647 ((surface.degree_u + 1) * (surface.degree_v + 1)) as f64 * f64::EPSILON * scale;
2648
2649 let mut net = surface.control_points.clone();
2651 let mut knots_u = surface.knots_u.clone();
2652 refine_to_lattice(&mut net, &mut knots_u, surface.degree_u, &us);
2653 let columns = net.first().map(Vec::len).unwrap_or(0);
2654 let mut transposed: Vec<Vec<Vec4>> =
2655 (0..columns).map(|column| net.iter().map(|row| row[column]).collect()).collect();
2656 let mut knots_v = surface.knots_v.clone();
2657 refine_to_lattice(&mut transposed, &mut knots_v, surface.degree_v, &vs);
2658 let rows = transposed.first().map(Vec::len).unwrap_or(0);
2659 let columns = transposed.len();
2660 if rows == 0 || columns == 0 {
2661 return Ok(None);
2662 }
2663 let split = [coarse_split(surface.degree_u, closed_u, coarse), coarse_split(surface.degree_v, closed_v, coarse)];
2664 let mut points = vec![Vec3::default(); rows * columns];
2665 for (column, fibre) in transposed.iter().enumerate() {
2666 for (row, control) in fibre.iter().enumerate() {
2667 points[row * columns + column] = control.point()?;
2668 }
2669 }
2670
2671 let mut nodes = Vec::with_capacity(us.len() * vs.len());
2672 for &u in &us {
2673 for &v in &vs {
2674 nodes.push(surface.evaluate(u, v)?);
2675 }
2676 }
2677
2678 let cell_rows = us.len() - 1;
2679 let cell_columns = vs.len() - 1;
2680 let mut boxes = Vec::with_capacity(cell_rows * cell_columns);
2681 let mut spheres = Vec::with_capacity(cell_rows * cell_columns);
2682 for i in 0..cell_rows {
2683 let (row_low, row_high) =
2684 supporting_range(&knots_u, surface.degree_u, rows, us[i], us[i + 1]);
2685 for j in 0..cell_columns {
2686 let (column_low, column_high) =
2687 supporting_range(&knots_v, surface.degree_v, columns, vs[j], vs[j + 1]);
2688 let at = |row: usize, column: usize| points[row * columns + column];
2689 let c00 = at(row_low, column_low);
2690 let c10 = at(row_high, column_low);
2691 let c01 = at(row_low, column_high);
2692 let c11 = at(row_high, column_high);
2693 let along_u = c10.sub(c00).add(c11.sub(c01));
2694 let along_v = c01.sub(c00).add(c11.sub(c10));
2695 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2696 let normal = unit_or(e1.cross(along_v), e1.perpendicular()?);
2697 let e2 = unit_or(normal.cross(e1), e1.perpendicular()?);
2698 let e3 = e1.cross(e2);
2699 let axes = [e1, e2, e3];
2700 let mut low = [f64::INFINITY; 3];
2701 let mut high = [f64::NEG_INFINITY; 3];
2702 for row in row_low..=row_high {
2703 for column in column_low..=column_high {
2704 let point = at(row, column);
2705 for axis in 0..3 {
2706 let coordinate = point.dot(axes[axis]);
2707 low[axis] = low[axis].min(coordinate);
2708 high[axis] = high[axis].max(coordinate);
2709 }
2710 }
2711 }
2712 for axis in 0..3 {
2713 low[axis] -= resolution;
2714 high[axis] += resolution;
2715 }
2716 let mut centre = Vec3::default();
2717 let mut half_diagonal_squared = 0.0;
2718 for axis in 0..3 {
2719 centre = centre.add(axes[axis].scale((low[axis] + high[axis]) * 0.5));
2720 let half = (high[axis] - low[axis]) * 0.5;
2721 half_diagonal_squared += half * half;
2722 }
2723 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2724 return Ok(None);
2725 }
2726 spheres.push((centre, half_diagonal_squared.sqrt() + resolution));
2727 boxes.push(CellBox { axes, low, high });
2728 }
2729 }
2730 let mut tree = Vec::with_capacity(2 * boxes.len());
2731 let mut node_boxes = Vec::with_capacity(2 * boxes.len());
2732 let node_margin = NODE_BOX_MARGIN * scale;
2737 let inputs = NodeBoxInputs { boxes: &boxes, nodes: &nodes, lattice_columns: vs.len(), margin: node_margin };
2738 build_cell_tree(&mut tree, &mut node_boxes, &inputs, &spheres, cell_columns, [0, cell_rows, 0, cell_columns]);
2739 if !(node_margin > 0.0 && node_margin.is_finite()) {
2740 node_boxes = Vec::new();
2741 }
2742 Ok(Some(ProjectionCells {
2743 us: us.into(),
2744 vs: vs.into(),
2745 nodes: nodes.into(),
2746 boxes: boxes.into(),
2747 tree: tree.into(),
2748 node_boxes: node_boxes.into(),
2749 node_margin,
2750 scale,
2751 resolution,
2752 split,
2753 sub_nodes: Default::default(),
2754 sub_boxes: Default::default(),
2755 samples: [
2756 lattice_samples(surface.degree_u, closed_u, coarse),
2757 lattice_samples(surface.degree_v, closed_v, coarse),
2758 ],
2759 }))
2760}
2761
2762fn optimality(
2767 derivatives: &[[Vec3; 3]; 3],
2768 point: Vec3,
2769 (u, v): (f64, f64),
2770 [ua, ub, va, vb]: [f64; 4],
2771 periodic: (bool, bool),
2772) -> Optimality {
2773 let residual = derivatives[0][0].sub(point);
2774 let residual_length = residual.length();
2775 let su = derivatives[1][0];
2776 let sv = derivatives[0][1];
2777 let f = su.dot(residual);
2778 let g = sv.dot(residual);
2779 let metric_u = su.length_squared();
2780 let metric_v = sv.length_squared();
2781 let stationary_u = metric_u.sqrt() * residual_length <= EPSILON
2782 || f.abs() <= 1e-10 * metric_u.sqrt() * residual_length;
2783 let stationary_v = metric_v.sqrt() * residual_length <= EPSILON
2784 || g.abs() <= 1e-10 * metric_v.sqrt() * residual_length;
2785 let pinned_u = !periodic.0 && ((u <= ua && f > 0.0) || (u >= ub && f < 0.0));
2786 let pinned_v = !periodic.1 && ((v <= va && g > 0.0) || (v >= vb && g < 0.0));
2787 let j00 = derivatives[2][0].dot(residual) + metric_u;
2788 let j01 = derivatives[1][1].dot(residual) + su.dot(sv);
2789 let j11 = derivatives[0][2].dot(residual) + metric_v;
2790 let determinant = j00 * j11 - j01 * j01;
2791 let convex = match (!pinned_u, !pinned_v) {
2792 (true, true) => j00 > 0.0 && determinant > 0.0,
2793 (true, false) => j00 > 0.0,
2794 (false, true) => j11 > 0.0,
2795 (false, false) => true,
2796 };
2797 Optimality {
2798 residual_length,
2799 gradient: (f, g),
2800 metric: (metric_u, metric_v),
2801 hessian: (j00, j01, j11),
2802 determinant,
2803 pinned: (pinned_u, pinned_v),
2804 convex,
2805 minimum: residual_length <= LINEAR_TOLERANCE
2806 || ((stationary_u || pinned_u) && (stationary_v || pinned_v) && convex),
2807 }
2808}
2809
2810struct Optimality {
2811 residual_length: f64,
2812 gradient: (f64, f64),
2813 metric: (f64, f64),
2814 hessian: (f64, f64, f64),
2815 determinant: f64,
2816 pinned: (bool, bool),
2817 convex: bool,
2818 minimum: bool,
2819}
2820
2821fn is_verified_minimum(
2822 surface: &NurbsSurface,
2823 point: Vec3,
2824 at: (f64, f64),
2825 rectangle: [f64; 4],
2826 periodic: (bool, bool),
2827) -> Result<bool, String> {
2828 let derivatives = surface.derivatives_small(at.0, at.1, 2)?;
2829 Ok(optimality(&derivatives, point, at, rectangle, periodic).minimum)
2830}
2831
2832fn confined_descent(
2848 surface: &NurbsSurface,
2849 point: Vec3,
2850 seed: (f64, f64),
2851 rectangle: [f64; 4],
2852 periodic: (bool, bool),
2853) -> Result<(NewtonResult, bool), String> {
2854 let [ua, ub, va, vb] = rectangle;
2855 let mut u = fit_parameter(seed.0, ua, ub, periodic.0);
2856 let mut v = fit_parameter(seed.1, va, vb, periodic.1);
2857 let mut converged = false;
2858 let mut current = surface.evaluate(u, v)?.sub(point).length_squared();
2859 for _ in 0..MAX_NEWTON_ITERATIONS {
2860 let derivatives = surface.derivatives_small(u, v, 2)?;
2861 let state = optimality(&derivatives, point, (u, v), rectangle, periodic);
2862 current = state.residual_length * state.residual_length;
2863 if state.minimum {
2864 converged = true;
2865 break;
2866 }
2867 let (f, g) = state.gradient;
2868 let (metric_u, metric_v) = state.metric;
2869 let (j00, j01, j11) = state.hessian;
2870 let determinant = state.determinant;
2871 let (free_u, free_v) = (!state.pinned.0, !state.pinned.1);
2872 let (mut du, mut dv) = match (free_u, free_v) {
2873 (true, true) if state.convex => (
2874 (-f * j11 + g * j01) / determinant,
2875 (-g * j00 + f * j01) / determinant,
2876 ),
2877 (true, false) if state.convex => (-f / j00, 0.0),
2878 (false, true) if state.convex => (0.0, -g / j11),
2879 _ => (
2880 if free_u && metric_u > 0.0 { -f / metric_u } else { 0.0 },
2881 if free_v && metric_v > 0.0 { -g / metric_v } else { 0.0 },
2882 ),
2883 };
2884 if !(du.is_finite() && dv.is_finite()) || (du == 0.0 && dv == 0.0) {
2885 break;
2886 }
2887 let mut moved = false;
2888 let taken = |next: f64, here: f64, low: f64, high: f64, wraps: bool| {
2890 let raw = next - here;
2891 if wraps {
2892 raw - (high - low) * (raw / (high - low)).round()
2893 } else {
2894 raw
2895 }
2896 };
2897 for _ in 0..40 {
2898 let next_u = fit_parameter(u + du, ua, ub, periodic.0);
2899 let next_v = fit_parameter(v + dv, va, vb, periodic.1);
2900 if next_u == u && next_v == v {
2901 break;
2902 }
2903 let trial = surface.evaluate(next_u, next_v)?.sub(point).length_squared();
2904 if trial <= current {
2905 moved = taken(next_u, u, ua, ub, periodic.0).abs() > 1e-15 * (ub - ua)
2906 || taken(next_v, v, va, vb, periodic.1).abs() > 1e-15 * (vb - va);
2907 u = next_u;
2908 v = next_v;
2909 current = trial;
2910 break;
2911 }
2912 du *= 0.5;
2913 dv *= 0.5;
2914 }
2915 if !moved {
2916 break;
2917 }
2918 }
2919 let result = NewtonResult {
2920 u,
2921 v,
2922 distance_squared: current,
2923 converged,
2924 };
2925 let on_edge =
2926 (!periodic.0 && (u <= ua || u >= ub)) || (!periodic.1 && (v <= va || v >= vb));
2927 Ok((result, on_edge))
2928}
2929
2930const NODE_BOX_MARGIN: f64 = 1e-9;
2933
2934fn node_boxes_enabled() -> bool {
2938 switch!("BREP_PROJECTION_NODE_BOXES", true)
2939}
2940
2941fn hull_candidates(cells: &ProjectionCells, point: Vec3, bound: f64, node_boxes: bool) -> (Vec<(f64, usize)>, f64) {
2962 let read_error = 32.0 * f64::EPSILON * (point.x.abs() + point.y.abs() + point.z.abs() + 4.0 * cells.scale);
2963 let boxes = node_boxes && !cells.node_boxes.is_empty() && 4.0 * read_error <= cells.node_margin;
2964 let mut candidates: Vec<(f64, usize)> = Vec::new();
2965 let mut excluded = f64::INFINITY;
2966 let mut stack: Vec<u32> = Vec::with_capacity(64);
2967 stack.push((cells.tree.len() - 1) as u32);
2968 while let Some(index) = stack.pop() {
2969 let node = cells.tree[index as usize];
2970 let sphere_bound = (point.sub(node.centre).length() - node.radius).max(0.0);
2971 if sphere_bound >= bound {
2972 excluded = excluded.min(sphere_bound);
2973 continue;
2974 }
2975 match node.children {
2976 Some((first, second)) => {
2977 if boxes {
2978 let box_bound = cells.node_boxes[index as usize].lower_bound(point);
2979 if box_bound >= bound && box_bound > 2.0 * read_error {
2980 excluded = excluded.min(box_bound);
2981 continue;
2982 }
2983 }
2984 stack.push(first);
2985 stack.push(second);
2986 }
2987 None => {
2988 let cell = node.cell as usize;
2989 let box_bound = cells.boxes[cell].lower_bound(point);
2990 if box_bound < bound {
2991 candidates.push((box_bound, cell));
2992 } else {
2993 excluded = excluded.min(box_bound);
2994 }
2995 }
2996 }
2997 }
2998 (candidates, excluded)
2999}
3000
3001#[allow(clippy::too_many_arguments)]
3004fn global_minimum(
3005 surface: &NurbsSurface,
3006 point: Vec3,
3007 domains: [f64; 4],
3008 periodic: (bool, bool),
3009 best: &mut NewtonResult,
3010 stats: &mut GlobalStats,
3011) -> Result<(), String> {
3012 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
3013 stats.settled_by_floor = true;
3014 return Ok(());
3015 }
3016 let Some(cells) = projection_cells(surface)? else {
3017 return Ok(());
3018 };
3019 if coarse_lattice_check() {
3020 let start = *best;
3021 global_minimum_with(surface, cells, point, domains, periodic, best, stats)?;
3022 if let Some(default) = default_cells_for_check(surface)?.as_ref() {
3023 let mut reference = start;
3024 global_minimum_with(surface, default, point, domains, periodic, &mut reference, &mut GlobalStats::default())?;
3025 let (coarse, fine) = (best.distance_squared.sqrt(), reference.distance_squared.sqrt());
3026 if coarse > fine + coarse_check_bar(default.resolution) {
3027 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);
3028 }
3029 }
3030 return Ok(());
3031 }
3032 global_minimum_with(surface, cells, point, domains, periodic, best, stats)
3033}
3034
3035#[allow(clippy::too_many_arguments)]
3037fn global_minimum_with(
3038 surface: &NurbsSurface,
3039 cells: &ProjectionCells,
3040 point: Vec3,
3041 domains: [f64; 4],
3042 periodic: (bool, bool),
3043 best: &mut NewtonResult,
3044 stats: &mut GlobalStats,
3045) -> Result<(), String> {
3046 let resolution = cells.resolution;
3047 let columns = cells.vs.len() - 1;
3048 let columns_u = cells.us.len() - 1;
3049 let mut bound = best.distance_squared.sqrt() - resolution;
3050
3051 let (mut candidates, excluded) = hull_candidates(cells, point, bound, node_boxes_enabled());
3054 stats.candidates = candidates.len();
3055 candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
3056 stats.hull_lower_bound = candidates
3057 .first()
3058 .map_or(excluded, |&(least, _)| least.min(excluded));
3059
3060 let cell_of = |u: f64, v: f64| {
3066 let row = (cells.us.partition_point(|&value| value <= u).max(1) - 1).min(columns_u - 1);
3067 let column = (cells.vs.partition_point(|&value| value <= v).max(1) - 1).min(columns - 1);
3068 row * columns + column
3069 };
3070 let mut settled: Vec<usize> = Vec::new();
3071 if is_verified_minimum(surface, point, (best.u, best.v), domains, periodic)? {
3072 settled.push(cell_of(best.u, best.v));
3073 }
3074 for (cell_bound, cell) in candidates {
3075 if cell_bound >= bound {
3076 break;
3077 }
3078 let row = cell / columns;
3079 let column = cell % columns;
3080 let rectangle = [
3081 cells.us[row],
3082 cells.us[row + 1],
3083 cells.vs[column],
3084 cells.vs[column + 1],
3085 ];
3086 if settled.contains(&cell) {
3087 continue;
3088 }
3089 if cells.split == [1, 1] {
3090 let mut seed = (rectangle[0], rectangle[2]);
3091 let mut seed_distance = f64::INFINITY;
3092 for (node_row, node_column) in
3093 [(row, column), (row + 1, column), (row, column + 1), (row + 1, column + 1)]
3094 {
3095 let distance = cells.nodes[node_row * cells.vs.len() + node_column]
3096 .sub(point)
3097 .length_squared();
3098 if distance < seed_distance {
3099 seed_distance = distance;
3100 seed = (cells.us[node_row], cells.vs[node_column]);
3101 }
3102 }
3103 if descend_cell(surface, point, seed, rectangle, domains, periodic, best, &mut bound, resolution, &mut settled, &cell_of, stats)? {
3104 return Ok(());
3105 }
3106 continue;
3107 }
3108 let [split_u, split_v] = cells.split;
3111 let at = |low: f64, high: f64, index: usize, count: usize| if index == count { high } else { low + (high - low) * index as f64 / count as f64 };
3112 for i in 0..split_u {
3113 for j in 0..split_v {
3114 let sub = [
3115 at(rectangle[0], rectangle[1], i, split_u),
3116 at(rectangle[0], rectangle[1], i + 1, split_u),
3117 at(rectangle[2], rectangle[3], j, split_v),
3118 at(rectangle[2], rectangle[3], j + 1, split_v),
3119 ];
3120 let index = (cell * split_u + i) * split_v + j;
3124 let cached = cells.sub_boxes.lock().ok().and_then(|boxes| boxes.get(&index).cloned());
3125 let hull = match cached {
3126 Some(hull) => hull,
3127 None => {
3128 let [su, sv] = cells.samples;
3129 let piece = |cell_index: usize, samples: usize, split: usize, sub: usize| {
3130 let (span, k) = (cell_index / samples, cell_index % samples);
3131 let steps = (samples * split) as f64;
3132 (span, [(k * split + sub) as f64 / steps, (k * split + sub + 1) as f64 / steps])
3133 };
3134 let (span_u, range_u) = piece(row, su, split_u, i);
3135 let (span_v, range_v) = piece(column, sv, split_v, j);
3136 let hull = crate::curve_clear::patch_piece_controls(surface, span_u, span_v, range_u, range_v)
3137 .and_then(|(controls, columns)| framed_box(&controls, columns, 64.0 * resolution));
3138 if let Ok(mut boxes) = cells.sub_boxes.lock() { boxes.insert(index, hull.clone()); }
3139 hull
3140 }
3141 };
3142 if let Some(hull) = hull {
3143 if hull.lower_bound(point) >= bound {
3144 continue;
3145 }
3146 }
3147 let mut seed = (sub[0], sub[2]);
3148 let mut seed_distance = f64::INFINITY;
3149 for (di, dj) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
3150 let (u, v) = (sub[di], sub[2 + dj]);
3151 let key = ((row * split_u + i + di) as u32, (column * split_v + j + dj) as u32);
3152 let cached = cells.sub_nodes.lock().ok().and_then(|nodes| nodes.get(&key).copied());
3153 let node = match cached {
3154 Some(node) => node,
3155 None => {
3156 let node = surface.evaluate(u, v)?;
3157 if let Ok(mut nodes) = cells.sub_nodes.lock() { nodes.insert(key, node); }
3158 node
3159 }
3160 };
3161 let distance = node.sub(point).length_squared();
3162 if distance < seed_distance {
3163 seed_distance = distance;
3164 seed = (u, v);
3165 }
3166 }
3167 if descend_cell(surface, point, seed, sub, domains, periodic, best, &mut bound, resolution, &mut settled, &cell_of, stats)? {
3168 return Ok(());
3169 }
3170 }
3171 }
3172 }
3173 Ok(())
3174}
3175
3176#[allow(clippy::too_many_arguments)]
3181fn descend_cell(
3182 surface: &NurbsSurface,
3183 point: Vec3,
3184 seed: (f64, f64),
3185 rectangle: [f64; 4],
3186 domains: [f64; 4],
3187 periodic: (bool, bool),
3188 best: &mut NewtonResult,
3189 bound: &mut f64,
3190 resolution: f64,
3191 settled: &mut Vec<usize>,
3192 cell_of: &dyn Fn(f64, f64) -> usize,
3193 stats: &mut GlobalStats,
3194) -> Result<bool, String> {
3195 stats.refinements += 1;
3196 let (confined, on_edge) = confined_descent(surface, point, seed, rectangle, (false, false))?;
3197 let mut found = confined;
3198 if on_edge && confined.distance_squared.sqrt() < *bound {
3199 stats.continuations += 1;
3202 let (continued, _) =
3203 confined_descent(surface, point, (confined.u, confined.v), domains, periodic)?;
3204 if continued.distance_squared < found.distance_squared {
3205 found = continued;
3206 }
3207 if continued.converged {
3208 settled.push(cell_of(continued.u, continued.v));
3209 }
3210 }
3211 if found.distance_squared.sqrt() < *bound {
3212 *best = found;
3213 *bound = best.distance_squared.sqrt() - resolution;
3214 stats.replaced = true;
3215 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
3216 return Ok(true);
3217 }
3218 }
3219 Ok(false)
3220}
3221
3222
3223
3224#[derive(Clone, Copy)]
3226pub enum FootDomain {
3227 Clamp,
3228 Wrap,
3229 Extended,
3230}
3231
3232#[derive(Clone, Copy)]
3233pub struct CurveFootPolicy {
3234 pub domain: FootDomain,
3235 pub iterations: usize,
3236 pub slope_guard: f64,
3237 pub step_limit: f64,
3238 pub parameter_tolerance: f64,
3239 pub mode: FootMode,
3240}
3241
3242#[derive(Clone, Copy)]
3244pub enum FootMode {
3245 Monotone,
3246 Witness,
3247 Stationary { positive_slope: bool, relative_step: bool },
3248 Backtracked,
3249 Planar,
3250}
3251
3252fn curve_foot_newton_state(
3255 curve: &NurbsCurve,
3256 point: Vec3,
3257 seed: f64,
3258 bracket: [f64; 2],
3259 policy: CurveFootPolicy,
3260) -> Result<(f64, f64, f64), String> {
3261 let fit = |u| match policy.domain {
3262 FootDomain::Clamp => fit_parameter(u, bracket[0], bracket[1], false),
3263 FootDomain::Wrap => fit_parameter(u, bracket[0], bracket[1], true),
3264 FootDomain::Extended => u,
3265 };
3266 let extended = matches!(policy.domain, FootDomain::Extended) || matches!(policy.mode, FootMode::Backtracked);
3267 let planar = matches!(policy.mode, FootMode::Planar);
3268 let project = |p: Vec3| if planar { Vec3::new(p.x, p.y, 0.0) } else { p };
3269 let point = project(point);
3270 let distance = |u| -> Result<f64, String> {
3271 let p = if extended { curve.derivatives_extended(u, 0)?[0] } else { curve.evaluate(u)? };
3272 Ok(project(p).sub(point).length())
3273 };
3274 let monotone = matches!(policy.mode, FootMode::Monotone | FootMode::Backtracked);
3275 let witness = matches!(policy.mode, FootMode::Witness);
3276 let mut u = if witness { seed } else { fit(seed) };
3277 let mut nearest_u = seed;
3278 let mut nearest_squared = f64::INFINITY;
3279 let mut best = if monotone { distance(u)? } else { f64::INFINITY };
3280 for _ in 0..policy.iterations {
3281 let derivatives = if extended {
3282 let values = curve.derivatives_extended(u, 2)?;
3283 [values[0], values[1], values[2]]
3284 } else if matches!(policy.mode, FootMode::Stationary { .. })
3285 || (planar && !crate::curve::small_curve_derivatives_enabled()) {
3286 let values = curve.derivatives(u, 2)?;
3287 [values[0], values[1], values[2]]
3288 } else {
3289 curve.derivatives_small(u, 2)?
3290 }.map(project);
3291 let offset = derivatives[0].sub(point);
3292 let numerator = offset.dot(derivatives[1]);
3293 let denominator = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
3294 if witness {
3295 let squared = offset.length_squared();
3296 if squared < nearest_squared {
3297 nearest_u = u;
3298 nearest_squared = squared;
3299 }
3300 let residual_length = squared.sqrt();
3301 if residual_length <= LINEAR_TOLERANCE
3302 || numerator.abs() <= EPSILON + 1e-10 * derivatives[1].length() * residual_length {
3303 break;
3304 }
3305 }
3306 let singular = if planar { denominator.abs() < policy.slope_guard }
3307 else { denominator.abs() <= policy.slope_guard };
3308 if singular || (matches!(policy.mode, FootMode::Stationary { positive_slope: true, .. }) && !(denominator > 0.0)) { break; }
3309 let mut step = if matches!(policy.mode, FootMode::Backtracked) && !(denominator > 0.0) {
3310 policy.step_limit.copysign(numerator)
3311 } else {
3312 (numerator / denominator).clamp(-policy.step_limit, policy.step_limit)
3313 };
3314 let mut next = fit(u - step);
3315 let mut next_distance = if monotone { distance(next)? } else { f64::INFINITY };
3316 if matches!(policy.mode, FootMode::Backtracked) {
3317 for _ in 0..30 {
3318 if next_distance < best { break; }
3319 step *= 0.5;
3320 next = fit(u - step);
3321 next_distance = distance(next)?;
3322 }
3323 if !(next_distance < best) { break; }
3324 } else if monotone && next_distance >= best { break; }
3325 let moved = if planar || matches!(policy.domain, FootDomain::Extended) { step }
3326 else if matches!(policy.domain, FootDomain::Wrap) {
3327 let period = bracket[1] - bracket[0];
3328 let raw = next - u;
3329 raw - period * (raw / period).round()
3330 } else { next - u };
3331 let tolerance = if matches!(policy.mode, FootMode::Stationary { relative_step: true, .. }) {
3332 policy.parameter_tolerance * (1.0 + u.abs())
3333 } else { policy.parameter_tolerance };
3334 let small = if planar || matches!(policy.mode, FootMode::Backtracked) { moved.abs() < tolerance }
3335 else { moved.abs() <= tolerance };
3336 if small && matches!(policy.mode, FootMode::Monotone) { break; }
3337 u = next;
3338 best = next_distance;
3339 if small { break; }
3340 }
3341 if witness { return Ok((u, nearest_u, nearest_squared)); }
3342 if !monotone { best = distance(u)?; }
3343 Ok((u, u, best * best))
3344}
3345
3346pub fn curve_foot_newton(
3347 curve: &NurbsCurve, point: Vec3, seed: f64, bracket: [f64; 2], policy: CurveFootPolicy,
3348) -> Result<(f64, f64), String> {
3349 let (_, nearest, squared) = curve_foot_newton_state(curve, point, seed, bracket, policy)?;
3350 Ok((nearest, squared))
3351}
3352
3353
3354
3355
3356