Skip to main content

brep_geometry/geometry/
projection.rs

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
33/// Escape hatch for tamper-verification: `BREP_PROJECTION_WITNESS=0` restores
34/// the pre-2026-09-14 answer — the Newton walk from the nearest seed and
35/// nothing else — so a fixture that depends on the rescue can be shown to
36/// depend on it. Read once; the projector is called about a million times in
37/// one boolean.
38fn witness_rescue_enabled() -> bool {
39    switch!("BREP_PROJECTION_WITNESS", true)
40}
41
42/// Squared distance from `point` to the SEGMENT `a`-`b`.
43///
44/// The seed sweep's consecutive samples are the segments of a polyline that
45/// approximates the curve, and this is how far that polyline passes from the
46/// query — the witness the rescue below reads.
47fn point_segment_distance_squared(point: Vec3, a: Vec3, b: Vec3) -> f64 {
48    point.distance_to_segment_squared(a, b)
49}
50
51/// One Newton refinement of the foot parameter, seeded at `seed`.
52///
53/// `best_u` / `best_distance_squared` carry the best answer found SO FAR and
54/// every iterate is compared against them, so a run that diverges or stalls can
55/// only leave the answer where it was. The returned parameter is where the
56/// iteration exited, which the caller still has to evaluate: the stall branch
57/// takes its last step without evaluating it.
58#[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
85/// The parameter in `[low, high]` nearest `point`, by golden-section search on
86/// the SQUARED distance.
87///
88/// Reads no derivative, so it is the one lane that still works where the
89/// tangent vanishes, and it can never return a point farther than the bracket's
90/// own ends. It assumes ONE minimum inside the bracket — true of a seed
91/// interval, which is one sample step of a single knot span wide.
92fn bracketed_nearest(curve: &NurbsCurve, point: Vec3, low: f64, high: f64) -> Result<f64, String> {
93    // 1/φ. 64 contractions take a bracket to 2.5e-14 of its width, below the
94    // parameter resolution the Newton polish that follows needs from a seed.
95    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
147/// PROJECTION MEMO (lane O row 22, 2026-10-29; on by default since the batch 6
148/// promotion, `BREP_PROJECTION_MEMO=0` projects every call). The projector is a pure function of the curve's net and the
149/// point. On the D2 outward shells every one of its 512 calls a shell call
150/// projects onto a straight two-point edge, and 209 of them repeat a call
151/// already made (the section's pierces, its ambiguity reads and the endpoint
152/// exchange re-project the same points; counted). A straight curve's
153/// whole net and the point make a 16-word key compared exactly, so a hit
154/// returns the very answer the projector computed.
155const 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
180// Immutable slices avoid retaining Vec spare capacity: cached sample payload
181// is at most 8 MiB per thread, plus at most 4096 map entries and Rc headers.
182type CurveSeeds = std::rc::Rc<SeedSet>;
183
184/// A curve's seed samples in their original sequence, and the boxes of consecutive blocks of them
185/// for [`blocked_seed_scan`] (`BREP_CURVE_SEED_BLOCKS`).
186#[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
199/// Samples per block of [`SeedSet::blocks`].
200const SEED_BLOCK: usize = 16;
201
202/// The box of block `b`'s samples `b * SEED_BLOCK ..` and of the sample before them, so it holds
203/// every segment that ends at one of its samples.
204#[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
230/// `BREP_CURVE_SEED_BLOCKS` (default on since its promotion; `=0` scans every sample): the curve projector's seed scan reads only the blocks of
231/// samples whose box can hold the nearest sample or the nearest segment ([`blocked_seed_scan`]),
232/// for the same answer as the scan of every sample.
233fn seed_blocks_enabled() -> bool {
234    switch!("BREP_CURVE_SEED_BLOCKS", true)
235}
236
237/// `BREP_CURVE_SEED_BLOCKS_CHECK=1`: run both scans and stop on any difference.
238fn seed_blocks_check() -> bool {
239    switch!("BREP_CURVE_SEED_BLOCKS_CHECK", false)
240}
241
242/// What the seed scan reads: the nearest sample (first of equals), the nearest segment between
243/// consecutive samples (first of equals), and the first and last samples.
244#[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
253/// The scan of every sample in order, as the projector has always read it.
254fn 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
276/// The same answer as [`linear_seed_scan`], reading only the blocks that can hold it. The linear
277/// scan keeps the FIRST sample (and segment) of least distance, so its answer is the least
278/// (distance, index) pair; a block whose box lies farther than both least distances found holds
279/// neither, and the blocks are read nearest box first until every remaining box is that far. The
280/// box bound is a true lower bound of each sample's computed distance (the same coordinate
281/// differences, rounded the same way, never larger). A segment's nearest point is computed, so its
282/// distance may read below the box: by a few ulps relative, and by an absolute rounding of the
283/// order of eps times the coordinates' size, which dominates near zero (a point an ulp off a
284/// closed curve's seam read its last chord at 3.269e-30 against a box at 3.303e-30). Each box is
285/// therefore read at its distance less a cushion of 64 eps times the size of the point and box
286/// corners, and less a relative 1e-9, and passed over only when that is farther than both.
287fn 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
343/// Discard the calling thread's bounded seed geometry at a history boundary.
344/// Other workers retain their own content-keyed entries until local eviction,
345/// an explicit clear on that worker, or thread exit. This is deliberately not
346/// a pool-wide invalidation: curve content fully determines every stored bit.
347/// Each worker retains at most 262,144 samples (8 MiB payload) and 4096 keys;
348/// temporary sampling and an outstanding borrowed snapshot are additional.
349pub 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
367/// Cache only the curve-dependent seed geometry, in its original sequence.
368/// Every query still performs the same distance comparisons, witness search,
369/// Newton iterations and tie breaking. The content key includes every knot
370/// and homogeneous control bit; failed sampling is never retained.
371fn 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    // Avoid allocating a giant one-off vector even when it would not be kept.
374    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/// A curve held with its seed samples, for a caller that projects onto the same curve again and
404/// again (an extrusion's reduced profile): the projector reads the held samples instead of
405/// hashing the curve's content into the seed cache on every call. Same samples, same answer.
406#[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    /// The curve without its samples: [`Self::project`] is then `project_point_to_curve`.
431    pub(crate) fn bare(curve: NurbsCurve) -> Self {
432        Self { curve, seeds: None }
433    }
434
435    /// `project_point_to_curve(&self.curve, point)`, bit for bit. A straight curve keeps the
436    /// projector's own memo, and a curve whose samples are not held goes the projector's way.
437    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    // The sweep's FIRST sample is exactly `start` and its LAST is exactly `end`
452    // (`breaks` opens at `start` and closes at `end`, and index 0 / index
453    // `samples_per_span` hit a span's own ends), so closure costs no extra
454    // evaluation: keep those two points and compare them.
455    let mut start_point = None;
456    let mut end_point = None;
457    // The sampled polyline's own nearest approach, and the seed interval that
458    // achieves it. Squared throughout, so the sweep pays no square root.
459    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    // A closed curve's domain is PERIODIC, so Newton must wrap across the seam
512    // rather than stop at it. Clamping made the projector return the seam for
513    // any query whose foot sits within half a seed spacing of it: `start` and
514    // `end` are the same POINT, the sweep keeps the first of equal distances and
515    // so seeds at `start`, and a Newton step toward a foot just BEFORE the seam
516    // is then clamped back to `start`, reads as a zero-length step, and breaks.
517    // Measured on a rational-quadratic circle of radius 20: 4.796 mm out, for a
518    // point taken off the curve itself. Swapping the sweep's tie-break to keep
519    // the LAST equal sample does not fix this — it mirrors it, returning the
520    // same 4.796 mm for queries just AFTER the seam. The surface projector has
521    // always wrapped (`fit_parameter` at the `project_point_to_surface` Newton
522    // step); this is the curve side catching up.
523    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    // AN ANSWER THE SEED POLYLINE REFUTES IS NOT AN ANSWER. The sweep's
547    // consecutive samples are a polyline that approximates the curve, so the
548    // nearest that polyline passes to the query is a witness: the curve
549    // demonstrably comes about that close. When the answer is FARTHER than the
550    // witness by more than a factor of two, Newton converged in the wrong basin
551    // and the seed interval the witness names is where the foot really is.
552    //
553    // Two different defects reach here, both of them "a point ON the curve does
554    // not project to its own parameter", and both measured on real geometry:
555    //
556    // * A STATIONARY seed. Newton is a first-order method and
557    //   `f = C'(t) · (C(t) - P)` vanishes at a stationary parameter for EVERY
558    //   `P`, so the iteration reads convergence there whatever the point is, and
559    //   the step it would otherwise take is `-f/f''`, a second-order quantity
560    //   whose sign has nothing to do with where the foot is. The 2026-09-14
561    //   herringbone document is full of them: a flank pcurve is a two-span cubic
562    //   whose first two control points COINCIDE (an involute's speed is
563    //   `r_base * t`, so its Hermite start tangent is exactly zero), the sweep's
564    //   nearest sample to a query near the start IS that cusp, and a point lying
565    //   exactly on the curve at t = 0.125 answered t = 0, 2.159e-2 out in uv.
566    //   That is the wrong answer `build_loop`'s partial-run rescue declined on.
567    // * A seed grid coarser in ONE span than in the rest. An imported pcurve
568    //   from `abc_00000013.step` carries 511 interior knots whose first span is
569    //   eighty times the width of the median, and five samples per span leave
570    //   its samples 4.6e-3 of uv apart — so a point on the curve at fraction
571    //   0.01 read as 3.969e-3 from a DIFFERENT branch at fraction 0.99, which
572    //   was genuinely nearer than any sample of its own.
573    //
574    // The witness refuted both by 71x and by 293000x. Every update below is a
575    // strict improvement on the distance already found, so a rescue that finds
576    // nothing better leaves the answer exactly where it was.
577    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
666/// Most seeded verification queries are already on the carrier. Row zero
667/// uses the same basis and rational arithmetic at counts zero and two; read
668/// it first, preserving the best-point and distance exit, and compute the
669/// remaining derivatives only when Newton actually needs to take a step.
670fn 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    // A step is a function of (u, v) alone, so an iterate that returns to an
692    // earlier one bit for bit repeats that stretch until the iteration cap:
693    // no exit fires (none did on the first pass through it), the best point
694    // cannot improve (every state of the stretch has been read, and the
695    // comparison is strict), and the state the cap would leave is the stretch's
696    // state at the cap's index. Take that state now instead of walking there
697    // (`BREP_PROJECTION_NEWTON_CYCLE_EXIT`, default on; `=0` walks). Measured
698    // on one import with fitted high-degree carriers and the projected-foot
699    // refine on: about one Newton call in eighteen ran to the cap, those calls
700    // held half of all Newton iterations, and at least three in five of them
701    // were repeating a stretch of eight states or fewer.
702    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
782/// Refine an existing branch foot for precision trim construction. The normal
783/// projector's distance exit is an on-carrier admission test, not a bound on
784/// tangential placement suitable for interpolating a more accurate trim.
785pub 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/// The point of `surface` nearest `point`, over the surface's whole domain.
799///
800/// Analytic carriers answer in closed form; every other surface goes through
801/// `project_point_to_surface_general`, which says what it guarantees.
802/// `#[track_caller]` names the call site in the `BREP_PROJECTION_AUDIT` log.
803#[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    // Recognized analytic carriers (plane / cylinder / cone / sphere /
811    // torus) have exact closed-form projections in the surface's own
812    // rational parameterization — skip grid seeding and Newton entirely.
813    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
831/// [`project_point_to_surface`] without the general projector's global stage:
832/// the same closed forms on analytic, ellipsoid and extrusion carriers, and on
833/// any other carrier Newton from the seed grid's nearest sample
834/// ([`project_point_to_surface_from_nearest_seed`]). A local foot: its distance
835/// is an upper bound on the nearest point's. For a caller that only needs a
836/// start on the surface near the point, such as a Newton's opening iterate.
837pub 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
859/// Project a point onto a surface starting Newton from an explicit `(u, v)`
860/// guess, WITHOUT the global grid seed. This is a footpoint refiner for
861/// continuity-preserving curve-on-surface tracing: seeding each edge sample
862/// from its neighbour's parameters keeps the fit on ONE branch of a surface
863/// that folds back over the small trimmed patch, where an independent global
864/// search would snap to whichever fold is momentarily closest and tear the
865/// pcurve into a self-crossing zig-zag. The caller compares the returned
866/// `distance` against the global answer and only adopts this result when it is
867/// geometrically just as valid, so a bad seed can never make a fit worse.
868pub 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    // An ellipsoid's foot is unique off its medial axis: the closed form IS
878    // the branch answer, as it is for the analytic carriers at the seeded
879    // entry (`project_point_to_surface_from_seed`).
880    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/// The foot of `point` on the branch of `seed`: the closed form on an analytic
907/// carrier, otherwise Newton from the caller's own `(u, v)`
908/// ([`project_point_to_surface_seeded`]), WITHOUT the global search.
909///
910/// **Which callers.** One that already holds a foot on this surface from a
911/// geometrically adjacent query and whose output needs continuity with it: a
912/// pcurve's previous sample, a march's previous station, a Newton's previous
913/// iterate. [`project_point_to_surface`] answers a different question — where
914/// on the WHOLE surface the point is nearest — and on a carrier that comes back
915/// near itself, or for an off-surface query about as far from two sheets, that
916/// answer is a foot on another branch: a pcurve sample on the wrong sheet, an
917/// iterate that jumps. A caller with no such foot (a vertex, a probe, the first
918/// station) asks the nearest-point question and calls the projector.
919///
920/// **An analytic carrier** answers in closed form, as the projector does. Its
921/// only places with two equally valid feet are its seam, its poles and its focal
922/// set (axis, centre, tube circle), and the closed form answers those exactly as
923/// the nearest-point query always has; no march on one changes.
924///
925/// **What it does not promise.** It is a local answer: its distance is an upper
926/// bound, and a Newton that stalls returns its best iterate without saying so.
927/// Every caller keeps its own on-surface check.
928///
929/// **Instruments**, each read once. `BREP_PROJECTION_FROM_SEED=0` returns
930/// [`project_point_to_surface`]'s answer at every caller (the reading before
931/// 2026-09-15, for a same-binary A/B); `BREP_PROJECTION_FROM_SEED_SITES=<a,b,…>`
932/// keeps the seeded answer only at the call sites whose `file:line` contains
933/// one of the substrings. Under `BREP_PROJECTION_AUDIT=<dir>` every query whose
934/// seeded foot lies farther than the on-surface floor from the nearest point's
935/// foot appends one line to `<dir>/projection-seed-audit-<pid>.tsv`. That
936/// comparand is the nearest-point projector under the same caller, so its own
937/// replacements land in `projection-audit-<pid>.tsv` at this site's line: they
938/// are the audit's, not an answer the caller took.
939#[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
972/// `BREP_PROJECTION_FROM_SEED=0` / `BREP_PROJECTION_FROM_SEED_SITES`: see
973/// [`project_point_to_surface_from_seed`].
974fn 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
998/// One line per seeded answer whose foot is not the nearest point's: the call
999/// site, both distances, the seed, both feet's `(u, v)`, the separation of the
1000/// two feet and the surface's shape.
1001fn 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
1047/// The Newton seed grid for general projection: (u, v, point) samples over
1048/// every knot span. A pure function of the surface, cached on it — building
1049/// the grid costs hundreds of evaluations and projection is the hottest
1050/// entry point in the kernel.
1051fn 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
1089/// The dense fallback grid for degenerate general projection: (u, v, point)
1090/// over a `(count_u+1) × (count_v+1)` lattice with `count_u/count_v` derived
1091/// from the surface's knot spans. A pure function of the surface, cached on
1092/// it — on metre-unit-mm parts the degenerate fallback fires ~1.7M times and
1093/// each re-evaluated all ~561 lattice points; caching them makes the argmin a
1094/// pure distance scan over reused points (bit-identical seed).
1095fn 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
1120/// Samples per block of a [`SampleGrid`].
1121const SAMPLE_BLOCK: usize = 32;
1122
1123/// Runs per group: the scan's second level, a box over [`GROUP_BLOCKS`]
1124/// consecutive runs ([`SampleGrid::groups`]).
1125const GROUP_BLOCKS: usize = 32;
1126
1127/// A cached `(u, v, point)` sample grid, with the axis-aligned box of each run
1128/// of [`SAMPLE_BLOCK`] consecutive samples, so the nearest-sample scan
1129/// ([`nearest_sample`]) skips a run none of whose samples can beat the answer
1130/// it holds.
1131#[derive(Clone, Debug)]
1132pub struct SampleGrid {
1133    samples: Vec<(f64, f64, Vec3)>,
1134    blocks: Vec<SampleBlock>,
1135    /// The union box of each [`GROUP_BLOCKS`] consecutive runs, prunable only
1136    /// when every run in it is. A union box's floor is at most each of its
1137    /// runs' floors as computed (the box faces are the runs' own, and the gap
1138    /// to a face farther out is no larger, IEEE rounding being monotone).
1139    groups: Vec<SampleBlock>,
1140    /// The box tree over the runs ([`nearest_sample_tree`]): `tree[0]` boxes
1141    /// each [`TREE_FANOUT`] consecutive runs, `tree[k]` each [`TREE_FANOUT`]
1142    /// consecutive boxes of `tree[k - 1]`, up to a single root. Built only by
1143    /// [`SampleGrid::with_tree`] (the dense grid), and empty when the grid has
1144    /// at most one group of runs.
1145    tree: Vec<Vec<SampleBlock>>,
1146}
1147
1148/// Children per node of [`SampleGrid::tree`].
1149const TREE_FANOUT: usize = 4;
1150
1151/// The union box of consecutive boxes, prunable only when each of them is.
1152fn 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/// One run's box. `prunable` is false when a sample has a non-finite
1168/// coordinate: the box says nothing about it, and the run is always scanned.
1169#[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    /// The grid with its box tree, for a scan that starts from a held answer
1208    /// (the dense fallback after a Newton): there the tree reads few floors.
1209    /// A scan from no answer reads its bound from a greedy descent, which on a
1210    /// surface whose boxes mostly hold the point lands on an arbitrary run;
1211    /// ABC 00027566's seed scans took 75 s through the tree against 44 s
1212    /// through the groups, so the seed grid keeps the groups.
1213    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    /// A floor on `sample.sub(point).length_squared()` over the run's samples,
1228    /// as COMPUTED, not only as real numbers: per axis the gap from `point` to
1229    /// the box is the same subtraction against the box face, and IEEE rounding
1230    /// is monotone, so `|fl(s - p)| >= fl(face - p)`; squaring and the same
1231    /// left-to-right sum of non-negative terms keep the order (`Vec3::dot`
1232    /// has no fused multiply-add). A NaN `point` reads gaps of 0 and every
1233    /// distance is NaN, which no scan takes, so skipping changes nothing.
1234    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
1251/// `BREP_PROJECTION_PRUNED_SCAN=0` scans every sample, as before 2026-11-10,
1252/// for a same-binary A/B. Read once per process.
1253fn pruned_scan() -> bool {
1254    switch!("BREP_PROJECTION_PRUNED_SCAN", true)
1255}
1256
1257/// Replace `best` with the grid's nearest sample when that is strictly nearer,
1258/// the first such in scan order: the bits of the linear scan, which this was
1259/// until 2026-11-10. A run is skipped only when its box's floor is not below
1260/// the distance held, so none of its samples could have replaced it (the
1261/// strict `<`), or lies above the bound read first ([`bound_first_scan`]),
1262/// and the runs are visited in scan order. ABC 00027566's
1263/// 166-span rational faces take the dense fallback on 71% of their pcurve
1264/// probes (the first Newton not converged), each scanning 22.7k samples: 9.1 s
1265/// of a face's 11.5 s of local answers.
1266fn 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
1274/// `BREP_PROJECTION_SCAN_TREE=0` scans through the two levels of groups and
1275/// runs alone, as before 2026-11-11, for a same-binary A/B. Read once per
1276/// process.
1277///
1278/// With it on, a grid built with a tree ([`SampleGrid::with_tree`]: the dense
1279/// grid, when it has more than one group) is scanned through
1280/// [`SampleGrid::tree`]. ABC 00027566's dense fallback on its 166-span faces
1281/// passed 52 of 287 group boxes per call (a group is a strip across the
1282/// surface, and many strips' boxes hold a point on it) and then read 1680 run
1283/// floors to scan 0.65 runs, never improving the answer it held: 26 s of floors
1284/// at one pcurve site.
1285fn scan_tree() -> bool {
1286    switch!("BREP_PROJECTION_SCAN_TREE", true)
1287}
1288
1289/// `BREP_PROJECTION_SCAN_HINT=0` reads the bound from the descent alone, as
1290/// before 2026-11-11, for a same-binary A/B. Read once per process.
1291///
1292/// With it on, a bound-first scan also reads the run that held the answer of
1293/// the last scan of the same grid on this thread. Consecutive queries are
1294/// mostly neighbours (a pcurve's probes): ABC 00027566's busiest pcurve site
1295/// found its answer in the previous answer's run on 98.8% of seed scans, while
1296/// the descent's run held it on 40%; with the hint the bound is the answer on
1297/// 99.4% and the seed scans there fell from 43.6 s to 18.4 s.
1298fn scan_hint() -> bool {
1299    switch!("BREP_PROJECTION_SCAN_HINT", true)
1300}
1301
1302const HINT_SLOTS: usize = 8;
1303
1304thread_local! {
1305    /// Direct-mapped by grid address: (grid samples address, run of its last answer).
1306    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
1315/// The bound lowered by the hinted run's samples. The hint is only a run
1316/// index: it is range-checked and read from the grid in hand, so a stale one
1317/// (another grid at a reused address) costs time, never bits. It lowers the
1318/// BOUND alone, never the answer held: each value it can take is a real
1319/// sample distance, at least the grid's least distance `m`, which is all the
1320/// bound-first argument asks of it.
1321fn 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
1341/// Remember the run that last improved the answer of a scan of `grid`.
1342fn 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
1353/// [`nearest_sample_with`]'s bound-first scan over the box tree: the bound is
1354/// read from the run reached by descending from the root through the child of
1355/// lowest floor (a real sample distance, or the incoming one, so never below
1356/// the grid's least distance `m`), then the tree is visited depth first in
1357/// scan order, skipping a box whose floor is at or above the distance held or
1358/// strictly above the bound. A union box's floor is at most each of its
1359/// children's as computed (the box faces are theirs, and IEEE rounding is
1360/// monotone), so a box is skipped only when every run under it would have
1361/// been, and the runs that are read are read in scan order: the bits of the
1362/// linear scan, by the argument [`nearest_sample_with`] gives for its groups.
1363fn 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    // Descend: at each level the child of lowest floor among the prunable ones.
1367    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    // Depth first in scan order: (level, index), level 0 of the stack meaning a run.
1400    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        // Pushed last-first so they pop in scan order.
1422        for child in children.rev() {
1423            stack.push((level - 1, child));
1424        }
1425    }
1426    remember_hint(grid, answer_run);
1427}
1428
1429/// `BREP_PROJECTION_BOUND_FIRST=0` prunes against the distance held alone, as
1430/// on 2026-11-10 before this pass, for a same-binary A/B. Read once per
1431/// process.
1432///
1433/// With it on, the runs are boxed again in groups of [`GROUP_BLOCKS`]. The scan
1434/// first reads the run of lowest floor inside the group of lowest floor and
1435/// takes the nearest of its samples as a BOUND, then visits the groups and
1436/// their runs in scan order, skipping any whose floor is at or above the
1437/// distance held or strictly above that bound. The runs alone started the seed
1438/// scan from no answer (its incoming distance is infinite), so every run ahead
1439/// of the nearest sample was read before the held distance fell, and every
1440/// scan computed one floor per run: on ABC 00027566 the seed
1441/// scans averaged 63k samples (361 s over 5M calls) and the dense ones 180k
1442/// (167 s over 3.5M), while a bound over the runs alone cut the first to 190 s
1443/// but doubled the second to 311 s with its extra pass of floors.
1444fn bound_first_scan() -> bool {
1445    switch!("BREP_PROJECTION_BOUND_FIRST", true)
1446}
1447
1448/// The scan behind [`nearest_sample`]. With `bound_first`, the bound is the
1449/// smaller of the incoming distance and one real sample distance, so it is
1450/// never below the grid's least distance `m`. The first sample at `m` lies in
1451/// a run whose floor is at most `m`, hence not above the bound and not at or
1452/// above the distance held when the scan reaches it (every sample before it is
1453/// strictly farther than `m`): that run is read and the sample taken, as the
1454/// linear scan takes it, and nothing after it is strictly nearer. A run whose
1455/// floor is above the bound holds no sample at `m`. The bound pass reads only
1456/// prunable runs, and updates on a strict `<`, so a NaN never enters it.
1457fn 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    // The bound: one real sample distance (or the incoming one), from the run
1468    // of lowest floor inside the group of lowest floor.
1469    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
1515/// The linear scan of one run: strict `<`, so the first of equal samples
1516/// stands.
1517fn 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
1528/// The index, within `range`, of the prunable box of least floor (the first
1529/// on a tie), or None when none is prunable.
1530fn 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
1545// Boundary-ring cache geometry: 4 sides × 22 exponents × 33 indices. The scan
1546// positions depend only on the surface domain and these fixed integers, so the
1547// evaluated points are a pure function of the surface and cacheable.
1548const RING_EXPONENTS: usize = 22;
1549const RING_INDICES: usize = 33; // index 0..=32
1550
1551#[inline]
1552fn ring_slot(side: usize, exponent_index: usize, index: usize) -> usize {
1553    (side * RING_EXPONENTS + exponent_index) * RING_INDICES + index
1554}
1555
1556/// The boundary-ring sample points for the degenerate projection fallback,
1557/// flattened by `ring_slot(side, exponent-1, index)`. Sides: 0 = v-low
1558/// (`v = v0 + (v1-v0)·offset`), 1 = v-high (`v1 - (v1-v0)·offset`), 2 = u-low
1559/// (`u0 + (u1-u0)·offset`), 3 = u-high (`u1 - (u1-u0)·offset`), where
1560/// `offset = 1/2^exponent`. A pure function of the surface, cached on it — the
1561/// fallback's boundary ring re-evaluated these on every one of ~1.7M calls.
1562fn 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
1590/// The LOCAL answer: Newton from the seed grid's single nearest sample (or the
1591/// linear-revolution foot), with the degenerate-parameterization fallbacks.
1592///
1593/// This is the whole of what the general projector returned before
1594/// 2026-09-14, and it is a local minimum, not the minimum: on a general patch
1595/// nearly closed in one direction the nearest sample can sit on the far end,
1596/// and Newton converges there (abc_00000026's thread flanks, 2.16e-2 .. 4.1e-2
1597/// against a true 1e-13). [`project_point_to_surface_general`] runs it first
1598/// and keeps its answer wherever no other basin beats it.
1599fn 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            // Read the pre-evaluated ring points at the exact same parameter
1658            // positions the live scans used (side/exponent/index → `ring_slot`),
1659            // preserving scan order and argmin tie-breaking for bit-identity.
1660            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
1723/// Escape hatch for A/B measurement: `BREP_PROJECTION_GLOBAL=0` returns the
1724/// local answer alone ([`nearest_seed_answer`], the pre-2026-09-14 projector),
1725/// so a population run can be repeated with and without the global stage from
1726/// one binary. Read once.
1727fn global_stage_enabled() -> bool {
1728    switch!("BREP_PROJECTION_GLOBAL", true)
1729}
1730
1731/// `BREP_PROJECTION_GLOBAL_SITES=<a,b,…>`: the global stage's answer is kept
1732/// only for call sites whose `file:line` contains one of the comma-separated
1733/// substrings, and the local answer is returned everywhere else — so a result
1734/// that moves can be attributed to the call site that moved it.
1735/// `BREP_PROJECTION_GLOBAL_EXCEPT=<a,b,…>` is the complement: every site but
1736/// those. Unset: every site. Read once.
1737/// Whether a `BREP_PROJECTION_GLOBAL_SITES`/`_EXCEPT` filter is set, i.e.
1738/// whether [`project_point_to_surface`]'s answer can depend on its call site.
1739pub fn global_site_filter_active() -> bool {
1740    // Read once per process, like the site lists `global_answer_admitted`
1741    // reads: the common reader asks this for every probe (two `getenv` calls,
1742    // ~3.7% of the elephant's B12 prefix on the production sampler,
1743    // 2026-11-02), and nothing sets these variables after start-up.
1744    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
1769/// `BREP_PROJECTION_AUDIT=<dir>`: every query on which the global stage
1770/// replaces the local answer appends one tab-separated line to
1771/// `<dir>/projection-audit-<pid>.tsv` — the call site, the local and the
1772/// global distance, both feet's `(u, v)` and the surface's shape. Per process,
1773/// because the case gate forks a child per case and loses its stderr.
1774fn 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/// The point of a general surface nearest `point`: the least local minimum of
1812/// the distance over the surface's whole domain.
1813///
1814/// **What it does.** First the local answer ([`nearest_seed_answer`]: Newton
1815/// from the nearest seed-grid sample, with its degenerate fallbacks — the whole
1816/// projector before 2026-09-14). Then the global stage ([`global_minimum`]):
1817/// the domain is cut into the cells of the projection lattice (every knot span
1818/// sampled `max(3, degree + 1)` times in an open direction and
1819/// `max(8, 4 × degree)` times in a closed one — the seed grid's own density),
1820/// and each cell is enclosed in a box built from the control points of the
1821/// surface REFINED to that cell. A NURBS patch with positive weights lies in
1822/// the convex hull of the control points that support it, so the distance from
1823/// the query to a cell's box is a rigorous LOWER bound on the distance to every
1824/// surface point of the cell. Every cell whose bound is below the best answer
1825/// so far is a candidate basin, and is refined by a descent confined to the
1826/// cell ([`confined_descent`]: Newton where the Hessian is positive definite,
1827/// the metric-scaled gradient where it is not, halved until the distance does
1828/// not rise, so it can end at a minimum but not at a saddle or a maximum),
1829/// seeded at the cell's nearest lattice node and continued over the domain
1830/// when the cell's least point is on its edge. The least answer wins. A closed
1831/// direction's seam is not special: the lattice spans the whole period, the
1832/// cells on either side of the seam are ordinary cells, and the continuation
1833/// wraps.
1834///
1835/// **What is guaranteed.**
1836/// * The answer is a point ON the surface, so its distance never under-reads.
1837/// * Every cell that could hold a point nearer than the answer by more than the
1838///   resolution has been descended in, unless it already held a verified
1839///   minimum: a cell left out was excluded by its hull bound, which cannot
1840///   over-read. [`GlobalStats::hull_lower_bound`] is that certificate: the
1841///   true distance lies in `[hull_lower_bound, answer]`, always.
1842/// * **The one step not certified in general: one basin in the cell that holds
1843///   the least minimum.** A descent finds the basin of its seed. A second basin
1844///   in any OTHER cell costs nothing — that cell's better basin is still no
1845///   nearer than the least minimum — but a second local minimum in the cell
1846///   holding the least minimum can catch the descent seeded at that cell's
1847///   nearest lattice node, and the least minimum is missed by at most
1848///   `answer − hull_lower_bound`. That takes a query past the focal distance of
1849///   part of the cell (farther than its radius of normal curvature on the
1850///   query's side, where the distance's Hessian `G − d·II` stops being positive
1851///   definite) or a cell whose image turns back toward the query. A descent that
1852///   runs out of iterations without a verified minimum fails the same way, with
1853///   the same bound. Seeding every corner of every candidate cell was measured
1854///   and changed no answer on the bench.
1855/// * **Certified on the analytic carriers** — the sphere, torus, cylinder and
1856///   cone, each a revolution of a circle or a line, and the plane. A lattice cell
1857///   there is an (azimuth × generatrix) rectangle under half a turn wide. In the
1858///   cell holding the least minimum the azimuthal derivative of the squared
1859///   distance, `2 ρ(v) ρ_P sin(λ − λ_P)`, vanishes only on the query's own
1860///   meridian, and moving toward that meridian lowers the distance from every
1861///   other point of the cell, so each local minimum over the cell is a local
1862///   minimum of the planar distance from the query's meridian image to the
1863///   generatrix over the cell's `v` range — exactly one on a circle arc under
1864///   half a turn or on a segment. At the focal sets (the axis, the sphere's
1865///   centre, the tube's centre circle) the minimum is a continuum of equal
1866///   distances and every foot is right. A general profile of revolution and a
1867///   general patch are not certified.
1868/// * Where the local answer is already the least minimum, it is returned
1869///   unchanged, bit for bit: the global stage replaces it only with a point
1870///   nearer by more than the resolution.
1871///
1872/// **The two numbers it reads.** The *on-surface floor* is `LINEAR_TOLERANCE`,
1873/// INHERITED unchanged: it is the local Newton's own stopping residual, and a
1874/// local answer within it of the query is on the surface and nothing is
1875/// searched. The *resolution* is the one new number, and it is the surface's
1876/// own: `(degree_u + 1)(degree_v + 1) · ε · scale`, `scale` the largest
1877/// control-point coordinate magnitude — the rounding of one evaluation, which
1878/// sums that many terms of that size. Every box is grown by it, and no
1879/// improvement finer than it is taken.
1880///
1881/// **What it costs.** A query settled by the floor costs what the local answer
1882/// always cost. Any other query builds the cell enclosure once per surface (one
1883/// knot refinement of the net to the lattice, cached on the surface beside the
1884/// seed grid), walks a bounding-sphere tree over the cells, and runs one
1885/// descent per candidate cell the hull bound does not exclude.
1886#[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
1914/// `BREP_SURFACE_PROJECTION_MEMO` (default on; =0 projects every call): the general projector keeps
1915/// its answers per thread, keyed by the surface's content hash
1916/// ([`NurbsSurface::content_key`]) and the point's bits, and answers a repeated
1917/// query from the memo. The projector is a pure function of the net and the
1918/// point (its grids and cells are built from the net), so a hit returns the
1919/// answer it computed. On a ball screwed round a tight helix 37% of the
1920/// general projections repeat one already made (the imprint's start points,
1921/// pierces and pair readings ask the same points again). Bypassed while a
1922/// call-site filter or the audit is set (they read the caller) and while
1923/// switches are read live (`BREP_ENV_READ_ONCE=0`); the switches a test forces
1924/// are part of the key. `BREP_SURFACE_PROJECTION_MEMO_CHECK=1` (with the memo
1925/// on) projects afresh on every hit and stops on any bit difference.
1926fn 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
1934/// No call-site filter and no audit (both read the caller), and switches read
1935/// once per process: under `BREP_ENV_READ_ONCE=0` a switch the projector reads
1936/// can change between two queries, which the key does not hold.
1937fn 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
1946/// The switches a test forces on this thread, as part of the memo's key: an
1947/// answer read under one setting is never returned under another. Zero
1948/// outside tests.
1949fn forced_switches_key() -> u64 {
1950    0
1951}
1952
1953/// The memo's bound per thread: cleared when it holds this many answers. An
1954/// entry is 96 bytes (key and answer), so the table stays under about 3.2 MB
1955/// a thread for the thread's life (32k buckets at most), under the curve seed
1956/// cache's own budget. Entries are keyed by content, never stale; a long-lived
1957/// process (the app, the PLM worker) holds at most this per kernel thread.
1958const 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
2002/// The single-seed inversion by itself: the closed form on an analytic
2003/// carrier, otherwise [`nearest_seed_answer`] — Newton from the seed grid's
2004/// nearest sample, WITHOUT the global stage. Its distance is an upper bound and
2005/// its foot a local minimum. It is not a nearest-point query: it exists for a
2006/// caller that asks a question ABOUT that inversion, and there is one —
2007/// `joint_branch_pcurves` (`io/step_import/builder/rims.rs`) offers a loop the
2008/// joint branch only when this inversion alternates between branches along it,
2009/// which it does on a carrier that comes back within one seed-grid spacing of
2010/// itself (`abc_00000026`'s nearly closed thread flanks).
2011pub 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/// Both answers for one query, and what the global stage did — the bench's
2040/// seam (`examples/projector_bench.rs`). Not for kernel callers.
2041#[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/// How many basins the cells of one query hold — the bench's measure of the
2068/// global stage's one uncertified step (see [`project_point_to_surface_general`]).
2069#[doc(hidden)]
2070#[derive(Clone, Debug, Default)]
2071pub struct BasinCensus {
2072    /// Cells whose hull bound is below the answer's distance: every cell the
2073    /// global stage could have descended in.
2074    pub cells: usize,
2075    /// Descents run: one from each corner of those cells and one from the middle.
2076    pub descents: usize,
2077    /// Descents that stopped without a verified minimum.
2078    pub unconverged: usize,
2079    /// Cells where two verified minima differ in distance by more than `bar`.
2080    /// Distances within the on-surface floor count as equal: the descent stops
2081    /// there, so two feet under it are one foot polished to different depths.
2082    pub cells_with_two_basins: usize,
2083    /// Of those, cells whose rectangle holds the least foot any descent found:
2084    /// the only cells where a second basin can cost the answer anything.
2085    pub foot_cells_with_two_basins: usize,
2086    /// The least distance any descent reached, and where.
2087    pub least: f64,
2088    pub least_uv: (f64, f64),
2089    /// Every descent in a two-basin cell that holds the least foot: the cell,
2090    /// its rectangle, the seed, where it stopped, its distance, and whether that
2091    /// is a verified minimum.
2092    pub foot_cell_descents: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)>,
2093}
2094
2095/// Descend in every cell whose hull bound is below `answer_distance` from each
2096/// of its corners and its middle, and count the cells whose verified minima
2097/// disagree by more than `bar`. For the bench only: it costs five descents per
2098/// cell, which the projector itself was measured not to need.
2099#[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/// What the global stage did on one query.
2167#[doc(hidden)]
2168#[derive(Clone, Copy, Debug, Default)]
2169pub struct GlobalStats {
2170    /// The local answer was within the on-surface floor; nothing searched.
2171    pub settled_by_floor: bool,
2172    /// Cells whose hull bound admitted them.
2173    pub candidates: usize,
2174    /// Confined Newtons run (candidates not already holding a converged foot).
2175    pub refinements: usize,
2176    /// Continuations across the domain from a cell edge.
2177    pub continuations: usize,
2178    /// The global stage replaced the local answer.
2179    pub replaced: bool,
2180    /// The least hull bound over every cell — the true distance is never
2181    /// below it (0 when the floor settled the query).
2182    pub hull_lower_bound: f64,
2183}
2184
2185/// One lattice cell's enclosure: an oriented box around the control points
2186/// that support the cell, in an orthonormal frame fitted to the cell.
2187#[derive(Clone, Debug)]
2188struct CellBox {
2189    axes: [Vec3; 3],
2190    low: [f64; 3],
2191    high: [f64; 3],
2192}
2193
2194impl CellBox {
2195    /// Distance from `point` to the box: a lower bound on the distance to
2196    /// every surface point of the cell.
2197    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/// A node of the bounding-sphere tree over the cells. A leaf names its cell;
2209/// an internal node its two children.
2210#[derive(Clone, Copy, Debug)]
2211struct CellTreeNode {
2212    centre: Vec3,
2213    radius: f64,
2214    children: Option<(u32, u32)>,
2215    cell: u32,
2216}
2217
2218/// The cached enclosure of every projection lattice cell (see
2219/// [`project_point_to_surface_general`]).
2220#[derive(Clone, Debug)]
2221pub struct ProjectionCells {
2222    us: Vec<f64>,
2223    vs: Vec<f64>,
2224    /// `us.len() × vs.len()` lattice points, row-major in u.
2225    nodes: Vec<Vec3>,
2226    /// `(us.len() - 1) × (vs.len() - 1)` cells, row-major in u.
2227    boxes: Vec<CellBox>,
2228    /// The tree's root is the LAST node.
2229    tree: Vec<CellTreeNode>,
2230    /// One box per tree node: a leaf's is its cell's box, an internal node's
2231    /// holds both children's boxes grown by `node_margin` on every side (see
2232    /// [`hull_candidates`]). Empty when the surface has no usable scale.
2233    node_boxes: Vec<CellBox>,
2234    /// The growth of each internal node's box over its children's.
2235    node_margin: f64,
2236    /// The largest control-point coordinate magnitude.
2237    scale: f64,
2238    resolution: f64,
2239}
2240
2241/// The projection lattice's parameters along one direction: every knot span
2242/// cut into `samples` equal pieces, the seed grid's density, shared span ends
2243/// listed once.
2244fn lattice_parameters(knots: &[f64], degree: usize, closed: bool) -> Vec<f64> {
2245    let [start, end] = crate::curve::knot_domain(knots, degree);
2246    let samples = if closed {
2247        8usize.max(degree * 4)
2248    } else {
2249        3usize.max(degree + 1)
2250    };
2251    let mut breaks = vec![start];
2252    breaks.extend(interior_knots(knots, degree));
2253    breaks.push(end);
2254    let mut parameters = Vec::with_capacity((breaks.len() - 1) * samples + 1);
2255    for pair in breaks.windows(2) {
2256        for index in 0..samples {
2257            parameters.push(pair[0] + (pair[1] - pair[0]) * index as f64 / samples as f64);
2258        }
2259    }
2260    parameters.push(end);
2261    parameters
2262}
2263
2264/// Raise every lattice parameter to full multiplicity in the knot vector, so
2265/// each lattice cell is one Bézier piece of the refined net.
2266///
2267/// `net[i]` is the i-th control point along the refined direction, held as a
2268/// row across the other direction, and every row takes the same combination.
2269/// Knot refinement in one pass (Piegl & Tiller, *The NURBS Book*, A5.4), in
2270/// homogeneous coordinates, so a rational net refines exactly and the cost is
2271/// linear in the refined net's size.
2272fn refine_to_lattice(net: &mut Vec<Vec<Vec4>>, knots: &mut Vec<f64>, degree: usize, parameters: &[f64]) {
2273    let p = degree;
2274    let n = net.len() - 1;
2275    let mut inserted = Vec::new();
2276    for &parameter in parameters {
2277        let multiplicity = knots.iter().filter(|&&knot| knot == parameter).count();
2278        for _ in multiplicity..p {
2279            inserted.push(parameter);
2280        }
2281    }
2282    if inserted.is_empty() || p == 0 {
2283        return;
2284    }
2285    inserted.sort_by(f64::total_cmp);
2286    let find_span = |parameter: f64| -> usize {
2287        if parameter >= knots[n + 1] {
2288            return n;
2289        }
2290        (knots.partition_point(|&knot| knot <= parameter) - 1).clamp(p, n)
2291    };
2292    let r = inserted.len() - 1;
2293    let m = n + p + 1;
2294    let a = find_span(inserted[0]);
2295    let b = find_span(inserted[r]) + 1;
2296    let columns = net[0].len();
2297    let blank = vec![
2298        Vec4 {
2299            x: 0.0,
2300            y: 0.0,
2301            z: 0.0,
2302            w: 0.0,
2303        };
2304        columns
2305    ];
2306    let mut refined = vec![blank; n + r + 2];
2307    let mut refined_knots = vec![0.0; m + r + 2];
2308    for j in 0..=a - p {
2309        refined[j] = net[j].clone();
2310    }
2311    for j in b - 1..=n {
2312        refined[j + r + 1] = net[j].clone();
2313    }
2314    refined_knots[..=a].copy_from_slice(&knots[..=a]);
2315    for j in b + p..=m {
2316        refined_knots[j + r + 1] = knots[j];
2317    }
2318    let mut i = b + p - 1;
2319    let mut k = b + p + r;
2320    for j in (0..=r).rev() {
2321        while inserted[j] <= knots[i] && i > a {
2322            refined[k - p - 1] = net[i - p - 1].clone();
2323            refined_knots[k] = knots[i];
2324            k -= 1;
2325            i -= 1;
2326        }
2327        refined[k - p - 1] = refined[k - p].clone();
2328        for l in 1..=p {
2329            let index = k - p + l;
2330            let numerator = refined_knots[k + l] - inserted[j];
2331            if numerator == 0.0 {
2332                refined[index - 1] = refined[index].clone();
2333            } else {
2334                let alpha = numerator / (refined_knots[k + l] - knots[i - p + l]);
2335                let (head, tail) = refined.split_at_mut(index);
2336                for (before, &here) in head[index - 1].iter_mut().zip(&tail[0]) {
2337                    *before = before.scale(alpha).add(here.scale(1.0 - alpha));
2338                }
2339            }
2340        }
2341        refined_knots[k] = inserted[j];
2342        k = k.saturating_sub(1);
2343    }
2344    *net = refined;
2345    *knots = refined_knots;
2346}
2347
2348/// The control-point index range supporting the parameter interval
2349/// `[low, high]`: every basis function non-zero anywhere on it.
2350fn supporting_range(knots: &[f64], degree: usize, count: usize, low: f64, high: f64) -> (usize, usize) {
2351    let first_span = knots.partition_point(|&knot| knot <= low).saturating_sub(1);
2352    let last_span = knots.partition_point(|&knot| knot < high).saturating_sub(1);
2353    (
2354        first_span.saturating_sub(degree).min(count - 1),
2355        last_span.max(first_span).min(count - 1),
2356    )
2357}
2358
2359fn unit_or(vector: Vec3, fallback: Vec3) -> Vec3 {
2360    let length = vector.length();
2361    if length > 0.0 && length.is_finite() {
2362        vector.scale(1.0 / length)
2363    } else {
2364        fallback
2365    }
2366}
2367
2368fn enclosing_sphere(a: (Vec3, f64), b: (Vec3, f64)) -> (Vec3, f64) {
2369    let offset = b.0.sub(a.0);
2370    let separation = offset.length();
2371    if separation + b.1 <= a.1 {
2372        return a;
2373    }
2374    if separation + a.1 <= b.1 {
2375        return b;
2376    }
2377    let radius = (separation + a.1 + b.1) * 0.5;
2378    let centre = a.0.add(offset.scale((radius - a.1) / separation));
2379    (centre, radius)
2380}
2381
2382/// What [`build_cell_tree`] reads besides the spheres: the cells' boxes and
2383/// the lattice points (row-major, `lattice_columns` per row) that frame each
2384/// internal node's box, and the margin each internal box grows by.
2385struct NodeBoxInputs<'a> {
2386    boxes: &'a [CellBox],
2387    nodes: &'a [Vec3],
2388    lattice_columns: usize,
2389    margin: f64,
2390}
2391
2392/// The box of an internal node: framed like a cell's (along u, then the
2393/// normal of the region's lattice corners), spanning every corner of both
2394/// children's boxes, grown by `margin` on every side. Unbounded when a frame or
2395/// an extent is not finite, so it never prunes.
2396fn enclosing_node_box(corners: [Vec3; 4], children: [&CellBox; 2], margin: f64) -> CellBox {
2397    let unbounded = || CellBox {
2398        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)],
2399        low: [f64::NEG_INFINITY; 3],
2400        high: [f64::INFINITY; 3],
2401    };
2402    let [c00, c10, c01, c11] = corners;
2403    let along_u = c10.sub(c00).add(c11.sub(c01));
2404    let along_v = c01.sub(c00).add(c11.sub(c10));
2405    let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2406    let Ok(fallback) = e1.perpendicular() else {
2407        return unbounded();
2408    };
2409    let normal = unit_or(e1.cross(along_v), fallback);
2410    let e2 = unit_or(normal.cross(e1), fallback);
2411    let e3 = e1.cross(e2);
2412    let axes = [e1, e2, e3];
2413    let mut low = [f64::INFINITY; 3];
2414    let mut high = [f64::NEG_INFINITY; 3];
2415    for child in children {
2416        for corner in 0..8 {
2417            let mut point = Vec3::default();
2418            for axis in 0..3 {
2419                let value = if corner >> axis & 1 == 0 { child.low[axis] } else { child.high[axis] };
2420                point = point.add(child.axes[axis].scale(value));
2421            }
2422            for axis in 0..3 {
2423                let coordinate = point.dot(axes[axis]);
2424                low[axis] = low[axis].min(coordinate);
2425                high[axis] = high[axis].max(coordinate);
2426            }
2427        }
2428    }
2429    for axis in 0..3 {
2430        low[axis] -= margin;
2431        high[axis] += margin;
2432    }
2433    if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2434        return unbounded();
2435    }
2436    CellBox { axes, low, high }
2437}
2438
2439fn build_cell_tree(
2440    tree: &mut Vec<CellTreeNode>,
2441    node_boxes: &mut Vec<CellBox>,
2442    inputs: &NodeBoxInputs<'_>,
2443    spheres: &[(Vec3, f64)],
2444    columns: usize,
2445    [row_low, row_high, column_low, column_high]: [usize; 4],
2446) -> u32 {
2447    if row_high - row_low == 1 && column_high - column_low == 1 {
2448        let cell = row_low * columns + column_low;
2449        node_boxes.push(inputs.boxes[cell].clone());
2450        tree.push(CellTreeNode {
2451            centre: spheres[cell].0,
2452            radius: spheres[cell].1,
2453            children: None,
2454            cell: cell as u32,
2455        });
2456        return (tree.len() - 1) as u32;
2457    }
2458    let (first, second) = if row_high - row_low >= column_high - column_low {
2459        let middle = (row_low + row_high) / 2;
2460        (
2461            [row_low, middle, column_low, column_high],
2462            [middle, row_high, column_low, column_high],
2463        )
2464    } else {
2465        let middle = (column_low + column_high) / 2;
2466        (
2467            [row_low, row_high, column_low, middle],
2468            [row_low, row_high, middle, column_high],
2469        )
2470    };
2471    let first = build_cell_tree(tree, node_boxes, inputs, spheres, columns, first);
2472    let second = build_cell_tree(tree, node_boxes, inputs, spheres, columns, second);
2473    let a = tree[first as usize];
2474    let b = tree[second as usize];
2475    let lattice = |row: usize, column: usize| inputs.nodes[row * inputs.lattice_columns + column];
2476    node_boxes.push(enclosing_node_box(
2477        [
2478            lattice(row_low, column_low),
2479            lattice(row_high, column_low),
2480            lattice(row_low, column_high),
2481            lattice(row_high, column_high),
2482        ],
2483        [&node_boxes[first as usize], &node_boxes[second as usize]],
2484        inputs.margin,
2485    ));
2486    // The resolution-inflated leaf spheres already absorb rounding; the merge
2487    // adds one more rounding of the same order, absorbed by growing the radius
2488    // by the larger child's own ulp.
2489    let (centre, radius) = enclosing_sphere((a.centre, a.radius), (b.centre, b.radius));
2490    tree.push(CellTreeNode {
2491        centre,
2492        radius: radius * (1.0 + 4.0 * f64::EPSILON),
2493        children: Some((first, second)),
2494        cell: u32::MAX,
2495    });
2496    (tree.len() - 1) as u32
2497}
2498
2499fn projection_cells(surface: &NurbsSurface) -> Result<Option<&ProjectionCells>, String> {
2500    if let Some(cells) = surface.projection_cells.get() {
2501        return Ok(cells.as_ref());
2502    }
2503    let cells = build_projection_cells(surface)?;
2504    Ok(surface.projection_cells.get_or_init(|| cells).as_ref())
2505}
2506
2507fn build_projection_cells(surface: &NurbsSurface) -> Result<Option<ProjectionCells>, String> {
2508    let (closed_u, closed_v) = surface.closed_directions()?;
2509    let us = lattice_parameters(&surface.knots_u, surface.degree_u, closed_u);
2510    let vs = lattice_parameters(&surface.knots_v, surface.degree_v, closed_v);
2511    if us.len() < 2 || vs.len() < 2 {
2512        return Ok(None);
2513    }
2514    let mut scale = 0.0f64;
2515    for control in surface.control_points.iter().flatten() {
2516        let point = control.point()?;
2517        scale = scale.max(point.x.abs()).max(point.y.abs()).max(point.z.abs());
2518    }
2519    let resolution =
2520        ((surface.degree_u + 1) * (surface.degree_v + 1)) as f64 * f64::EPSILON * scale;
2521
2522    // Refine u (the net's rows), then v (its columns, as rows of the transpose).
2523    let mut net = surface.control_points.clone();
2524    let mut knots_u = surface.knots_u.clone();
2525    refine_to_lattice(&mut net, &mut knots_u, surface.degree_u, &us);
2526    let columns = net.first().map(Vec::len).unwrap_or(0);
2527    let mut transposed: Vec<Vec<Vec4>> =
2528        (0..columns).map(|column| net.iter().map(|row| row[column]).collect()).collect();
2529    let mut knots_v = surface.knots_v.clone();
2530    refine_to_lattice(&mut transposed, &mut knots_v, surface.degree_v, &vs);
2531    let rows = transposed.first().map(Vec::len).unwrap_or(0);
2532    let columns = transposed.len();
2533    if rows == 0 || columns == 0 {
2534        return Ok(None);
2535    }
2536    let mut points = vec![Vec3::default(); rows * columns];
2537    for (column, fibre) in transposed.iter().enumerate() {
2538        for (row, control) in fibre.iter().enumerate() {
2539            points[row * columns + column] = control.point()?;
2540        }
2541    }
2542
2543    let mut nodes = Vec::with_capacity(us.len() * vs.len());
2544    for &u in &us {
2545        for &v in &vs {
2546            nodes.push(surface.evaluate(u, v)?);
2547        }
2548    }
2549
2550    let cell_rows = us.len() - 1;
2551    let cell_columns = vs.len() - 1;
2552    let mut boxes = Vec::with_capacity(cell_rows * cell_columns);
2553    let mut spheres = Vec::with_capacity(cell_rows * cell_columns);
2554    for i in 0..cell_rows {
2555        let (row_low, row_high) =
2556            supporting_range(&knots_u, surface.degree_u, rows, us[i], us[i + 1]);
2557        for j in 0..cell_columns {
2558            let (column_low, column_high) =
2559                supporting_range(&knots_v, surface.degree_v, columns, vs[j], vs[j + 1]);
2560            let at = |row: usize, column: usize| points[row * columns + column];
2561            let c00 = at(row_low, column_low);
2562            let c10 = at(row_high, column_low);
2563            let c01 = at(row_low, column_high);
2564            let c11 = at(row_high, column_high);
2565            let along_u = c10.sub(c00).add(c11.sub(c01));
2566            let along_v = c01.sub(c00).add(c11.sub(c10));
2567            let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2568            let normal = unit_or(e1.cross(along_v), e1.perpendicular()?);
2569            let e2 = unit_or(normal.cross(e1), e1.perpendicular()?);
2570            let e3 = e1.cross(e2);
2571            let axes = [e1, e2, e3];
2572            let mut low = [f64::INFINITY; 3];
2573            let mut high = [f64::NEG_INFINITY; 3];
2574            for row in row_low..=row_high {
2575                for column in column_low..=column_high {
2576                    let point = at(row, column);
2577                    for axis in 0..3 {
2578                        let coordinate = point.dot(axes[axis]);
2579                        low[axis] = low[axis].min(coordinate);
2580                        high[axis] = high[axis].max(coordinate);
2581                    }
2582                }
2583            }
2584            for axis in 0..3 {
2585                low[axis] -= resolution;
2586                high[axis] += resolution;
2587            }
2588            let mut centre = Vec3::default();
2589            let mut half_diagonal_squared = 0.0;
2590            for axis in 0..3 {
2591                centre = centre.add(axes[axis].scale((low[axis] + high[axis]) * 0.5));
2592                let half = (high[axis] - low[axis]) * 0.5;
2593                half_diagonal_squared += half * half;
2594            }
2595            if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2596                return Ok(None);
2597            }
2598            spheres.push((centre, half_diagonal_squared.sqrt() + resolution));
2599            boxes.push(CellBox { axes, low, high });
2600        }
2601    }
2602    let mut tree = Vec::with_capacity(2 * boxes.len());
2603    let mut node_boxes = Vec::with_capacity(2 * boxes.len());
2604    // Each internal box grows by a billionth of the surface's scale over its
2605    // children: far above the rounding of the corners it spans and of the
2606    // bound read from it, so a box that excludes a point excludes every cell
2607    // under it (see `hull_candidates`).
2608    let node_margin = NODE_BOX_MARGIN * scale;
2609    let inputs = NodeBoxInputs { boxes: &boxes, nodes: &nodes, lattice_columns: vs.len(), margin: node_margin };
2610    build_cell_tree(&mut tree, &mut node_boxes, &inputs, &spheres, cell_columns, [0, cell_rows, 0, cell_columns]);
2611    if !(node_margin > 0.0 && node_margin.is_finite()) {
2612        node_boxes = Vec::new();
2613    }
2614    Ok(Some(ProjectionCells {
2615        us,
2616        vs,
2617        nodes,
2618        boxes,
2619        tree,
2620        node_boxes,
2621        node_margin,
2622        scale,
2623        resolution,
2624    }))
2625}
2626
2627/// First- and second-order optimality of `(u, v)` for the distance over the
2628/// rectangle: stationary on the coordinates the rectangle leaves free (the
2629/// descent's own cosine test), with a positive definite Hessian there. A
2630/// `periodic` direction has no edge to be pinned against: its seam is interior.
2631fn optimality(
2632    derivatives: &[[Vec3; 3]; 3],
2633    point: Vec3,
2634    (u, v): (f64, f64),
2635    [ua, ub, va, vb]: [f64; 4],
2636    periodic: (bool, bool),
2637) -> Optimality {
2638    let residual = derivatives[0][0].sub(point);
2639    let residual_length = residual.length();
2640    let su = derivatives[1][0];
2641    let sv = derivatives[0][1];
2642    let f = su.dot(residual);
2643    let g = sv.dot(residual);
2644    let metric_u = su.length_squared();
2645    let metric_v = sv.length_squared();
2646    let stationary_u = metric_u.sqrt() * residual_length <= EPSILON
2647        || f.abs() <= 1e-10 * metric_u.sqrt() * residual_length;
2648    let stationary_v = metric_v.sqrt() * residual_length <= EPSILON
2649        || g.abs() <= 1e-10 * metric_v.sqrt() * residual_length;
2650    let pinned_u = !periodic.0 && ((u <= ua && f > 0.0) || (u >= ub && f < 0.0));
2651    let pinned_v = !periodic.1 && ((v <= va && g > 0.0) || (v >= vb && g < 0.0));
2652    let j00 = derivatives[2][0].dot(residual) + metric_u;
2653    let j01 = derivatives[1][1].dot(residual) + su.dot(sv);
2654    let j11 = derivatives[0][2].dot(residual) + metric_v;
2655    let determinant = j00 * j11 - j01 * j01;
2656    let convex = match (!pinned_u, !pinned_v) {
2657        (true, true) => j00 > 0.0 && determinant > 0.0,
2658        (true, false) => j00 > 0.0,
2659        (false, true) => j11 > 0.0,
2660        (false, false) => true,
2661    };
2662    Optimality {
2663        residual_length,
2664        gradient: (f, g),
2665        metric: (metric_u, metric_v),
2666        hessian: (j00, j01, j11),
2667        determinant,
2668        pinned: (pinned_u, pinned_v),
2669        convex,
2670        minimum: residual_length <= LINEAR_TOLERANCE
2671            || ((stationary_u || pinned_u) && (stationary_v || pinned_v) && convex),
2672    }
2673}
2674
2675struct Optimality {
2676    residual_length: f64,
2677    gradient: (f64, f64),
2678    metric: (f64, f64),
2679    hessian: (f64, f64, f64),
2680    determinant: f64,
2681    pinned: (bool, bool),
2682    convex: bool,
2683    minimum: bool,
2684}
2685
2686fn is_verified_minimum(
2687    surface: &NurbsSurface,
2688    point: Vec3,
2689    at: (f64, f64),
2690    rectangle: [f64; 4],
2691    periodic: (bool, bool),
2692) -> Result<bool, String> {
2693    let derivatives = surface.derivatives_small(at.0, at.1, 2)?;
2694    Ok(optimality(&derivatives, point, at, rectangle, periodic).minimum)
2695}
2696
2697/// A descent to a local minimum of the distance over the rectangle
2698/// `[ua, ub] × [va, vb]`, from a seed inside it.
2699///
2700/// Newton on the gradient converges to ANY critical point — a saddle or a
2701/// maximum as readily as a minimum — and reads convergence there, so every
2702/// step here must lower the distance: the Newton step where the Hessian is
2703/// positive definite on the free coordinates, the metric-scaled gradient step
2704/// where it is not, halved until the distance does not rise. A coordinate
2705/// pinned at the rectangle's edge by a gradient pointing out of it is held
2706/// there and the other takes the one-dimensional step, so a minimum ON the edge
2707/// converges as one (the Karush-Kuhn-Tucker point) instead of stalling.
2708///
2709/// Returns the best iterate, whether it is a verified minimum (stationary on
2710/// the free coordinates with a positive definite Hessian there, or within the
2711/// on-surface floor), and whether it lies on the rectangle's edge.
2712fn confined_descent(
2713    surface: &NurbsSurface,
2714    point: Vec3,
2715    seed: (f64, f64),
2716    rectangle: [f64; 4],
2717    periodic: (bool, bool),
2718) -> Result<(NewtonResult, bool), String> {
2719    let [ua, ub, va, vb] = rectangle;
2720    let mut u = fit_parameter(seed.0, ua, ub, periodic.0);
2721    let mut v = fit_parameter(seed.1, va, vb, periodic.1);
2722    let mut converged = false;
2723    let mut current = surface.evaluate(u, v)?.sub(point).length_squared();
2724    for _ in 0..MAX_NEWTON_ITERATIONS {
2725        let derivatives = surface.derivatives_small(u, v, 2)?;
2726        let state = optimality(&derivatives, point, (u, v), rectangle, periodic);
2727        current = state.residual_length * state.residual_length;
2728        if state.minimum {
2729            converged = true;
2730            break;
2731        }
2732        let (f, g) = state.gradient;
2733        let (metric_u, metric_v) = state.metric;
2734        let (j00, j01, j11) = state.hessian;
2735        let determinant = state.determinant;
2736        let (free_u, free_v) = (!state.pinned.0, !state.pinned.1);
2737        let (mut du, mut dv) = match (free_u, free_v) {
2738            (true, true) if state.convex => (
2739                (-f * j11 + g * j01) / determinant,
2740                (-g * j00 + f * j01) / determinant,
2741            ),
2742            (true, false) if state.convex => (-f / j00, 0.0),
2743            (false, true) if state.convex => (0.0, -g / j11),
2744            _ => (
2745                if free_u && metric_u > 0.0 { -f / metric_u } else { 0.0 },
2746                if free_v && metric_v > 0.0 { -g / metric_v } else { 0.0 },
2747            ),
2748        };
2749        if !(du.is_finite() && dv.is_finite()) || (du == 0.0 && dv == 0.0) {
2750            break;
2751        }
2752        let mut moved = false;
2753        // The step actually taken, a whole period removed across a seam.
2754        let taken = |next: f64, here: f64, low: f64, high: f64, wraps: bool| {
2755            let raw = next - here;
2756            if wraps {
2757                raw - (high - low) * (raw / (high - low)).round()
2758            } else {
2759                raw
2760            }
2761        };
2762        for _ in 0..40 {
2763            let next_u = fit_parameter(u + du, ua, ub, periodic.0);
2764            let next_v = fit_parameter(v + dv, va, vb, periodic.1);
2765            if next_u == u && next_v == v {
2766                break;
2767            }
2768            let trial = surface.evaluate(next_u, next_v)?.sub(point).length_squared();
2769            if trial <= current {
2770                moved = taken(next_u, u, ua, ub, periodic.0).abs() > 1e-15 * (ub - ua)
2771                    || taken(next_v, v, va, vb, periodic.1).abs() > 1e-15 * (vb - va);
2772                u = next_u;
2773                v = next_v;
2774                current = trial;
2775                break;
2776            }
2777            du *= 0.5;
2778            dv *= 0.5;
2779        }
2780        if !moved {
2781            break;
2782        }
2783    }
2784    let result = NewtonResult {
2785        u,
2786        v,
2787        distance_squared: current,
2788        converged,
2789    };
2790    let on_edge =
2791        (!periodic.0 && (u <= ua || u >= ub)) || (!periodic.1 && (v <= va || v >= vb));
2792    Ok((result, on_edge))
2793}
2794
2795/// The growth of an internal node's box over its children's, per unit of
2796/// the surface's scale.
2797const NODE_BOX_MARGIN: f64 = 1e-9;
2798
2799/// `BREP_PROJECTION_NODE_BOXES` (default on): the cell-tree walk also reads
2800/// each internal node's box, not only its sphere. `=0` walks on spheres alone,
2801/// as before. Read once.
2802fn node_boxes_enabled() -> bool {
2803    switch!("BREP_PROJECTION_NODE_BOXES", true)
2804}
2805
2806/// The walk of the global stage: every cell whose box comes nearer `point`
2807/// than `bound`, with its box bound, in the walk's order, and the least bound
2808/// over everything the walk excluded.
2809///
2810/// A node is excluded when its sphere is no nearer than `bound`, and, with
2811/// `node_boxes`, when its box is not either. Cell spheres are loose on long,
2812/// thin cells (a 16 × 5632 lattice: about 3000 nodes visited and 200 cells
2813/// read per query to admit one), and an internal box is not. The box test
2814/// only removes subtrees whose every cell the cell test would reject, in the
2815/// same order, so the candidates are the same list to the bit with and
2816/// without it. Each internal box holds its children's boxes grown by
2817/// `node_margin` (`m`), and both bounds are read within `e` of their exact
2818/// value, `e` (below) set by the point's and the surface's magnitudes. A
2819/// box read at `b ≥ bound` with `b > 2e` is truly at least `b − e > 0` away,
2820/// so each cell box under it is truly at least `b − e + m` away and reads at
2821/// least `b − 2e + m ≥ bound` whenever `m ≥ 2e`; the test is skipped for a
2822/// point so far out that `4e > m` (beyond about 3·10⁴ scales), keeping half
2823/// of `m` for the rounding of the box corners themselves. Only the excluded
2824/// bound (the certificate in `GlobalStats::hull_lower_bound`) can differ: it
2825/// is still a lower bound, read from a tighter box.
2826fn hull_candidates(cells: &ProjectionCells, point: Vec3, bound: f64, node_boxes: bool) -> (Vec<(f64, usize)>, f64) {
2827    let read_error = 32.0 * f64::EPSILON * (point.x.abs() + point.y.abs() + point.z.abs() + 4.0 * cells.scale);
2828    let boxes = node_boxes && !cells.node_boxes.is_empty() && 4.0 * read_error <= cells.node_margin;
2829    let mut candidates: Vec<(f64, usize)> = Vec::new();
2830    let mut excluded = f64::INFINITY;
2831    let mut stack: Vec<u32> = Vec::with_capacity(64);
2832    stack.push((cells.tree.len() - 1) as u32);
2833    while let Some(index) = stack.pop() {
2834        let node = cells.tree[index as usize];
2835        let sphere_bound = (point.sub(node.centre).length() - node.radius).max(0.0);
2836        if sphere_bound >= bound {
2837            excluded = excluded.min(sphere_bound);
2838            continue;
2839        }
2840        match node.children {
2841            Some((first, second)) => {
2842                if boxes {
2843                    let box_bound = cells.node_boxes[index as usize].lower_bound(point);
2844                    if box_bound >= bound && box_bound > 2.0 * read_error {
2845                        excluded = excluded.min(box_bound);
2846                        continue;
2847                    }
2848                }
2849                stack.push(first);
2850                stack.push(second);
2851            }
2852            None => {
2853                let cell = node.cell as usize;
2854                let box_bound = cells.boxes[cell].lower_bound(point);
2855                if box_bound < bound {
2856                    candidates.push((box_bound, cell));
2857                } else {
2858                    excluded = excluded.min(box_bound);
2859                }
2860            }
2861        }
2862    }
2863    (candidates, excluded)
2864}
2865
2866/// The global stage of [`project_point_to_surface_general`]: replace `best`
2867/// with the least local minimum over every cell the hull bound admits.
2868#[allow(clippy::too_many_arguments)]
2869fn global_minimum(
2870    surface: &NurbsSurface,
2871    point: Vec3,
2872    domains: [f64; 4],
2873    periodic: (bool, bool),
2874    best: &mut NewtonResult,
2875    stats: &mut GlobalStats,
2876) -> Result<(), String> {
2877    if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2878        stats.settled_by_floor = true;
2879        return Ok(());
2880    }
2881    let Some(cells) = projection_cells(surface)? else {
2882        return Ok(());
2883    };
2884    let resolution = cells.resolution;
2885    let columns = cells.vs.len() - 1;
2886    let columns_u = cells.us.len() - 1;
2887    let mut bound = best.distance_squared.sqrt() - resolution;
2888
2889    // Every cell whose box comes nearer than the answer; the least bound over
2890    // what the walk excluded is the certificate.
2891    let (mut candidates, excluded) = hull_candidates(cells, point, bound, node_boxes_enabled());
2892    stats.candidates = candidates.len();
2893    candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
2894    stats.hull_lower_bound = candidates
2895        .first()
2896        .map_or(excluded, |&(least, _)| least.min(excluded));
2897
2898    // Cells already holding a verified minimum need no second descent. A foot
2899    // names ONE cell even when it sits on a lattice line shared by up to four:
2900    // a neighbour can hold a better basin of its own in its interior, and it
2901    // was admitted precisely because its bound beat this answer. The local
2902    // answer is one when it passes the same test the descent applies.
2903    let cell_of = |u: f64, v: f64| {
2904        let row = (cells.us.partition_point(|&value| value <= u).max(1) - 1).min(columns_u - 1);
2905        let column = (cells.vs.partition_point(|&value| value <= v).max(1) - 1).min(columns - 1);
2906        row * columns + column
2907    };
2908    let mut settled: Vec<usize> = Vec::new();
2909    if is_verified_minimum(surface, point, (best.u, best.v), domains, periodic)? {
2910        settled.push(cell_of(best.u, best.v));
2911    }
2912    for (cell_bound, cell) in candidates {
2913        if cell_bound >= bound {
2914            break;
2915        }
2916        let row = cell / columns;
2917        let column = cell % columns;
2918        let rectangle = [
2919            cells.us[row],
2920            cells.us[row + 1],
2921            cells.vs[column],
2922            cells.vs[column + 1],
2923        ];
2924        if settled.contains(&cell) {
2925            continue;
2926        }
2927        let mut seed = (rectangle[0], rectangle[2]);
2928        let mut seed_distance = f64::INFINITY;
2929        for (node_row, node_column) in
2930            [(row, column), (row + 1, column), (row, column + 1), (row + 1, column + 1)]
2931        {
2932            let distance = cells.nodes[node_row * cells.vs.len() + node_column]
2933                .sub(point)
2934                .length_squared();
2935            if distance < seed_distance {
2936                seed_distance = distance;
2937                seed = (cells.us[node_row], cells.vs[node_column]);
2938            }
2939        }
2940        stats.refinements += 1;
2941        let (confined, on_edge) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2942        let mut found = confined;
2943        if on_edge && confined.distance_squared.sqrt() < bound {
2944            // The cell's least point is on its edge and beats the answer:
2945            // the basin continues past the cell.
2946            stats.continuations += 1;
2947            let (continued, _) =
2948                confined_descent(surface, point, (confined.u, confined.v), domains, periodic)?;
2949            if continued.distance_squared < found.distance_squared {
2950                found = continued;
2951            }
2952            if continued.converged {
2953                settled.push(cell_of(continued.u, continued.v));
2954            }
2955        }
2956        if found.distance_squared.sqrt() < bound {
2957            *best = found;
2958            bound = best.distance_squared.sqrt() - resolution;
2959            stats.replaced = true;
2960            if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2961                return Ok(());
2962            }
2963        }
2964    }
2965    Ok(())
2966}
2967
2968
2969
2970/// Domain handling for a local foot-point Newton walk.
2971#[derive(Clone, Copy)]
2972pub enum FootDomain {
2973    Clamp,
2974    Wrap,
2975    Extended,
2976}
2977
2978#[derive(Clone, Copy)]
2979pub struct CurveFootPolicy {
2980    pub domain: FootDomain,
2981    pub iterations: usize,
2982    pub slope_guard: f64,
2983    pub step_limit: f64,
2984    pub parameter_tolerance: f64,
2985    pub mode: FootMode,
2986}
2987
2988/// Acceptance and convergence differ between a distance minimum and a stationary root.
2989#[derive(Clone, Copy)]
2990pub enum FootMode {
2991    Monotone,
2992    Witness,
2993    Stationary { positive_slope: bool, relative_step: bool },
2994    Backtracked,
2995    Planar,
2996}
2997
2998/// Local Newton foot. Seeding and enumeration of local minima belong to the caller.
2999/// Returns the last parameter, best witnessed parameter, and squared distance.
3000fn curve_foot_newton_state(
3001    curve: &NurbsCurve,
3002    point: Vec3,
3003    seed: f64,
3004    bracket: [f64; 2],
3005    policy: CurveFootPolicy,
3006) -> Result<(f64, f64, f64), String> {
3007    let fit = |u| match policy.domain {
3008        FootDomain::Clamp => fit_parameter(u, bracket[0], bracket[1], false),
3009        FootDomain::Wrap => fit_parameter(u, bracket[0], bracket[1], true),
3010        FootDomain::Extended => u,
3011    };
3012    let extended = matches!(policy.domain, FootDomain::Extended) || matches!(policy.mode, FootMode::Backtracked);
3013    let planar = matches!(policy.mode, FootMode::Planar);
3014    let project = |p: Vec3| if planar { Vec3::new(p.x, p.y, 0.0) } else { p };
3015    let point = project(point);
3016    let distance = |u| -> Result<f64, String> {
3017        let p = if extended { curve.derivatives_extended(u, 0)?[0] } else { curve.evaluate(u)? };
3018        Ok(project(p).sub(point).length())
3019    };
3020    let monotone = matches!(policy.mode, FootMode::Monotone | FootMode::Backtracked);
3021    let witness = matches!(policy.mode, FootMode::Witness);
3022    let mut u = if witness { seed } else { fit(seed) };
3023    let mut nearest_u = seed;
3024    let mut nearest_squared = f64::INFINITY;
3025    let mut best = if monotone { distance(u)? } else { f64::INFINITY };
3026    for _ in 0..policy.iterations {
3027        let derivatives = if extended {
3028            let values = curve.derivatives_extended(u, 2)?;
3029            [values[0], values[1], values[2]]
3030        } else if matches!(policy.mode, FootMode::Stationary { .. })
3031            || (planar && !crate::curve::small_curve_derivatives_enabled()) {
3032            let values = curve.derivatives(u, 2)?;
3033            [values[0], values[1], values[2]]
3034        } else {
3035            curve.derivatives_small(u, 2)?
3036        }.map(project);
3037        let offset = derivatives[0].sub(point);
3038        let numerator = offset.dot(derivatives[1]);
3039        let denominator = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
3040        if witness {
3041            let squared = offset.length_squared();
3042            if squared < nearest_squared {
3043                nearest_u = u;
3044                nearest_squared = squared;
3045            }
3046            let residual_length = squared.sqrt();
3047            if residual_length <= LINEAR_TOLERANCE
3048                || numerator.abs() <= EPSILON + 1e-10 * derivatives[1].length() * residual_length {
3049                break;
3050            }
3051        }
3052        let singular = if planar { denominator.abs() < policy.slope_guard }
3053            else { denominator.abs() <= policy.slope_guard };
3054        if singular || (matches!(policy.mode, FootMode::Stationary { positive_slope: true, .. }) && !(denominator > 0.0)) { break; }
3055        let mut step = if matches!(policy.mode, FootMode::Backtracked) && !(denominator > 0.0) {
3056            policy.step_limit.copysign(numerator)
3057        } else {
3058            (numerator / denominator).clamp(-policy.step_limit, policy.step_limit)
3059        };
3060        let mut next = fit(u - step);
3061        let mut next_distance = if monotone { distance(next)? } else { f64::INFINITY };
3062        if matches!(policy.mode, FootMode::Backtracked) {
3063            for _ in 0..30 {
3064                if next_distance < best { break; }
3065                step *= 0.5;
3066                next = fit(u - step);
3067                next_distance = distance(next)?;
3068            }
3069            if !(next_distance < best) { break; }
3070        } else if monotone && next_distance >= best { break; }
3071        let moved = if planar || matches!(policy.domain, FootDomain::Extended) { step }
3072            else if matches!(policy.domain, FootDomain::Wrap) {
3073                let period = bracket[1] - bracket[0];
3074                let raw = next - u;
3075                raw - period * (raw / period).round()
3076            } else { next - u };
3077        let tolerance = if matches!(policy.mode, FootMode::Stationary { relative_step: true, .. }) {
3078            policy.parameter_tolerance * (1.0 + u.abs())
3079        } else { policy.parameter_tolerance };
3080        let small = if planar || matches!(policy.mode, FootMode::Backtracked) { moved.abs() < tolerance }
3081            else { moved.abs() <= tolerance };
3082        if small && matches!(policy.mode, FootMode::Monotone) { break; }
3083        u = next;
3084        best = next_distance;
3085        if small { break; }
3086    }
3087    if witness { return Ok((u, nearest_u, nearest_squared)); }
3088    if !monotone { best = distance(u)?; }
3089    Ok((u, u, best * best))
3090}
3091
3092pub fn curve_foot_newton(
3093    curve: &NurbsCurve, point: Vec3, seed: f64, bracket: [f64; 2], policy: CurveFootPolicy,
3094) -> Result<(f64, f64), String> {
3095    let (_, nearest, squared) = curve_foot_newton_state(curve, point, seed, bracket, policy)?;
3096    Ok((nearest, squared))
3097}
3098
3099
3100
3101
3102