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    // The order's storage is kept between scans (one per projection seed).
290    thread_local! {
291        static ORDER: std::cell::Cell<Vec<(f64, usize)>> = const { std::cell::Cell::new(Vec::new()) };
292    }
293    let mut order = ORDER.with(|kept| kept.take());
294    order.clear();
295    order.extend(set.blocks.iter().enumerate().map(|(b, block)| {
296        let (dx, dy, dz) = (gap(block.low.x, block.high.x, point.x), gap(block.low.y, block.high.y, point.y), gap(block.low.z, block.high.z, point.z));
297        let cushion = 64.0 * f64::EPSILON * (point.length() + block.low.length() + block.high.length());
298        let reach = ((dx * dx + dy * dy + dz * dz).sqrt() * (1.0 - 1e-9) - cushion).max(0.0);
299        (reach * reach, b)
300    }));
301    order.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
302    let samples = &set.samples;
303    let (mut best, mut best_index) = (f64::INFINITY, usize::MAX);
304    let (mut witness, mut witness_index) = (f64::INFINITY, usize::MAX);
305    for &(bound, b) in &order {
306        if bound > best.max(witness) {
307            break;
308        }
309        let first = b * SEED_BLOCK;
310        let last = (first + SEED_BLOCK).min(samples.len());
311        for i in first..last {
312            let (_, sample) = samples[i];
313            let distance_squared = sample.sub(point).length_squared();
314            if distance_squared < best || (distance_squared == best && best_index != usize::MAX && i < best_index) {
315                best = distance_squared;
316                best_index = i;
317            }
318            if i > 0 {
319                let segment = point_segment_distance_squared(point, samples[i - 1].1, sample);
320                if segment < witness || (segment == witness && witness_index != usize::MAX && i < witness_index) {
321                    witness = segment;
322                    witness_index = i;
323                }
324            }
325        }
326    }
327    let mut scan = SeedScan { best_u: start, best_distance_squared: f64::INFINITY, witness_distance_squared: f64::INFINITY, witness_low: start, witness_high: start };
328    if best_index != usize::MAX {
329        scan.best_u = samples[best_index].0;
330        scan.best_distance_squared = best;
331    }
332    if witness_index != usize::MAX {
333        scan.witness_distance_squared = witness;
334        scan.witness_low = samples[witness_index - 1].0;
335        scan.witness_high = samples[witness_index].0;
336    }
337    ORDER.with(|kept| kept.set(order));
338    scan
339}
340const CURVE_SEED_BUDGET: usize = 262_144;
341thread_local! {
342    static CURVE_SEEDS: std::cell::RefCell<(rustc_hash::FxHashMap<[u64; 2], CurveSeeds>, usize)> = Default::default();
343}
344
345/// Discard the calling thread's bounded seed geometry at a history boundary.
346/// Other workers retain their own content-keyed entries until local eviction,
347/// an explicit clear on that worker, or thread exit. This is deliberately not
348/// a pool-wide invalidation: curve content fully determines every stored bit.
349/// Each worker retains at most 262,144 samples (8 MiB payload) and 4096 keys;
350/// temporary sampling and an outstanding borrowed snapshot are additional.
351pub fn clear_curve_seed_cache() {
352    CURVE_SEEDS.with(|memo| *memo.borrow_mut() = Default::default());
353}
354
355fn visit_curve_seeds(curve: &NurbsCurve, start: f64, end: f64, mut visit: impl FnMut(f64, Vec3)) -> Result<(), String> {
356    let mut breaks = vec![start];
357    breaks.extend(interior_knots(&curve.knots, curve.degree));
358    breaks.push(end);
359    let samples_per_span = 4usize.max(curve.degree + 2);
360    for pair in breaks.windows(2) {
361        for index in 0..=samples_per_span {
362            let parameter = pair[0] + (pair[1] - pair[0]) * index as f64 / samples_per_span as f64;
363            visit(parameter, curve.evaluate(parameter)?);
364        }
365    }
366    Ok(())
367}
368
369/// Cache only the curve-dependent seed geometry, in its original sequence.
370/// Every query still performs the same distance comparisons, witness search,
371/// Newton iterations and tie breaking. The content key includes every knot
372/// and homogeneous control bit; failed sampling is never retained.
373fn cached_curve_seeds(curve: &NurbsCurve, start: f64, end: f64) -> Result<Option<CurveSeeds>, String> {
374    if !switch!("BREP_CURVE_PROJECTION_SEEDS", true) { return Ok(None); }
375    // Avoid allocating a giant one-off vector even when it would not be kept.
376    let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
377    if bound > CURVE_SEED_BUDGET { return Ok(None); }
378    let mut key = crate::identity_hash::TwoLane::new();
379    crate::identity_hash::hash_curve(&mut key, curve);
380    key.f64(start); key.f64(end);
381    let key = key.finish();
382    if let Some(seeds) = CURVE_SEEDS.with(|memo| memo.borrow().0.get(&key).cloned()) {
383        return Ok(Some(seeds));
384    }
385    let mut seeds = Vec::new();
386    visit_curve_seeds(curve, start, end, |u, point| seeds.push((u, point)))?;
387    let seeds: CurveSeeds = std::rc::Rc::new(SeedSet::new(seeds));
388    CURVE_SEEDS.with(|memo| {
389        let mut memo = memo.borrow_mut();
390        if memo.0.len() >= PROJECTION_MEMO_ENTRIES || memo.1 + seeds.len() > CURVE_SEED_BUDGET {
391            memo.0.clear(); memo.1 = 0;
392        }
393        memo.1 += seeds.len();
394        memo.0.insert(key, seeds.clone());
395    });
396    Ok(Some(seeds))
397}
398
399fn project_point_to_curve_uncached(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
400    let [start, end] = curve.domain()?;
401    let seeds = cached_curve_seeds(curve, start, end)?;
402    project_point_to_curve_seeded(curve, point, seeds.as_deref())
403}
404
405/// A curve held with its seed samples, for a caller that projects onto the same curve again and
406/// again (an extrusion's reduced profile): the projector reads the held samples instead of
407/// hashing the curve's content into the seed cache on every call. Same samples, same answer.
408#[derive(Clone)]
409pub struct HeldCurve {
410    pub(crate) curve: NurbsCurve,
411    seeds: Option<SeedSet>,
412}
413
414impl std::fmt::Debug for HeldCurve {
415    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
416        f.debug_struct("HeldCurve").field("curve", &self.curve).field("seeds", &self.seeds.as_ref().map(|s| s.samples.len())).finish()
417    }
418}
419
420impl HeldCurve {
421    pub fn new(curve: NurbsCurve) -> Self {
422        let seeds = curve.domain().ok().and_then(|[start, end]| {
423            let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
424            if bound > CURVE_SEED_BUDGET { return None; }
425            let mut samples = Vec::new();
426            visit_curve_seeds(&curve, start, end, |u, point| samples.push((u, point))).ok()?;
427            Some(SeedSet::new(samples))
428        });
429        Self { curve, seeds }
430    }
431
432    /// The curve without its samples: [`Self::project`] is then `project_point_to_curve`.
433    pub(crate) fn bare(curve: NurbsCurve) -> Self {
434        Self { curve, seeds: None }
435    }
436
437    /// `project_point_to_curve(&self.curve, point)`, bit for bit. A straight curve keeps the
438    /// projector's own memo, and a curve whose samples are not held goes the projector's way.
439    pub fn project(&self, point: Vec3) -> Result<CurveProjection, String> {
440        match &self.seeds {
441            Some(seeds) if !(projection_memo_enabled() && straight_projection_key(&self.curve, point).is_some()) => {
442                project_point_to_curve_seeded(&self.curve, point, Some(seeds))
443            }
444            _ => project_point_to_curve(&self.curve, point),
445        }
446    }
447}
448
449fn project_point_to_curve_seeded(curve: &NurbsCurve, point: Vec3, seeds: Option<&SeedSet>) -> Result<CurveProjection, String> {
450    let [start, end] = curve.domain()?;
451    let mut best_u = start;
452    let mut best_distance_squared = f64::INFINITY;
453    // The sweep's FIRST sample is exactly `start` and its LAST is exactly `end`
454    // (`breaks` opens at `start` and closes at `end`, and index 0 / index
455    // `samples_per_span` hit a span's own ends), so closure costs no extra
456    // evaluation: keep those two points and compare them.
457    let mut start_point = None;
458    let mut end_point = None;
459    // The sampled polyline's own nearest approach, and the seed interval that
460    // achieves it. Squared throughout, so the sweep pays no square root.
461    let mut previous: Option<(f64, Vec3)> = None;
462    let mut witness_distance_squared = f64::INFINITY;
463    let mut witness_low = start;
464    let mut witness_high = start;
465    let mut visit = |parameter, sample: Vec3| {
466        if start_point.is_none() {
467            start_point = Some(sample);
468        }
469        end_point = Some(sample);
470        let distance_squared = sample.sub(point).length_squared();
471        if distance_squared < best_distance_squared {
472            best_distance_squared = distance_squared;
473            best_u = parameter;
474        }
475        if let Some((previous_parameter, previous_sample)) = previous {
476            let segment = point_segment_distance_squared(point, previous_sample, sample);
477            if segment < witness_distance_squared {
478                witness_distance_squared = segment;
479                witness_low = previous_parameter;
480                witness_high = parameter;
481            }
482        }
483        previous = Some((parameter, sample));
484    };
485    match seeds.filter(|set| !set.samples.is_empty() && (seed_blocks_enabled() || seed_blocks_check())) {
486        Some(set) => {
487            let scan = if seed_blocks_check() {
488                let linear = linear_seed_scan(&set.samples, point, start);
489                let blocked = blocked_seed_scan(set, point, start);
490                let bits = |s: &SeedScan| [s.best_u, s.best_distance_squared, s.witness_distance_squared, s.witness_low, s.witness_high].map(f64::to_bits);
491                if bits(&linear) != bits(&blocked) {
492                    panic!("curve seed blocks check: blocked scan {blocked:?} differs from the linear scan {linear:?} at {point:?}");
493                }
494                linear
495            } else {
496                blocked_seed_scan(set, point, start)
497            };
498            best_u = scan.best_u;
499            best_distance_squared = scan.best_distance_squared;
500            witness_distance_squared = scan.witness_distance_squared;
501            witness_low = scan.witness_low;
502            witness_high = scan.witness_high;
503            start_point = Some(set.samples[0].1);
504            end_point = Some(set.samples[set.samples.len() - 1].1);
505        }
506        None => match seeds {
507            Some(seeds) => {
508                for &(parameter, sample) in seeds.iter() { visit(parameter, sample); }
509            }
510            None => visit_curve_seeds(curve, start, end, visit)?,
511        },
512    }
513    // A closed curve's domain is PERIODIC, so Newton must wrap across the seam
514    // rather than stop at it. Clamping made the projector return the seam for
515    // any query whose foot sits within half a seed spacing of it: `start` and
516    // `end` are the same POINT, the sweep keeps the first of equal distances and
517    // so seeds at `start`, and a Newton step toward a foot just BEFORE the seam
518    // is then clamped back to `start`, reads as a zero-length step, and breaks.
519    // Measured on a rational-quadratic circle of radius 20: 4.796 mm out, for a
520    // point taken off the curve itself. Swapping the sweep's tie-break to keep
521    // the LAST equal sample does not fix this — it mirrors it, returning the
522    // same 4.796 mm for queries just AFTER the seam. The surface projector has
523    // always wrapped (`fit_parameter` at the `project_point_to_surface` Newton
524    // step); this is the curve side catching up.
525    const CLOSED_SEAM_TOLERANCE: f64 = 1e-6;
526    let closed = match (start_point, end_point) {
527        (Some(first), Some(last)) => first.sub(last).length() <= CLOSED_SEAM_TOLERANCE,
528        _ => false,
529    };
530
531    let parameter = curve_newton(
532        curve,
533        point,
534        best_u,
535        start,
536        end,
537        closed,
538        &mut best_u,
539        &mut best_distance_squared,
540    )?;
541    for candidate in [start, end, parameter] {
542        let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
543        if distance_squared < best_distance_squared {
544            best_distance_squared = distance_squared;
545            best_u = candidate;
546        }
547    }
548    // AN ANSWER THE SEED POLYLINE REFUTES IS NOT AN ANSWER. The sweep's
549    // consecutive samples are a polyline that approximates the curve, so the
550    // nearest that polyline passes to the query is a witness: the curve
551    // demonstrably comes about that close. When the answer is FARTHER than the
552    // witness by more than a factor of two, Newton converged in the wrong basin
553    // and the seed interval the witness names is where the foot really is.
554    //
555    // Two different defects reach here, both of them "a point ON the curve does
556    // not project to its own parameter", and both measured on real geometry:
557    //
558    // * A STATIONARY seed. Newton is a first-order method and
559    //   `f = C'(t) · (C(t) - P)` vanishes at a stationary parameter for EVERY
560    //   `P`, so the iteration reads convergence there whatever the point is, and
561    //   the step it would otherwise take is `-f/f''`, a second-order quantity
562    //   whose sign has nothing to do with where the foot is. The 2026-09-14
563    //   herringbone document is full of them: a flank pcurve is a two-span cubic
564    //   whose first two control points COINCIDE (an involute's speed is
565    //   `r_base * t`, so its Hermite start tangent is exactly zero), the sweep's
566    //   nearest sample to a query near the start IS that cusp, and a point lying
567    //   exactly on the curve at t = 0.125 answered t = 0, 2.159e-2 out in uv.
568    //   That is the wrong answer `build_loop`'s partial-run rescue declined on.
569    // * A seed grid coarser in ONE span than in the rest. An imported pcurve
570    //   from `abc_00000013.step` carries 511 interior knots whose first span is
571    //   eighty times the width of the median, and five samples per span leave
572    //   its samples 4.6e-3 of uv apart — so a point on the curve at fraction
573    //   0.01 read as 3.969e-3 from a DIFFERENT branch at fraction 0.99, which
574    //   was genuinely nearer than any sample of its own.
575    //
576    // The witness refuted both by 71x and by 293000x. Every update below is a
577    // strict improvement on the distance already found, so a rescue that finds
578    // nothing better leaves the answer exactly where it was.
579    const WITNESS_FACTOR: f64 = 2.0;
580    if witness_distance_squared * (WITNESS_FACTOR * WITNESS_FACTOR) < best_distance_squared
581        && witness_rescue_enabled()
582    {
583        let bracketed = bracketed_nearest(curve, point, witness_low, witness_high)?;
584        let polished = curve_newton(
585            curve,
586            point,
587            bracketed,
588            start,
589            end,
590            closed,
591            &mut best_u,
592            &mut best_distance_squared,
593        )?;
594        for candidate in [bracketed, polished] {
595            let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
596            if distance_squared < best_distance_squared {
597                best_distance_squared = distance_squared;
598                best_u = candidate;
599            }
600        }
601    }
602    let projected = curve.evaluate(best_u)?;
603    Ok(CurveProjection {
604        u: best_u,
605        point: projected,
606        distance: projected.sub(point).length(),
607    })
608}
609
610fn project_linear_revolution(
611    surface: &NurbsSurface,
612    point: Vec3,
613) -> Result<Option<SurfaceProjection>, String> {
614    let rows = &surface.control_points;
615    if surface.degree_u != 2
616        || surface.degree_v != 1
617        || rows.len() < 5
618        || rows[0].len() != 2
619        || !surface.closed_directions()?.0
620    {
621        return Ok(None);
622    }
623    let base = rows[0][0].point()?.add(rows[4][0].point()?).scale(0.5);
624    let top = rows[0][1].point()?.add(rows[4][1].point()?).scale(0.5);
625    let axis_vector = top.sub(base);
626    let height = axis_vector.length();
627    if height <= EPSILON {
628        return Ok(None);
629    }
630    let axis = axis_vector.normalized()?;
631    let [v0, v1] = surface.domain_v()?;
632    let axial = point.sub(base).dot(axis).clamp(0.0, height);
633    let v = v0 + (v1 - v0) * axial / height;
634    let circle = surface.iso_curve_v(v)?;
635    let projection = project_point_to_curve(&circle, point)?;
636    let [u0, u1] = surface.domain_u()?;
637    let u = projection.u.clamp(u0, u1);
638    let projected = surface.evaluate(u, v)?;
639    Ok(Some(SurfaceProjection {
640        u,
641        v,
642        point: projected,
643        distance: projected.sub(point).length(),
644    }))
645}
646
647#[derive(Clone, Copy)]
648struct NewtonResult {
649    u: f64,
650    v: f64,
651    distance_squared: f64,
652    converged: bool,
653}
654
655fn surface_newton(
656    surface: &NurbsSurface,
657    point: Vec3,
658    seed_u: f64,
659    seed_v: f64,
660    domains: [f64; 4],
661    closed_u: bool,
662    closed_v: bool,
663) -> Result<NewtonResult, String> {
664    surface_newton_impl(surface, point, seed_u, seed_v, domains, closed_u, closed_v,
665        switch!("BREP_PROJECTION_LAZY_DERIVATIVES", false), LINEAR_TOLERANCE)
666}
667
668/// Most seeded verification queries are already on the carrier. Row zero
669/// uses the same basis and rational arithmetic at counts zero and two; read
670/// it first, preserving the best-point and distance exit, and compute the
671/// remaining derivatives only when Newton actually needs to take a step.
672fn surface_newton_impl(
673    surface: &NurbsSurface,
674    point: Vec3,
675    seed_u: f64,
676    seed_v: f64,
677    domains: [f64; 4],
678    closed_u: bool,
679    closed_v: bool,
680    lazy: bool,
681    linear_tolerance: f64,
682) -> Result<NewtonResult, String> {
683    let [u0, u1, v0, v1] = domains;
684    let mut u = seed_u;
685    let mut v = seed_v;
686    let mut converged = false;
687    let mut best = NewtonResult {
688        u,
689        v,
690        distance_squared: surface.evaluate(u, v)?.sub(point).length_squared(),
691        converged,
692    };
693    // A step is a function of (u, v) alone, so an iterate that returns to an
694    // earlier one bit for bit repeats that stretch until the iteration cap:
695    // no exit fires (none did on the first pass through it), the best point
696    // cannot improve (every state of the stretch has been read, and the
697    // comparison is strict), and the state the cap would leave is the stretch's
698    // state at the cap's index. Take that state now instead of walking there
699    // (`BREP_PROJECTION_NEWTON_CYCLE_EXIT`, default on; `=0` walks). Measured
700    // on one import with fitted high-degree carriers and the projected-foot
701    // refine on: about one Newton call in eighteen ran to the cap, those calls
702    // held half of all Newton iterations, and at least three in five of them
703    // were repeating a stretch of eight states or fewer.
704    let cycle_exit = switch!("BREP_PROJECTION_NEWTON_CYCLE_EXIT", true);
705    let mut trail = [(0u64, 0u64); MAX_NEWTON_ITERATIONS];
706    for iteration in 0..MAX_NEWTON_ITERATIONS {
707        if cycle_exit {
708            let state = (u.to_bits(), v.to_bits());
709            if let Some(first) = trail[..iteration].iter().position(|earlier| *earlier == state) {
710                let period = iteration - first;
711                let (last_u, last_v) = trail[first + (MAX_NEWTON_ITERATIONS - first) % period];
712                u = f64::from_bits(last_u);
713                v = f64::from_bits(last_v);
714                crate::work_counts::add(|c| c.newton_iterations += (MAX_NEWTON_ITERATIONS - iteration) as u64);
715                break;
716            }
717            trail[iteration] = state;
718        }
719        crate::work_counts::add(|c| c.newton_iterations += 1);
720        let derivatives = surface.derivatives_small(u, v, if lazy { 0 } else { 2 })?;
721        let residual = derivatives[0][0].sub(point);
722        let distance_squared = residual.length_squared();
723        if distance_squared < best.distance_squared {
724            best.u = u;
725            best.v = v;
726            best.distance_squared = distance_squared;
727        }
728        let residual_length = distance_squared.sqrt();
729        if residual_length <= linear_tolerance {
730            crate::work_counts::add(|c| { c.newton_unused += 1; c.newton_unused_first += u64::from(iteration == 0); });
731            converged = true;
732            break;
733        }
734        let derivatives = if lazy { surface.derivatives_small(u, v, 2)? } else { derivatives };
735        let f = derivatives[1][0].dot(residual);
736        let g = derivatives[0][1].dot(residual);
737        let tangent_u_length = derivatives[1][0].length();
738        let tangent_v_length = derivatives[0][1].length();
739        let cosine_u = if tangent_u_length * residual_length <= EPSILON {
740            0.0
741        } else {
742            f.abs() / (tangent_u_length * residual_length)
743        };
744        let cosine_v = if tangent_v_length * residual_length <= EPSILON {
745            0.0
746        } else {
747            g.abs() / (tangent_v_length * residual_length)
748        };
749        if cosine_u <= 1e-10 && cosine_v <= 1e-10 {
750            converged = true;
751            break;
752        }
753        let j00 = derivatives[2][0].dot(residual) + derivatives[1][0].length_squared();
754        let j01 = derivatives[1][1].dot(residual) + derivatives[1][0].dot(derivatives[0][1]);
755        let j11 = derivatives[0][2].dot(residual) + derivatives[0][1].length_squared();
756        let determinant = j00 * j11 - j01 * j01;
757        if determinant.abs() <= EPSILON {
758            break;
759        }
760        let mut du = (-f * j11 + g * j01) / determinant;
761        let mut dv = (-g * j00 + f * j01) / determinant;
762        du = du.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
763        dv = dv.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
764        let next_u = fit_parameter(u + du, u0, u1, closed_u);
765        let next_v = fit_parameter(v + dv, v0, v1, closed_v);
766        let stalled =
767            (next_u - u).abs() <= 1e-15 * (u1 - u0) && (next_v - v).abs() <= 1e-15 * (v1 - v0);
768        u = next_u;
769        v = next_v;
770        if stalled {
771            break;
772        }
773    }
774    let final_distance_squared = surface.evaluate(u, v)?.sub(point).length_squared();
775    if final_distance_squared < best.distance_squared {
776        best.u = u;
777        best.v = v;
778        best.distance_squared = final_distance_squared;
779    }
780    best.converged = converged;
781    Ok(best)
782}
783
784/// Refine an existing branch foot for precision trim construction. The normal
785/// projector's distance exit is an on-carrier admission test, not a bound on
786/// tangential placement suitable for interpolating a more accurate trim.
787pub fn refine_trim_foot(
788    surface: &NurbsSurface, point: Vec3, foot: SurfaceProjection,
789) -> Result<SurfaceProjection, String> {
790    let [u0, u1] = surface.domain_u()?;
791    let [v0, v1] = surface.domain_v()?;
792    let (cu, cv) = surface.closed_directions()?;
793    let result = surface_newton_impl(surface, point, foot.u, foot.v,
794        [u0, u1, v0, v1], cu, cv, false, 1e-11)?;
795    let projected = surface.evaluate(result.u, result.v)?;
796    Ok(SurfaceProjection { u: result.u, v: result.v, point: projected,
797        distance: projected.sub(point).length() })
798}
799
800/// The point of `surface` nearest `point`, over the surface's whole domain.
801///
802/// Analytic carriers answer in closed form; every other surface goes through
803/// `project_point_to_surface_general`, which says what it guarantees.
804/// `#[track_caller]` names the call site in the `BREP_PROJECTION_AUDIT` log.
805#[track_caller]
806pub fn project_point_to_surface(
807    surface: &NurbsSurface,
808    point: Vec3,
809) -> Result<SurfaceProjection, String> {
810    crate::work_counts::add(|c| c.projection_global += 1);
811    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_PROJECT, surface);
812    // Recognized analytic carriers (plane / cylinder / cone / sphere /
813    // torus) have exact closed-form projections in the surface's own
814    // rational parameterization — skip grid seeding and Newton entirely.
815    if let Some(analytic) = surface.analytic() {
816        if let Some(projection) = analytic.project(surface, point) {
817            return Ok(projection);
818        }
819    }
820    if let Some(ellipsoid) = surface.affine_sphere() {
821        if let Some(projection) = ellipsoid.project(surface, point) {
822            return Ok(projection);
823        }
824    }
825    if switch!("BREP_EXTRUSION_PROJECTION", true) {
826        if let Some(projection) = surface.linear_extrusion().and_then(|e| e.project(surface,point)) {
827            return Ok(projection);
828        }
829    }
830    project_point_to_surface_general(surface, point)
831}
832
833/// [`project_point_to_surface`] without the general projector's global stage:
834/// the same closed forms on analytic, ellipsoid and extrusion carriers, and on
835/// any other carrier Newton from the seed grid's nearest sample
836/// ([`project_point_to_surface_from_nearest_seed`]). A local foot: its distance
837/// is an upper bound on the nearest point's. For a caller that only needs a
838/// start on the surface near the point, such as a Newton's opening iterate.
839pub fn project_point_to_surface_local(
840    surface: &NurbsSurface,
841    point: Vec3,
842) -> Result<SurfaceProjection, String> {
843    if let Some(analytic) = surface.analytic() {
844        if let Some(projection) = analytic.project(surface, point) {
845            return Ok(projection);
846        }
847    }
848    if let Some(ellipsoid) = surface.affine_sphere() {
849        if let Some(projection) = ellipsoid.project(surface, point) {
850            return Ok(projection);
851        }
852    }
853    if switch!("BREP_EXTRUSION_PROJECTION", true) {
854        if let Some(projection) = surface.linear_extrusion().and_then(|e| e.project(surface, point)) {
855            return Ok(projection);
856        }
857    }
858    project_point_to_surface_from_nearest_seed(surface, point)
859}
860
861/// Project a point onto a surface starting Newton from an explicit `(u, v)`
862/// guess, WITHOUT the global grid seed. This is a footpoint refiner for
863/// continuity-preserving curve-on-surface tracing: seeding each edge sample
864/// from its neighbour's parameters keeps the fit on ONE branch of a surface
865/// that folds back over the small trimmed patch, where an independent global
866/// search would snap to whichever fold is momentarily closest and tear the
867/// pcurve into a self-crossing zig-zag. The caller compares the returned
868/// `distance` against the global answer and only adopts this result when it is
869/// geometrically just as valid, so a bad seed can never make a fit worse.
870pub fn project_point_to_surface_seeded(
871    surface: &NurbsSurface,
872    point: Vec3,
873    seed_u: f64,
874    seed_v: f64,
875) -> Result<SurfaceProjection, String> {
876    crate::work_counts::add(|c| c.projection_seeded += 1);
877    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
878    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_SEEDED, surface);
879    // An ellipsoid's foot is unique off its medial axis: the closed form IS
880    // the branch answer, as it is for the analytic carriers at the seeded
881    // entry (`project_point_to_surface_from_seed`).
882    if let Some(ellipsoid) = surface.affine_sphere() {
883        if let Some(projection) = ellipsoid.project(surface, point) {
884            return Ok(projection);
885        }
886    }
887    let [u0, u1] = surface.domain_u()?;
888    let [v0, v1] = surface.domain_v()?;
889    let (closed_u, closed_v) = surface.closed_directions()?;
890    let result = surface_newton(
891        surface,
892        point,
893        seed_u,
894        seed_v,
895        [u0, u1, v0, v1],
896        closed_u,
897        closed_v,
898    )?;
899    let projected = surface.evaluate(result.u, result.v)?;
900    Ok(SurfaceProjection {
901        u: result.u,
902        v: result.v,
903        point: projected,
904        distance: projected.sub(point).length(),
905    })
906}
907
908/// The foot of `point` on the branch of `seed`: the closed form on an analytic
909/// carrier, otherwise Newton from the caller's own `(u, v)`
910/// ([`project_point_to_surface_seeded`]), WITHOUT the global search.
911///
912/// **Which callers.** One that already holds a foot on this surface from a
913/// geometrically adjacent query and whose output needs continuity with it: a
914/// pcurve's previous sample, a march's previous station, a Newton's previous
915/// iterate. [`project_point_to_surface`] answers a different question — where
916/// on the WHOLE surface the point is nearest — and on a carrier that comes back
917/// near itself, or for an off-surface query about as far from two sheets, that
918/// answer is a foot on another branch: a pcurve sample on the wrong sheet, an
919/// iterate that jumps. A caller with no such foot (a vertex, a probe, the first
920/// station) asks the nearest-point question and calls the projector.
921///
922/// **An analytic carrier** answers in closed form, as the projector does. Its
923/// only places with two equally valid feet are its seam, its poles and its focal
924/// set (axis, centre, tube circle), and the closed form answers those exactly as
925/// the nearest-point query always has; no march on one changes.
926///
927/// **What it does not promise.** It is a local answer: its distance is an upper
928/// bound, and a Newton that stalls returns its best iterate without saying so.
929/// Every caller keeps its own on-surface check.
930///
931/// **Instruments**, each read once. `BREP_PROJECTION_FROM_SEED=0` returns
932/// [`project_point_to_surface`]'s answer at every caller (the reading before
933/// 2026-09-15, for a same-binary A/B); `BREP_PROJECTION_FROM_SEED_SITES=<a,b,…>`
934/// keeps the seeded answer only at the call sites whose `file:line` contains
935/// one of the substrings. Under `BREP_PROJECTION_AUDIT=<dir>` every query whose
936/// seeded foot lies farther than the on-surface floor from the nearest point's
937/// foot appends one line to `<dir>/projection-seed-audit-<pid>.tsv`. That
938/// comparand is the nearest-point projector under the same caller, so its own
939/// replacements land in `projection-audit-<pid>.tsv` at this site's line: they
940/// are the audit's, not an answer the caller took.
941#[track_caller]
942pub fn project_point_to_surface_from_seed(
943    surface: &NurbsSurface,
944    point: Vec3,
945    seed: [f64; 2],
946) -> Result<SurfaceProjection, String> {
947    crate::work_counts::add(|c| c.projection_from_seed += 1);
948    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
949    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_SEED, surface);
950    if let Some(analytic) = surface.analytic() {
951        if let Some(projection) = analytic.project(surface, point) {
952            return Ok(projection);
953        }
954    }
955    if let Some(ellipsoid) = surface.affine_sphere() {
956        if let Some(projection) = ellipsoid.project(surface, point) {
957            return Ok(projection);
958        }
959    }
960    let caller = std::panic::Location::caller();
961    if !seeded_answer_admitted(caller) {
962        return project_point_to_surface_general(surface, point);
963    }
964    let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
965    if seed_audit_enabled() {
966        let nearest = project_point_to_surface_general(surface, point)?;
967        if seeded.point.sub(nearest.point).length() > LINEAR_TOLERANCE {
968            seed_audit_record(caller, surface, seed, &seeded, &nearest);
969        }
970    }
971    Ok(seeded)
972}
973
974/// `BREP_PROJECTION_FROM_SEED=0` / `BREP_PROJECTION_FROM_SEED_SITES`: see
975/// [`project_point_to_surface_from_seed`].
976fn seeded_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
977    static SITES: std::sync::OnceLock<Option<Option<Vec<String>>>> = std::sync::OnceLock::new();
978    let sites = SITES.get_or_init(|| {
979        if std::env::var("BREP_PROJECTION_FROM_SEED").as_deref() == Ok("0") {
980            return None;
981        }
982        Some(std::env::var("BREP_PROJECTION_FROM_SEED_SITES").ok().map(|value| {
983            value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect()
984        }))
985    });
986    match sites {
987        None => false,
988        Some(None) => true,
989        Some(Some(only)) => {
990            let location = format!("{}:{}", caller.file(), caller.line());
991            only.iter().any(|site| location.contains(site.as_str()))
992        }
993    }
994}
995
996fn seed_audit_enabled() -> bool {
997    debug_flag!("BREP_PROJECTION_AUDIT")
998}
999
1000/// One line per seeded answer whose foot is not the nearest point's: the call
1001/// site, both distances, the seed, both feet's `(u, v)`, the separation of the
1002/// two feet and the surface's shape.
1003fn seed_audit_record(
1004    caller: &std::panic::Location<'_>,
1005    surface: &NurbsSurface,
1006    seed: [f64; 2],
1007    seeded: &SurfaceProjection,
1008    nearest: &SurfaceProjection,
1009) {
1010    use std::io::Write;
1011    static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1012        std::sync::OnceLock::new();
1013    let sink = SINK.get_or_init(|| {
1014        let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1015        let path = std::path::Path::new(&directory)
1016            .join(format!("projection-seed-audit-{}.tsv", std::process::id()));
1017        std::fs::OpenOptions::new()
1018            .create(true)
1019            .append(true)
1020            .open(path)
1021            .ok()
1022            .map(std::sync::Mutex::new)
1023    });
1024    if let Some(file) = sink {
1025        if let Ok(mut file) = file.lock() {
1026            let _ = writeln!(
1027                file,
1028                "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.6e}\t{}x{} cp {}x{}",
1029                caller.file(),
1030                caller.line(),
1031                seeded.distance,
1032                nearest.distance,
1033                seed[0],
1034                seed[1],
1035                seeded.u,
1036                seeded.v,
1037                nearest.u,
1038                nearest.v,
1039                seeded.point.sub(nearest.point).length(),
1040                surface.degree_u,
1041                surface.degree_v,
1042                surface.control_points.len(),
1043                surface.control_points.first().map(Vec::len).unwrap_or(0),
1044            );
1045        }
1046    }
1047}
1048
1049/// The Newton seed grid for general projection: (u, v, point) samples over
1050/// every knot span. A pure function of the surface, cached on it — building
1051/// the grid costs hundreds of evaluations and projection is the hottest
1052/// entry point in the kernel.
1053fn projection_seed_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
1054    if let Some(grid) = surface.projection_grid.get() {
1055        return Ok(grid);
1056    }
1057    tables_within_limit(surface)?;
1058    let [u0, u1] = surface.domain_u()?;
1059    let [v0, v1] = surface.domain_v()?;
1060    let (closed_u, closed_v) = surface.closed_directions()?;
1061    let mut breaks_u = vec![u0];
1062    breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
1063    breaks_u.push(u1);
1064    let mut breaks_v = vec![v0];
1065    breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
1066    breaks_v.push(v1);
1067    let samples_u = if closed_u {
1068        8usize.max(surface.degree_u * 4)
1069    } else {
1070        3usize.max(surface.degree_u + 1)
1071    };
1072    let samples_v = if closed_v {
1073        8usize.max(surface.degree_v * 4)
1074    } else {
1075        3usize.max(surface.degree_v + 1)
1076    };
1077    let mut grid = Vec::with_capacity((breaks_u.len() - 1) * (breaks_v.len() - 1) * (samples_u + 1) * (samples_v + 1));
1078    for u_pair in breaks_u.windows(2) {
1079        for v_pair in breaks_v.windows(2) {
1080            for i in 0..=samples_u {
1081                for j in 0..=samples_v {
1082                    let u = u_pair[0] + (u_pair[1] - u_pair[0]) * i as f64 / samples_u as f64;
1083                    let v = v_pair[0] + (v_pair[1] - v_pair[0]) * j as f64 / samples_v as f64;
1084                    grid.push((u, v, surface.evaluate(u, v)?));
1085                }
1086            }
1087        }
1088    }
1089    Ok(surface.projection_grid.get_or_init(|| SampleGrid::new(grid)))
1090}
1091
1092/// The dense fallback grid for degenerate general projection: (u, v, point)
1093/// over a `(count_u+1) × (count_v+1)` lattice with `count_u/count_v` derived
1094/// from the surface's knot spans. A pure function of the surface, cached on
1095/// it — on metre-unit-mm parts the degenerate fallback fires ~1.7M times and
1096/// each re-evaluated all ~561 lattice points; caching them makes the argmin a
1097/// pure distance scan over reused points (bit-identical seed).
1098fn projection_dense_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
1099    if let Some(grid) = surface.projection_dense_grid.get() {
1100        return Ok(grid);
1101    }
1102    tables_within_limit(surface)?;
1103    let [u0, u1] = surface.domain_u()?;
1104    let [v0, v1] = surface.domain_v()?;
1105    let mut breaks_u = vec![u0];
1106    breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
1107    breaks_u.push(u1);
1108    let mut breaks_v = vec![v0];
1109    breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
1110    breaks_v.push(v1);
1111    let count_u = 32usize.max((breaks_u.len() - 1) * 8);
1112    let count_v = 16usize.max((breaks_v.len() - 1) * 8);
1113    let mut grid = Vec::with_capacity((count_u + 1) * (count_v + 1));
1114    for i in 0..=count_u {
1115        for j in 0..=count_v {
1116            let u = u0 + (u1 - u0) * i as f64 / count_u as f64;
1117            let v = v0 + (v1 - v0) * j as f64 / count_v as f64;
1118            grid.push((u, v, surface.evaluate(u, v)?));
1119        }
1120    }
1121    Ok(surface.projection_dense_grid.get_or_init(|| SampleGrid::with_tree(grid)))
1122}
1123
1124/// Samples per block of a [`SampleGrid`].
1125const SAMPLE_BLOCK: usize = 32;
1126
1127/// Runs per group: the scan's second level, a box over [`GROUP_BLOCKS`]
1128/// consecutive runs ([`SampleGrid::groups`]).
1129const GROUP_BLOCKS: usize = 32;
1130
1131/// A cached `(u, v, point)` sample grid, with the axis-aligned box of each run
1132/// of [`SAMPLE_BLOCK`] consecutive samples, so the nearest-sample scan
1133/// ([`nearest_sample`]) skips a run none of whose samples can beat the answer
1134/// it holds.
1135#[derive(Clone, Debug)]
1136pub struct SampleGrid {
1137    samples: Vec<(f64, f64, Vec3)>,
1138    blocks: Vec<SampleBlock>,
1139    /// The union box of each [`GROUP_BLOCKS`] consecutive runs, prunable only
1140    /// when every run in it is. A union box's floor is at most each of its
1141    /// runs' floors as computed (the box faces are the runs' own, and the gap
1142    /// to a face farther out is no larger, IEEE rounding being monotone).
1143    groups: Vec<SampleBlock>,
1144    /// The box tree over the runs ([`nearest_sample_tree`]): `tree[0]` boxes
1145    /// each [`TREE_FANOUT`] consecutive runs, `tree[k]` each [`TREE_FANOUT`]
1146    /// consecutive boxes of `tree[k - 1]`, up to a single root. Built only by
1147    /// [`SampleGrid::with_tree`] (the dense grid), and empty when the grid has
1148    /// at most one group of runs.
1149    tree: Vec<Vec<SampleBlock>>,
1150}
1151
1152/// Children per node of [`SampleGrid::tree`].
1153const TREE_FANOUT: usize = 4;
1154
1155/// The union box of consecutive boxes, prunable only when each of them is.
1156fn union_boxes(boxes: &[SampleBlock]) -> Vec<SampleBlock> {
1157    boxes
1158        .chunks(TREE_FANOUT)
1159        .map(|chunk| {
1160            let mut union = chunk[0];
1161            for block in chunk {
1162                union.low = Vec3::new(union.low.x.min(block.low.x), union.low.y.min(block.low.y), union.low.z.min(block.low.z));
1163                union.high = Vec3::new(union.high.x.max(block.high.x), union.high.y.max(block.high.y), union.high.z.max(block.high.z));
1164                union.prunable &= block.prunable;
1165            }
1166            union
1167        })
1168        .collect()
1169}
1170
1171/// One run's box. `prunable` is false when a sample has a non-finite
1172/// coordinate: the box says nothing about it, and the run is always scanned.
1173#[derive(Clone, Copy, Debug)]
1174struct SampleBlock {
1175    low: Vec3,
1176    high: Vec3,
1177    prunable: bool,
1178}
1179
1180impl SampleGrid {
1181    fn new(samples: Vec<(f64, f64, Vec3)>) -> Self {
1182        let blocks = samples
1183            .chunks(SAMPLE_BLOCK)
1184            .map(|chunk| {
1185                let mut low = chunk[0].2;
1186                let mut high = low;
1187                let mut prunable = true;
1188                for &(_, _, p) in chunk {
1189                    prunable &= p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
1190                    low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
1191                    high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
1192                }
1193                SampleBlock { low, high, prunable }
1194            })
1195            .collect::<Vec<_>>();
1196        let groups = blocks
1197            .chunks(GROUP_BLOCKS)
1198            .map(|chunk| {
1199                let mut group = chunk[0];
1200                for block in chunk {
1201                    group.low = Vec3::new(group.low.x.min(block.low.x), group.low.y.min(block.low.y), group.low.z.min(block.low.z));
1202                    group.high = Vec3::new(group.high.x.max(block.high.x), group.high.y.max(block.high.y), group.high.z.max(block.high.z));
1203                    group.prunable &= block.prunable;
1204                }
1205                group
1206            })
1207            .collect();
1208        Self { samples, blocks, groups, tree: Vec::new() }
1209    }
1210
1211    /// The grid with its box tree, for a scan that starts from a held answer
1212    /// (the dense fallback after a Newton): there the tree reads few floors.
1213    /// A scan from no answer reads its bound from a greedy descent, which on a
1214    /// surface whose boxes mostly hold the point lands on an arbitrary run;
1215    /// ABC 00027566's seed scans took 75 s through the tree against 44 s
1216    /// through the groups, so the seed grid keeps the groups.
1217    fn with_tree(samples: Vec<(f64, f64, Vec3)>) -> Self {
1218        let mut grid = Self::new(samples);
1219        if grid.blocks.len() > GROUP_BLOCKS {
1220            grid.tree.push(union_boxes(&grid.blocks));
1221            while grid.tree.last().is_some_and(|level| level.len() > 1) {
1222                let next = union_boxes(grid.tree.last().unwrap());
1223                grid.tree.push(next);
1224            }
1225        }
1226        grid
1227    }
1228}
1229
1230impl SampleBlock {
1231    /// A floor on `sample.sub(point).length_squared()` over the run's samples,
1232    /// as COMPUTED, not only as real numbers: per axis the gap from `point` to
1233    /// the box is the same subtraction against the box face, and IEEE rounding
1234    /// is monotone, so `|fl(s - p)| >= fl(face - p)`; squaring and the same
1235    /// left-to-right sum of non-negative terms keep the order (`Vec3::dot`
1236    /// has no fused multiply-add). A NaN `point` reads gaps of 0 and every
1237    /// distance is NaN, which no scan takes, so skipping changes nothing.
1238    fn lower_bound(&self, point: Vec3) -> f64 {
1239        let gap = |p: f64, low: f64, high: f64| {
1240            if p < low {
1241                low - p
1242            } else if p > high {
1243                p - high
1244            } else {
1245                0.0
1246            }
1247        };
1248        let x = gap(point.x, self.low.x, self.high.x);
1249        let y = gap(point.y, self.low.y, self.high.y);
1250        let z = gap(point.z, self.low.z, self.high.z);
1251        x * x + y * y + z * z
1252    }
1253}
1254
1255/// `BREP_PROJECTION_PRUNED_SCAN=0` scans every sample, as before 2026-11-10,
1256/// for a same-binary A/B. Read once per process.
1257fn pruned_scan() -> bool {
1258    switch!("BREP_PROJECTION_PRUNED_SCAN", true)
1259}
1260
1261/// Replace `best` with the grid's nearest sample when that is strictly nearer,
1262/// the first such in scan order: the bits of the linear scan, which this was
1263/// until 2026-11-10. A run is skipped only when its box's floor is not below
1264/// the distance held, so none of its samples could have replaced it (the
1265/// strict `<`), or lies above the bound read first ([`bound_first_scan`]),
1266/// and the runs are visited in scan order. ABC 00027566's
1267/// 166-span rational faces take the dense fallback on 71% of their pcurve
1268/// probes (the first Newton not converged), each scanning 22.7k samples: 9.1 s
1269/// of a face's 11.5 s of local answers.
1270fn nearest_sample(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1271    if !grid.tree.is_empty() && scan_tree() && pruned_scan() && bound_first_scan() {
1272        nearest_sample_tree(grid, point, best);
1273        return;
1274    }
1275    nearest_sample_with(grid, point, best, pruned_scan(), bound_first_scan());
1276}
1277
1278/// `BREP_PROJECTION_SCAN_TREE=0` scans through the two levels of groups and
1279/// runs alone, as before 2026-11-11, for a same-binary A/B. Read once per
1280/// process.
1281///
1282/// With it on, a grid built with a tree ([`SampleGrid::with_tree`]: the dense
1283/// grid, when it has more than one group) is scanned through
1284/// [`SampleGrid::tree`]. ABC 00027566's dense fallback on its 166-span faces
1285/// passed 52 of 287 group boxes per call (a group is a strip across the
1286/// surface, and many strips' boxes hold a point on it) and then read 1680 run
1287/// floors to scan 0.65 runs, never improving the answer it held: 26 s of floors
1288/// at one pcurve site.
1289fn scan_tree() -> bool {
1290    switch!("BREP_PROJECTION_SCAN_TREE", true)
1291}
1292
1293/// `BREP_PROJECTION_SCAN_HINT=0` reads the bound from the descent alone, as
1294/// before 2026-11-11, for a same-binary A/B. Read once per process.
1295///
1296/// With it on, a bound-first scan also reads the run that held the answer of
1297/// the last scan of the same grid on this thread. Consecutive queries are
1298/// mostly neighbours (a pcurve's probes): ABC 00027566's busiest pcurve site
1299/// found its answer in the previous answer's run on 98.8% of seed scans, while
1300/// the descent's run held it on 40%; with the hint the bound is the answer on
1301/// 99.4% and the seed scans there fell from 43.6 s to 18.4 s.
1302fn scan_hint() -> bool {
1303    switch!("BREP_PROJECTION_SCAN_HINT", true)
1304}
1305
1306const HINT_SLOTS: usize = 8;
1307
1308thread_local! {
1309    /// Direct-mapped by grid address: (grid samples address, run of its last answer).
1310    static SCAN_HINTS: std::cell::Cell<[(usize, usize); HINT_SLOTS]> =
1311        const { std::cell::Cell::new([(0, usize::MAX); HINT_SLOTS]) };
1312}
1313
1314fn hint_slot(grid: &SampleGrid) -> (usize, usize) {
1315    let address = grid.samples.as_ptr() as usize;
1316    (address, (address >> 4) % HINT_SLOTS)
1317}
1318
1319/// The bound lowered by the hinted run's samples. The hint is only a run
1320/// index: it is range-checked and read from the grid in hand, so a stale one
1321/// (another grid at a reused address) costs time, never bits. It lowers the
1322/// BOUND alone, never the answer held: each value it can take is a real
1323/// sample distance, at least the grid's least distance `m`, which is all the
1324/// bound-first argument asks of it.
1325fn hinted_bound(grid: &SampleGrid, point: Vec3, mut bound: f64) -> f64 {
1326    if !scan_hint() {
1327        return bound;
1328    }
1329    let (address, slot) = hint_slot(grid);
1330    let (held, run) = SCAN_HINTS.with(|hints| hints.get()[slot]);
1331    if held != address || run >= grid.blocks.len() || !grid.blocks[run].prunable {
1332        return bound;
1333    }
1334    let start = run * SAMPLE_BLOCK;
1335    let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1336    for &(_, _, sample) in &grid.samples[start..end] {
1337        let distance_squared = sample.sub(point).length_squared();
1338        if distance_squared < bound {
1339            bound = distance_squared;
1340        }
1341    }
1342    bound
1343}
1344
1345/// Remember the run that last improved the answer of a scan of `grid`.
1346fn remember_hint(grid: &SampleGrid, run: Option<usize>) {
1347    if let Some(run) = run.filter(|_| scan_hint()) {
1348        let (address, slot) = hint_slot(grid);
1349        SCAN_HINTS.with(|hints| {
1350            let mut all = hints.get();
1351            all[slot] = (address, run);
1352            hints.set(all);
1353        });
1354    }
1355}
1356
1357/// [`nearest_sample_with`]'s bound-first scan over the box tree: the bound is
1358/// read from the run reached by descending from the root through the child of
1359/// lowest floor (a real sample distance, or the incoming one, so never below
1360/// the grid's least distance `m`), then the tree is visited depth first in
1361/// scan order, skipping a box whose floor is at or above the distance held or
1362/// strictly above the bound. A union box's floor is at most each of its
1363/// children's as computed (the box faces are theirs, and IEEE rounding is
1364/// monotone), so a box is skipped only when every run under it would have
1365/// been, and the runs that are read are read in scan order: the bits of the
1366/// linear scan, by the argument [`nearest_sample_with`] gives for its groups.
1367fn nearest_sample_tree(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1368    let top = grid.tree.len() - 1;
1369    let mut bound = best.distance_squared;
1370    // Descend: at each level the child of lowest floor among the prunable ones.
1371    let mut node = 0usize;
1372    let mut reached = true;
1373    for level in (0..=top).rev() {
1374        let children = |count: usize| node * TREE_FANOUT..((node + 1) * TREE_FANOUT).min(count);
1375        let below = if level == 0 { &grid.blocks } else { &grid.tree[level - 1] };
1376        match lowest_floor(below, children(below.len()), point) {
1377            Some(child) => node = child,
1378            None => {
1379                reached = false;
1380                break;
1381            }
1382        }
1383    }
1384    if reached {
1385        let start = node * SAMPLE_BLOCK;
1386        let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1387        for &(_, _, sample) in &grid.samples[start..end] {
1388            let distance_squared = sample.sub(point).length_squared();
1389            if distance_squared < bound {
1390                bound = distance_squared;
1391            }
1392        }
1393    }
1394    let bound = hinted_bound(grid, point, bound);
1395    let skip = |box_: &SampleBlock, held: f64| {
1396        if !box_.prunable {
1397            return false;
1398        }
1399        let floor = box_.lower_bound(point);
1400        floor >= held || floor > bound
1401    };
1402    let mut answer_run = None;
1403    // Depth first in scan order: (level, index), level 0 of the stack meaning a run.
1404    let mut stack: Vec<(usize, usize)> = Vec::with_capacity(TREE_FANOUT * (top + 2));
1405    stack.push((top + 1, 0));
1406    while let Some((level, index)) = stack.pop() {
1407        if level == 0 {
1408            if skip(&grid.blocks[index], best.distance_squared) {
1409                continue;
1410            }
1411            let start = index * SAMPLE_BLOCK;
1412            let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1413            let held = best.distance_squared;
1414            scan_run(&grid.samples[start..end], point, best);
1415            if best.distance_squared < held {
1416                answer_run = Some(index);
1417            }
1418            continue;
1419        }
1420        if skip(&grid.tree[level - 1][index], best.distance_squared) {
1421            continue;
1422        }
1423        let count = if level == 1 { grid.blocks.len() } else { grid.tree[level - 2].len() };
1424        let children = index * TREE_FANOUT..((index + 1) * TREE_FANOUT).min(count);
1425        // Pushed last-first so they pop in scan order.
1426        for child in children.rev() {
1427            stack.push((level - 1, child));
1428        }
1429    }
1430    remember_hint(grid, answer_run);
1431}
1432
1433/// `BREP_PROJECTION_BOUND_FIRST=0` prunes against the distance held alone, as
1434/// on 2026-11-10 before this pass, for a same-binary A/B. Read once per
1435/// process.
1436///
1437/// With it on, the runs are boxed again in groups of [`GROUP_BLOCKS`]. The scan
1438/// first reads the run of lowest floor inside the group of lowest floor and
1439/// takes the nearest of its samples as a BOUND, then visits the groups and
1440/// their runs in scan order, skipping any whose floor is at or above the
1441/// distance held or strictly above that bound. The runs alone started the seed
1442/// scan from no answer (its incoming distance is infinite), so every run ahead
1443/// of the nearest sample was read before the held distance fell, and every
1444/// scan computed one floor per run: on ABC 00027566 the seed
1445/// scans averaged 63k samples (361 s over 5M calls) and the dense ones 180k
1446/// (167 s over 3.5M), while a bound over the runs alone cut the first to 190 s
1447/// but doubled the second to 311 s with its extra pass of floors.
1448fn bound_first_scan() -> bool {
1449    switch!("BREP_PROJECTION_BOUND_FIRST", true)
1450}
1451
1452/// The scan behind [`nearest_sample`]. With `bound_first`, the bound is the
1453/// smaller of the incoming distance and one real sample distance, so it is
1454/// never below the grid's least distance `m`. The first sample at `m` lies in
1455/// a run whose floor is at most `m`, hence not above the bound and not at or
1456/// above the distance held when the scan reaches it (every sample before it is
1457/// strictly farther than `m`): that run is read and the sample taken, as the
1458/// linear scan takes it, and nothing after it is strictly nearer. A run whose
1459/// floor is above the bound holds no sample at `m`. The bound pass reads only
1460/// prunable runs, and updates on a strict `<`, so a NaN never enters it.
1461fn nearest_sample_with(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult, pruned: bool, bound_first: bool) {
1462    if !(pruned && bound_first) {
1463        for (block, chunk) in grid.blocks.iter().zip(grid.samples.chunks(SAMPLE_BLOCK)) {
1464            if pruned && block.prunable && block.lower_bound(point) >= best.distance_squared {
1465                continue;
1466            }
1467            scan_run(chunk, point, best);
1468        }
1469        return;
1470    }
1471    // The bound: one real sample distance (or the incoming one), from the run
1472    // of lowest floor inside the group of lowest floor.
1473    let mut bound = best.distance_squared;
1474    let lowest_group = lowest_floor(&grid.groups, 0..grid.groups.len(), point);
1475    if let Some(group) = lowest_group {
1476        let runs = group * GROUP_BLOCKS..((group + 1) * GROUP_BLOCKS).min(grid.blocks.len());
1477        if let Some(run) = lowest_floor(&grid.blocks, runs, point) {
1478            let start = run * SAMPLE_BLOCK;
1479            let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1480            for &(_, _, sample) in &grid.samples[start..end] {
1481                let distance_squared = sample.sub(point).length_squared();
1482                if distance_squared < bound {
1483                    bound = distance_squared;
1484                }
1485            }
1486        }
1487    }
1488    let bound = hinted_bound(grid, point, bound);
1489    let skip = |box_: &SampleBlock, held: f64| {
1490        if !box_.prunable {
1491            return false;
1492        }
1493        let floor = box_.lower_bound(point);
1494        floor >= held || floor > bound
1495    };
1496    let mut answer_run = None;
1497    for (group_index, group) in grid.groups.iter().enumerate() {
1498        if skip(group, best.distance_squared) {
1499            continue;
1500        }
1501        let first = group_index * GROUP_BLOCKS;
1502        let last = (first + GROUP_BLOCKS).min(grid.blocks.len());
1503        for run in first..last {
1504            if skip(&grid.blocks[run], best.distance_squared) {
1505                continue;
1506            }
1507            let start = run * SAMPLE_BLOCK;
1508            let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1509            let held = best.distance_squared;
1510            scan_run(&grid.samples[start..end], point, best);
1511            if best.distance_squared < held {
1512                answer_run = Some(run);
1513            }
1514        }
1515    }
1516    remember_hint(grid, answer_run);
1517}
1518
1519/// The linear scan of one run: strict `<`, so the first of equal samples
1520/// stands.
1521fn scan_run(run: &[(f64, f64, Vec3)], point: Vec3, best: &mut NewtonResult) {
1522    for &(u, v, sample) in run {
1523        let distance_squared = sample.sub(point).length_squared();
1524        if distance_squared < best.distance_squared {
1525            best.u = u;
1526            best.v = v;
1527            best.distance_squared = distance_squared;
1528        }
1529    }
1530}
1531
1532/// The index, within `range`, of the prunable box of least floor (the first
1533/// on a tie), or None when none is prunable.
1534fn lowest_floor(boxes: &[SampleBlock], range: std::ops::Range<usize>, point: Vec3) -> Option<usize> {
1535    let mut lowest: Option<(usize, f64)> = None;
1536    for index in range {
1537        let box_ = &boxes[index];
1538        if !box_.prunable {
1539            continue;
1540        }
1541        let floor = box_.lower_bound(point);
1542        if lowest.is_none_or(|(_, held)| floor < held) {
1543            lowest = Some((index, floor));
1544        }
1545    }
1546    lowest.map(|(index, _)| index)
1547}
1548
1549// Boundary-ring cache geometry: 4 sides × 22 exponents × 33 indices. The scan
1550// positions depend only on the surface domain and these fixed integers, so the
1551// evaluated points are a pure function of the surface and cacheable.
1552const RING_EXPONENTS: usize = 22;
1553const RING_INDICES: usize = 33; // index 0..=32
1554
1555#[inline]
1556fn ring_slot(side: usize, exponent_index: usize, index: usize) -> usize {
1557    (side * RING_EXPONENTS + exponent_index) * RING_INDICES + index
1558}
1559
1560/// The boundary-ring sample points for the degenerate projection fallback,
1561/// flattened by `ring_slot(side, exponent-1, index)`. Sides: 0 = v-low
1562/// (`v = v0 + (v1-v0)·offset`), 1 = v-high (`v1 - (v1-v0)·offset`), 2 = u-low
1563/// (`u0 + (u1-u0)·offset`), 3 = u-high (`u1 - (u1-u0)·offset`), where
1564/// `offset = 1/2^exponent`. A pure function of the surface, cached on it — the
1565/// fallback's boundary ring re-evaluated these on every one of ~1.7M calls.
1566fn projection_ring_grid(surface: &NurbsSurface) -> Result<&[Vec3], String> {
1567    if let Some(grid) = surface.projection_ring_grid.get() {
1568        return Ok(grid);
1569    }
1570    let [u0, u1] = surface.domain_u()?;
1571    let [v0, v1] = surface.domain_v()?;
1572    let mut grid = vec![Vec3::default(); 4 * RING_EXPONENTS * RING_INDICES];
1573    for exponent in 1..=RING_EXPONENTS as i32 {
1574        let offset = 1.0 / 2f64.powi(exponent);
1575        let e = exponent as usize - 1;
1576        let v_lo = v0 + (v1 - v0) * offset;
1577        let v_hi = v1 - (v1 - v0) * offset;
1578        let u_lo = u0 + (u1 - u0) * offset;
1579        let u_hi = u1 - (u1 - u0) * offset;
1580        for index in 0..=32 {
1581            let u = u0 + (u1 - u0) * index as f64 / 32.0;
1582            grid[ring_slot(0, e, index as usize)] = surface.evaluate(u, v_lo)?;
1583            grid[ring_slot(1, e, index as usize)] = surface.evaluate(u, v_hi)?;
1584        }
1585        for index in 0..=32 {
1586            let v = v0 + (v1 - v0) * index as f64 / 32.0;
1587            grid[ring_slot(2, e, index as usize)] = surface.evaluate(u_lo, v)?;
1588            grid[ring_slot(3, e, index as usize)] = surface.evaluate(u_hi, v)?;
1589        }
1590    }
1591    Ok(surface.projection_ring_grid.get_or_init(|| grid))
1592}
1593
1594/// The LOCAL answer: Newton from the seed grid's single nearest sample (or the
1595/// linear-revolution foot), with the degenerate-parameterization fallbacks.
1596///
1597/// This is the whole of what the general projector returned before
1598/// 2026-09-14, and it is a local minimum, not the minimum: on a general patch
1599/// nearly closed in one direction the nearest sample can sit on the far end,
1600/// and Newton converges there (abc_00000026's thread flanks, 2.16e-2 .. 4.1e-2
1601/// against a true 1e-13). [`project_point_to_surface_general`] runs it first
1602/// and keeps its answer wherever no other basin beats it.
1603fn nearest_seed_answer(
1604    surface: &NurbsSurface,
1605    point: Vec3,
1606    [u0, u1, v0, v1]: [f64; 4],
1607    closed_u: bool,
1608    closed_v: bool,
1609) -> Result<NewtonResult, String> {
1610    let mut best = NewtonResult {
1611        u: u0,
1612        v: v0,
1613        distance_squared: f64::INFINITY,
1614        converged: false,
1615    };
1616    nearest_sample(projection_seed_grid(surface)?, point, &mut best);
1617    if let Some(revolution) = project_linear_revolution(surface, point)? {
1618        if revolution.distance * revolution.distance < best.distance_squared {
1619            best.u = revolution.u;
1620            best.v = revolution.v;
1621            best.distance_squared = revolution.distance * revolution.distance;
1622        }
1623    }
1624    let first_newton = surface_newton(
1625        surface,
1626        point,
1627        best.u,
1628        best.v,
1629        [u0, u1, v0, v1],
1630        closed_u,
1631        closed_v,
1632    )?;
1633    if first_newton.distance_squared < best.distance_squared {
1634        best = first_newton;
1635    }
1636    let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1637    let degenerate = su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length());
1638    if degenerate || !first_newton.converged {
1639        let mut grid = best;
1640        nearest_sample(projection_dense_grid(surface)?, point, &mut grid);
1641        if grid.distance_squared < best.distance_squared {
1642            best = grid;
1643        }
1644        let polished = surface_newton(
1645            surface,
1646            point,
1647            grid.u,
1648            grid.v,
1649            [u0, u1, v0, v1],
1650            closed_u,
1651            closed_v,
1652        )?;
1653        if polished.distance_squared < best.distance_squared {
1654            best = polished;
1655        }
1656
1657        let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1658        if su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length()) {
1659            let ring_grid = projection_ring_grid(surface)?;
1660            let mut ring = best;
1661            // Read the pre-evaluated ring points at the exact same parameter
1662            // positions the live scans used (side/exponent/index → `ring_slot`),
1663            // preserving scan order and argmin tie-breaking for bit-identity.
1664            let scan = |side: usize,
1665                        exponent_index: usize,
1666                        along_u: bool,
1667                        fixed: f64,
1668                        candidate: &mut NewtonResult| {
1669                for index in 0..=32 {
1670                    let moving = if along_u {
1671                        u0 + (u1 - u0) * index as f64 / 32.0
1672                    } else {
1673                        v0 + (v1 - v0) * index as f64 / 32.0
1674                    };
1675                    let (u, v) = if along_u {
1676                        (moving, fixed)
1677                    } else {
1678                        (fixed, moving)
1679                    };
1680                    let distance_squared = ring_grid
1681                        [ring_slot(side, exponent_index, index as usize)]
1682                    .sub(point)
1683                    .length_squared();
1684                    if distance_squared < candidate.distance_squared {
1685                        candidate.u = u;
1686                        candidate.v = v;
1687                        candidate.distance_squared = distance_squared;
1688                    }
1689                }
1690            };
1691            for exponent in 1..=22 {
1692                let offset = 1.0 / 2f64.powi(exponent);
1693                let e = exponent as usize - 1;
1694                if (best.v - v0).abs() <= (v1 - v0) * 0.02 {
1695                    scan(0, e, true, v0 + (v1 - v0) * offset, &mut ring);
1696                }
1697                if (best.v - v1).abs() <= (v1 - v0) * 0.02 {
1698                    scan(1, e, true, v1 - (v1 - v0) * offset, &mut ring);
1699                }
1700                if (best.u - u0).abs() <= (u1 - u0) * 0.02 {
1701                    scan(2, e, false, u0 + (u1 - u0) * offset, &mut ring);
1702                }
1703                if (best.u - u1).abs() <= (u1 - u0) * 0.02 {
1704                    scan(3, e, false, u1 - (u1 - u0) * offset, &mut ring);
1705                }
1706            }
1707            if ring.distance_squared < best.distance_squared {
1708                best = ring;
1709            }
1710            let polished = surface_newton(
1711                surface,
1712                point,
1713                ring.u,
1714                ring.v,
1715                [u0, u1, v0, v1],
1716                closed_u,
1717                closed_v,
1718            )?;
1719            if polished.distance_squared < best.distance_squared {
1720                best = polished;
1721            }
1722        }
1723    }
1724    Ok(best)
1725}
1726
1727/// Escape hatch for A/B measurement: `BREP_PROJECTION_GLOBAL=0` returns the
1728/// local answer alone ([`nearest_seed_answer`], the pre-2026-09-14 projector),
1729/// so a population run can be repeated with and without the global stage from
1730/// one binary. Read once.
1731fn global_stage_enabled() -> bool {
1732    switch!("BREP_PROJECTION_GLOBAL", true)
1733}
1734
1735/// `BREP_PROJECTION_GLOBAL_SITES=<a,b,…>`: the global stage's answer is kept
1736/// only for call sites whose `file:line` contains one of the comma-separated
1737/// substrings, and the local answer is returned everywhere else — so a result
1738/// that moves can be attributed to the call site that moved it.
1739/// `BREP_PROJECTION_GLOBAL_EXCEPT=<a,b,…>` is the complement: every site but
1740/// those. Unset: every site. Read once.
1741/// Whether a `BREP_PROJECTION_GLOBAL_SITES`/`_EXCEPT` filter is set, i.e.
1742/// whether [`project_point_to_surface`]'s answer can depend on its call site.
1743pub fn global_site_filter_active() -> bool {
1744    // Read once per process, like the site lists `global_answer_admitted`
1745    // reads: the common reader asks this for every probe (two `getenv` calls,
1746    // ~3.7% of the elephant's B12 prefix on the production sampler,
1747    // 2026-11-02), and nothing sets these variables after start-up.
1748    static ACTIVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1749    *ACTIVE.get_or_init(|| {
1750        std::env::var_os("BREP_PROJECTION_GLOBAL_SITES").is_some() || std::env::var_os("BREP_PROJECTION_GLOBAL_EXCEPT").is_some()
1751    })
1752}
1753
1754fn global_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
1755    fn list(name: &str) -> Option<Vec<String>> {
1756        std::env::var(name)
1757            .ok()
1758            .map(|value| value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect())
1759    }
1760    static SITES: std::sync::OnceLock<(Option<Vec<String>>, Option<Vec<String>>)> =
1761        std::sync::OnceLock::new();
1762    let (only, except) = SITES.get_or_init(|| {
1763        (list("BREP_PROJECTION_GLOBAL_SITES"), list("BREP_PROJECTION_GLOBAL_EXCEPT"))
1764    });
1765    if only.is_none() && except.is_none() {
1766        return true;
1767    }
1768    let location = format!("{}:{}", caller.file(), caller.line());
1769    let named = |sites: &Vec<String>| sites.iter().any(|site| location.contains(site.as_str()));
1770    only.as_ref().is_none_or(named) && !except.as_ref().is_some_and(named)
1771}
1772
1773/// `BREP_PROJECTION_AUDIT=<dir>`: every query on which the global stage
1774/// replaces the local answer appends one tab-separated line to
1775/// `<dir>/projection-audit-<pid>.tsv` — the call site, the local and the
1776/// global distance, both feet's `(u, v)` and the surface's shape. Per process,
1777/// because the case gate forks a child per case and loses its stderr.
1778fn audit_record(caller: &std::panic::Location<'_>, surface: &NurbsSurface, local: &NewtonResult, global: &NewtonResult) {
1779    use std::io::Write;
1780    static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1781        std::sync::OnceLock::new();
1782    let sink = SINK.get_or_init(|| {
1783        let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1784        let path = std::path::Path::new(&directory)
1785            .join(format!("projection-audit-{}.tsv", std::process::id()));
1786        std::fs::OpenOptions::new()
1787            .create(true)
1788            .append(true)
1789            .open(path)
1790            .ok()
1791            .map(std::sync::Mutex::new)
1792    });
1793    if let Some(file) = sink {
1794        if let Ok(mut file) = file.lock() {
1795            let _ = writeln!(
1796                file,
1797                "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{}x{} cp {}x{}",
1798                caller.file(),
1799                caller.line(),
1800                local.distance_squared.sqrt(),
1801                global.distance_squared.sqrt(),
1802                local.u,
1803                local.v,
1804                global.u,
1805                global.v,
1806                surface.degree_u,
1807                surface.degree_v,
1808                surface.control_points.len(),
1809                surface.control_points.first().map(Vec::len).unwrap_or(0),
1810            );
1811        }
1812    }
1813}
1814
1815/// The point of a general surface nearest `point`: the least local minimum of
1816/// the distance over the surface's whole domain.
1817///
1818/// **What it does.** First the local answer ([`nearest_seed_answer`]: Newton
1819/// from the nearest seed-grid sample, with its degenerate fallbacks — the whole
1820/// projector before 2026-09-14). Then the global stage ([`global_minimum`]):
1821/// the domain is cut into the cells of the projection lattice (every knot span
1822/// sampled `max(3, degree + 1)` times in an open direction and
1823/// `max(8, 4 × degree)` times in a closed one — the seed grid's own density),
1824/// and each cell is enclosed in a box built from the control points of the
1825/// surface REFINED to that cell. A NURBS patch with positive weights lies in
1826/// the convex hull of the control points that support it, so the distance from
1827/// the query to a cell's box is a rigorous LOWER bound on the distance to every
1828/// surface point of the cell. Every cell whose bound is below the best answer
1829/// so far is a candidate basin, and is refined by a descent confined to the
1830/// cell ([`confined_descent`]: Newton where the Hessian is positive definite,
1831/// the metric-scaled gradient where it is not, halved until the distance does
1832/// not rise, so it can end at a minimum but not at a saddle or a maximum),
1833/// seeded at the cell's nearest lattice node and continued over the domain
1834/// when the cell's least point is on its edge. The least answer wins. A closed
1835/// direction's seam is not special: the lattice spans the whole period, the
1836/// cells on either side of the seam are ordinary cells, and the continuation
1837/// wraps.
1838///
1839/// **What is guaranteed.**
1840/// * The answer is a point ON the surface, so its distance never under-reads.
1841/// * Every cell that could hold a point nearer than the answer by more than the
1842///   resolution has been descended in, unless it already held a verified
1843///   minimum: a cell left out was excluded by its hull bound, which cannot
1844///   over-read. [`GlobalStats::hull_lower_bound`] is that certificate: the
1845///   true distance lies in `[hull_lower_bound, answer]`, always.
1846/// * **The one step not certified in general: one basin in the cell that holds
1847///   the least minimum.** A descent finds the basin of its seed. A second basin
1848///   in any OTHER cell costs nothing — that cell's better basin is still no
1849///   nearer than the least minimum — but a second local minimum in the cell
1850///   holding the least minimum can catch the descent seeded at that cell's
1851///   nearest lattice node, and the least minimum is missed by at most
1852///   `answer − hull_lower_bound`. That takes a query past the focal distance of
1853///   part of the cell (farther than its radius of normal curvature on the
1854///   query's side, where the distance's Hessian `G − d·II` stops being positive
1855///   definite) or a cell whose image turns back toward the query. A descent that
1856///   runs out of iterations without a verified minimum fails the same way, with
1857///   the same bound. Seeding every corner of every candidate cell was measured
1858///   and changed no answer on the bench.
1859/// * **Certified on the analytic carriers** — the sphere, torus, cylinder and
1860///   cone, each a revolution of a circle or a line, and the plane. A lattice cell
1861///   there is an (azimuth × generatrix) rectangle under half a turn wide. In the
1862///   cell holding the least minimum the azimuthal derivative of the squared
1863///   distance, `2 ρ(v) ρ_P sin(λ − λ_P)`, vanishes only on the query's own
1864///   meridian, and moving toward that meridian lowers the distance from every
1865///   other point of the cell, so each local minimum over the cell is a local
1866///   minimum of the planar distance from the query's meridian image to the
1867///   generatrix over the cell's `v` range — exactly one on a circle arc under
1868///   half a turn or on a segment. At the focal sets (the axis, the sphere's
1869///   centre, the tube's centre circle) the minimum is a continuum of equal
1870///   distances and every foot is right. A general profile of revolution and a
1871///   general patch are not certified.
1872/// * Where the local answer is already the least minimum, it is returned
1873///   unchanged, bit for bit: the global stage replaces it only with a point
1874///   nearer by more than the resolution.
1875///
1876/// **The two numbers it reads.** The *on-surface floor* is `LINEAR_TOLERANCE`,
1877/// INHERITED unchanged: it is the local Newton's own stopping residual, and a
1878/// local answer within it of the query is on the surface and nothing is
1879/// searched. The *resolution* is the one new number, and it is the surface's
1880/// own: `(degree_u + 1)(degree_v + 1) · ε · scale`, `scale` the largest
1881/// control-point coordinate magnitude — the rounding of one evaluation, which
1882/// sums that many terms of that size. Every box is grown by it, and no
1883/// improvement finer than it is taken.
1884///
1885/// **What it costs.** A query settled by the floor costs what the local answer
1886/// always cost. Any other query builds the cell enclosure once per surface (one
1887/// knot refinement of the net to the lattice, cached on the surface beside the
1888/// seed grid), walks a bounding-sphere tree over the cells, and runs one
1889/// descent per candidate cell the hull bound does not exclude.
1890#[track_caller]
1891pub fn project_point_to_surface_general(
1892    surface: &NurbsSurface,
1893    point: Vec3,
1894) -> Result<SurfaceProjection, String> {
1895    if !surface_projection_memo_enabled() || !surface_projection_memo_admitted() {
1896        return project_point_to_surface_general_fresh(surface, point);
1897    }
1898    let key = (surface.content_key(), [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()], forced_switches_key());
1899    if let Some(hit) = SURFACE_PROJECTION_MEMO.with(|memo| memo.borrow().get(&key).copied()) {
1900        if surface_projection_memo_check() {
1901            let fresh = project_point_to_surface_general_fresh(surface, point)?;
1902            let bits = |p: &SurfaceProjection| [p.u.to_bits(), p.v.to_bits(), p.point.x.to_bits(), p.point.y.to_bits(), p.point.z.to_bits(), p.distance.to_bits()];
1903            assert_eq!(bits(&hit), bits(&fresh), "surface projection memo check: held {hit:?} vs fresh {fresh:?}");
1904        }
1905        return Ok(hit);
1906    }
1907    let answer = project_point_to_surface_general_fresh(surface, point)?;
1908    SURFACE_PROJECTION_MEMO.with(|memo| {
1909        let mut memo = memo.borrow_mut();
1910        if memo.len() >= SURFACE_PROJECTION_MEMO_ENTRIES {
1911            memo.clear();
1912        }
1913        memo.insert(key, answer);
1914    });
1915    Ok(answer)
1916}
1917
1918/// `BREP_SURFACE_PROJECTION_MEMO` (default on; =0 projects every call): the general projector keeps
1919/// its answers per thread, keyed by the surface's content hash
1920/// ([`NurbsSurface::content_key`]) and the point's bits, and answers a repeated
1921/// query from the memo. The projector is a pure function of the net and the
1922/// point (its grids and cells are built from the net), so a hit returns the
1923/// answer it computed. On a ball screwed round a tight helix 37% of the
1924/// general projections repeat one already made (the imprint's start points,
1925/// pierces and pair readings ask the same points again). Bypassed while a
1926/// call-site filter or the audit is set (they read the caller) and while
1927/// switches are read live (`BREP_ENV_READ_ONCE=0`); the switches a test forces
1928/// are part of the key. `BREP_SURFACE_PROJECTION_MEMO_CHECK=1` (with the memo
1929/// on) projects afresh on every hit and stops on any bit difference.
1930fn surface_projection_memo_enabled() -> bool {
1931    switch!("BREP_SURFACE_PROJECTION_MEMO", true)
1932}
1933
1934fn surface_projection_memo_check() -> bool {
1935    switch!("BREP_SURFACE_PROJECTION_MEMO_CHECK", false)
1936}
1937
1938/// No call-site filter and no audit (both read the caller), and switches read
1939/// once per process: under `BREP_ENV_READ_ONCE=0` a switch the projector reads
1940/// can change between two queries, which the key does not hold.
1941fn surface_projection_memo_admitted() -> bool {
1942    static CALLER_FREE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1943    crate::env_read::read_once_enabled() && *CALLER_FREE.get_or_init(|| {
1944        env_read!("BREP_PROJECTION_GLOBAL_SITES").is_none()
1945            && env_read!("BREP_PROJECTION_GLOBAL_EXCEPT").is_none()
1946            && env_read!("BREP_PROJECTION_AUDIT").is_none()
1947    })
1948}
1949
1950/// The switches a test forces on this thread, as part of the memo's key: an
1951/// answer read under one setting is never returned under another. Zero
1952/// outside tests.
1953fn forced_switches_key() -> u64 {
1954    0
1955}
1956
1957/// The memo's bound per thread: cleared when it holds this many answers. An
1958/// entry is 96 bytes (key and answer), so the table stays under about 3.2 MB
1959/// a thread for the thread's life (32k buckets at most), under the curve seed
1960/// cache's own budget. Entries are keyed by content, never stale; a long-lived
1961/// process (the app, the PLM worker) holds at most this per kernel thread.
1962const SURFACE_PROJECTION_MEMO_ENTRIES: usize = 1 << 14;
1963
1964thread_local! {
1965    static SURFACE_PROJECTION_MEMO: std::cell::RefCell<rustc_hash::FxHashMap<([u64; 2], [u64; 3], u64), SurfaceProjection>> = Default::default();
1966}
1967
1968#[track_caller]
1969fn project_point_to_surface_general_fresh(
1970    surface: &NurbsSurface,
1971    point: Vec3,
1972) -> Result<SurfaceProjection, String> {
1973    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_GENERAL, surface);
1974    let [u0, u1] = surface.domain_u()?;
1975    let [v0, v1] = surface.domain_v()?;
1976    let (closed_u, closed_v) = surface.closed_directions()?;
1977    let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1978    let mut best = local;
1979    if global_stage_enabled() {
1980        global_minimum(
1981            surface,
1982            point,
1983            [u0, u1, v0, v1],
1984            (closed_u, closed_v),
1985            &mut best,
1986            &mut GlobalStats::default(),
1987        )?;
1988        if best.u != local.u || best.v != local.v {
1989            let caller = std::panic::Location::caller();
1990            if global_answer_admitted(caller) {
1991                audit_record(caller, surface, &local, &best);
1992            } else {
1993                best = local;
1994            }
1995        }
1996    }
1997    let projected = surface.evaluate(best.u, best.v)?;
1998    Ok(SurfaceProjection {
1999        u: best.u,
2000        v: best.v,
2001        point: projected,
2002        distance: projected.sub(point).length(),
2003    })
2004}
2005
2006/// The single-seed inversion by itself: the closed form on an analytic
2007/// carrier, otherwise [`nearest_seed_answer`] — Newton from the seed grid's
2008/// nearest sample, WITHOUT the global stage. Its distance is an upper bound and
2009/// its foot a local minimum. It is not a nearest-point query: it exists for a
2010/// caller that asks a question ABOUT that inversion, and there is one —
2011/// `joint_branch_pcurves` (`io/step_import/builder/rims.rs`) offers a loop the
2012/// joint branch only when this inversion alternates between branches along it,
2013/// which it does on a carrier that comes back within one seed-grid spacing of
2014/// itself (`abc_00000026`'s nearly closed thread flanks).
2015pub fn project_point_to_surface_from_nearest_seed(
2016    surface: &NurbsSurface,
2017    point: Vec3,
2018) -> Result<SurfaceProjection, String> {
2019    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_NEAREST_SEED, surface);
2020    if let Some(analytic) = surface.analytic() {
2021        if let Some(projection) = analytic.project(surface, point) {
2022            return Ok(projection);
2023        }
2024    }
2025    if let Some(ellipsoid) = surface.affine_sphere() {
2026        if let Some(projection) = ellipsoid.project(surface, point) {
2027            return Ok(projection);
2028        }
2029    }
2030    let [u0, u1] = surface.domain_u()?;
2031    let [v0, v1] = surface.domain_v()?;
2032    let (closed_u, closed_v) = surface.closed_directions()?;
2033    let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
2034    let projected = surface.evaluate(local.u, local.v)?;
2035    Ok(SurfaceProjection {
2036        u: local.u,
2037        v: local.v,
2038        point: projected,
2039        distance: projected.sub(point).length(),
2040    })
2041}
2042
2043/// Both answers for one query, and what the global stage did — the bench's
2044/// seam (`examples/projector_bench.rs`). Not for kernel callers.
2045#[doc(hidden)]
2046pub fn project_point_to_surface_general_lanes(
2047    surface: &NurbsSurface,
2048    point: Vec3,
2049    run_global: bool,
2050) -> Result<(SurfaceProjection, GlobalStats), String> {
2051    let [u0, u1] = surface.domain_u()?;
2052    let [v0, v1] = surface.domain_v()?;
2053    let (closed_u, closed_v) = surface.closed_directions()?;
2054    let mut best = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
2055    let mut stats = GlobalStats::default();
2056    if run_global {
2057        global_minimum(surface, point, [u0, u1, v0, v1], (closed_u, closed_v), &mut best, &mut stats)?;
2058    }
2059    let projected = surface.evaluate(best.u, best.v)?;
2060    Ok((
2061        SurfaceProjection {
2062            u: best.u,
2063            v: best.v,
2064            point: projected,
2065            distance: projected.sub(point).length(),
2066        },
2067        stats,
2068    ))
2069}
2070
2071/// How many basins the cells of one query hold — the bench's measure of the
2072/// global stage's one uncertified step (see [`project_point_to_surface_general`]).
2073#[doc(hidden)]
2074#[derive(Clone, Debug, Default)]
2075pub struct BasinCensus {
2076    /// Cells whose hull bound is below the answer's distance: every cell the
2077    /// global stage could have descended in.
2078    pub cells: usize,
2079    /// Descents run: one from each corner of those cells and one from the middle.
2080    pub descents: usize,
2081    /// Descents that stopped without a verified minimum.
2082    pub unconverged: usize,
2083    /// Cells where two verified minima differ in distance by more than `bar`.
2084    /// Distances within the on-surface floor count as equal: the descent stops
2085    /// there, so two feet under it are one foot polished to different depths.
2086    pub cells_with_two_basins: usize,
2087    /// Of those, cells whose rectangle holds the least foot any descent found:
2088    /// the only cells where a second basin can cost the answer anything.
2089    pub foot_cells_with_two_basins: usize,
2090    /// The least distance any descent reached, and where.
2091    pub least: f64,
2092    pub least_uv: (f64, f64),
2093    /// Every descent in a two-basin cell that holds the least foot: the cell,
2094    /// its rectangle, the seed, where it stopped, its distance, and whether that
2095    /// is a verified minimum.
2096    pub foot_cell_descents: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)>,
2097}
2098
2099/// Descend in every cell whose hull bound is below `answer_distance` from each
2100/// of its corners and its middle, and count the cells whose verified minima
2101/// disagree by more than `bar`. For the bench only: it costs five descents per
2102/// cell, which the projector itself was measured not to need.
2103#[doc(hidden)]
2104pub fn project_point_to_surface_basin_census(
2105    surface: &NurbsSurface,
2106    point: Vec3,
2107    answer_distance: f64,
2108    bar: f64,
2109) -> Result<BasinCensus, String> {
2110    let mut census = BasinCensus {
2111        least: f64::INFINITY,
2112        ..BasinCensus::default()
2113    };
2114    let Some(cells) = projection_cells(surface)? else {
2115        return Ok(census);
2116    };
2117    let columns = cells.vs.len() - 1;
2118    let mut spreads: Vec<(usize, f64)> = Vec::new();
2119    let mut runs: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)> = Vec::new();
2120    for (cell, cell_box) in cells.boxes.iter().enumerate() {
2121        if cell_box.lower_bound(point) >= answer_distance {
2122            continue;
2123        }
2124        census.cells += 1;
2125        let (row, column) = (cell / columns, cell % columns);
2126        let rectangle = [cells.us[row], cells.us[row + 1], cells.vs[column], cells.vs[column + 1]];
2127        let middle = ((rectangle[0] + rectangle[1]) * 0.5, (rectangle[2] + rectangle[3]) * 0.5);
2128        let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
2129        for seed in [
2130            (rectangle[0], rectangle[2]),
2131            (rectangle[1], rectangle[2]),
2132            (rectangle[0], rectangle[3]),
2133            (rectangle[1], rectangle[3]),
2134            middle,
2135        ] {
2136            census.descents += 1;
2137            let (found, _) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2138            let distance = found.distance_squared.sqrt();
2139            runs.push((cell, rectangle, seed, (found.u, found.v), distance, found.converged));
2140            if distance < census.least {
2141                census.least = distance;
2142                census.least_uv = (found.u, found.v);
2143            }
2144            if !found.converged {
2145                census.unconverged += 1;
2146                continue;
2147            }
2148            low = low.min(distance.max(LINEAR_TOLERANCE));
2149            high = high.max(distance.max(LINEAR_TOLERANCE));
2150        }
2151        if high - low > bar {
2152            spreads.push((cell, high - low));
2153        }
2154    }
2155    census.cells_with_two_basins = spreads.len();
2156    let (u, v) = census.least_uv;
2157    let foot_cells: Vec<usize> = spreads
2158        .iter()
2159        .map(|&(cell, _)| cell)
2160        .filter(|&cell| {
2161            let (row, column) = (cell / columns, cell % columns);
2162            cells.us[row] <= u && u <= cells.us[row + 1] && cells.vs[column] <= v && v <= cells.vs[column + 1]
2163        })
2164        .collect();
2165    census.foot_cells_with_two_basins = foot_cells.len();
2166    census.foot_cell_descents = runs.into_iter().filter(|run| foot_cells.contains(&run.0)).collect();
2167    Ok(census)
2168}
2169
2170/// What the global stage did on one query.
2171#[doc(hidden)]
2172#[derive(Clone, Copy, Debug, Default)]
2173pub struct GlobalStats {
2174    /// The local answer was within the on-surface floor; nothing searched.
2175    pub settled_by_floor: bool,
2176    /// Cells whose hull bound admitted them.
2177    pub candidates: usize,
2178    /// Confined Newtons run (candidates not already holding a converged foot).
2179    pub refinements: usize,
2180    /// Continuations across the domain from a cell edge.
2181    pub continuations: usize,
2182    /// The global stage replaced the local answer.
2183    pub replaced: bool,
2184    /// The least hull bound over every cell — the true distance is never
2185    /// below it (0 when the floor settled the query).
2186    pub hull_lower_bound: f64,
2187}
2188
2189/// One lattice cell's enclosure: an oriented box around the control points
2190/// that support the cell, in an orthonormal frame fitted to the cell.
2191#[derive(Clone, Debug)]
2192struct CellBox {
2193    axes: [Vec3; 3],
2194    low: [f64; 3],
2195    high: [f64; 3],
2196}
2197
2198impl CellBox {
2199    /// Distance from `point` to the box: a lower bound on the distance to
2200    /// every surface point of the cell.
2201    fn lower_bound(&self, point: Vec3) -> f64 {
2202        let mut squared = 0.0;
2203        for axis in 0..3 {
2204            let coordinate = point.dot(self.axes[axis]);
2205            let excess = (self.low[axis] - coordinate).max(coordinate - self.high[axis]).max(0.0);
2206            squared += excess * excess;
2207        }
2208        squared.sqrt()
2209    }
2210}
2211
2212/// A node of the bounding-sphere tree over the cells. A leaf names its cell;
2213/// an internal node its two children.
2214#[derive(Clone, Copy, Debug)]
2215struct CellTreeNode {
2216    centre: Vec3,
2217    radius: f64,
2218    children: Option<(u32, u32)>,
2219    cell: u32,
2220}
2221
2222/// The cached enclosure of every projection lattice cell (see
2223/// [`project_point_to_surface_general`]). The lattice, boxes and tree are
2224/// shared, not copied, when the surface carrying them is cloned: the
2225/// assembler clones every face it rebuilds, and copying these was 8% of
2226/// brep-bench swept/drum-leaning-to-a-screw.
2227#[derive(Clone, Debug)]
2228pub struct ProjectionCells {
2229    us: std::sync::Arc<[f64]>,
2230    vs: std::sync::Arc<[f64]>,
2231    /// `us.len() × vs.len()` lattice points, row-major in u.
2232    nodes: std::sync::Arc<[Vec3]>,
2233    /// `(us.len() - 1) × (vs.len() - 1)` cells, row-major in u.
2234    boxes: std::sync::Arc<[CellBox]>,
2235    /// The tree's root is the LAST node.
2236    tree: std::sync::Arc<[CellTreeNode]>,
2237    /// One box per tree node: a leaf's is its cell's box, an internal node's
2238    /// holds both children's boxes grown by `node_margin` on every side (see
2239    /// [`hull_candidates`]). Empty when the surface has no usable scale.
2240    node_boxes: std::sync::Arc<[CellBox]>,
2241    /// The growth of each internal node's box over its children's.
2242    node_margin: f64,
2243    /// The largest control-point coordinate magnitude.
2244    scale: f64,
2245    resolution: f64,
2246    /// Descents per cell along u and v: 1, or under the coarse lattice the
2247    /// default stations' count over the coarse one, rounded up, along a
2248    /// thinned direction, so a cell is descended as densely as before.
2249    split: [usize; 2],
2250    /// Surface points at the sub-rectangle corners of coarse cells, by their
2251    /// index on the sub-grid (`row * split_u + i`, `column * split_v + j`),
2252    /// filled as descents read them.
2253    sub_nodes: std::sync::Arc<std::sync::Mutex<rustc_hash::FxHashMap<(u32, u32), Vec3>>>,
2254    /// Under a split: the hull boxes of the cells' sub-rectangles, by index
2255    /// `(cell · split_u + i) · split_v + j`, built on first use from the
2256    /// carrier's Bézier patches (`curve_clear::patch_piece_box`); `None`
2257    /// where a box could not be built.
2258    sub_boxes: std::sync::Arc<std::sync::Mutex<rustc_hash::FxHashMap<usize, Option<CellBox>>>>,
2259    /// Lattice stations per knot span along u and v.
2260    samples: [usize; 2],
2261}
2262
2263/// The projection lattice's parameters along one direction: every knot span
2264/// cut into `samples` equal pieces, the seed grid's density, shared span ends
2265/// listed once.
2266fn lattice_parameters(knots: &[f64], degree: usize, closed: bool) -> Vec<f64> {
2267    lattice_parameters_at(knots, degree, closed, false)
2268}
2269
2270/// [`lattice_parameters`], with `coarse` the reading of
2271/// [`coarse_lattice_enabled`]: an open direction of degree four or more takes
2272/// [`COARSE_SAMPLES`] stations per span instead of `degree + 1`.
2273/// Lattice stations per knot span of a direction.
2274fn lattice_samples(degree: usize, closed: bool, coarse: bool) -> usize {
2275    if closed {
2276        8usize.max(degree * 4)
2277    } else if coarse && degree >= 4 {
2278        COARSE_SAMPLES
2279    } else {
2280        3usize.max(degree + 1)
2281    }
2282}
2283
2284/// How many descents a coarse cell takes along a direction of `degree`:
2285/// the default stations per span over [`COARSE_SAMPLES`], rounded up (1 where
2286/// the direction is not thinned).
2287fn coarse_split(degree: usize, closed: bool, coarse: bool) -> usize {
2288    if coarse && !closed && degree >= 4 { (degree + 1).div_ceil(COARSE_SAMPLES) } else { 1 }
2289}
2290
2291fn lattice_parameters_at(knots: &[f64], degree: usize, closed: bool, coarse: bool) -> Vec<f64> {
2292    let [start, end] = crate::curve::knot_domain(knots, degree);
2293    let samples = lattice_samples(degree, closed, coarse);
2294    let mut breaks = vec![start];
2295    breaks.extend(interior_knots(knots, degree));
2296    breaks.push(end);
2297    let mut parameters = Vec::with_capacity((breaks.len() - 1) * samples + 1);
2298    for pair in breaks.windows(2) {
2299        for index in 0..samples {
2300            parameters.push(pair[0] + (pair[1] - pair[0]) * index as f64 / samples as f64);
2301        }
2302    }
2303    parameters.push(end);
2304    parameters
2305}
2306
2307/// Raise every lattice parameter to full multiplicity in the knot vector, so
2308/// each lattice cell is one Bézier piece of the refined net.
2309///
2310/// `net[i]` is the i-th control point along the refined direction, held as a
2311/// row across the other direction, and every row takes the same combination.
2312/// Knot refinement in one pass (Piegl & Tiller, *The NURBS Book*, A5.4), in
2313/// homogeneous coordinates, so a rational net refines exactly and the cost is
2314/// linear in the refined net's size.
2315fn refine_to_lattice(net: &mut Vec<Vec<Vec4>>, knots: &mut Vec<f64>, degree: usize, parameters: &[f64]) {
2316    let p = degree;
2317    let n = net.len() - 1;
2318    let mut inserted = Vec::new();
2319    for &parameter in parameters {
2320        let multiplicity = knots.iter().filter(|&&knot| knot == parameter).count();
2321        for _ in multiplicity..p {
2322            inserted.push(parameter);
2323        }
2324    }
2325    if inserted.is_empty() || p == 0 {
2326        return;
2327    }
2328    inserted.sort_by(f64::total_cmp);
2329    let find_span = |parameter: f64| -> usize {
2330        if parameter >= knots[n + 1] {
2331            return n;
2332        }
2333        (knots.partition_point(|&knot| knot <= parameter) - 1).clamp(p, n)
2334    };
2335    let r = inserted.len() - 1;
2336    let m = n + p + 1;
2337    let a = find_span(inserted[0]);
2338    let b = find_span(inserted[r]) + 1;
2339    let columns = net[0].len();
2340    let blank = vec![
2341        Vec4 {
2342            x: 0.0,
2343            y: 0.0,
2344            z: 0.0,
2345            w: 0.0,
2346        };
2347        columns
2348    ];
2349    let mut refined = vec![blank; n + r + 2];
2350    let mut refined_knots = vec![0.0; m + r + 2];
2351    for j in 0..=a - p {
2352        refined[j] = net[j].clone();
2353    }
2354    for j in b - 1..=n {
2355        refined[j + r + 1] = net[j].clone();
2356    }
2357    refined_knots[..=a].copy_from_slice(&knots[..=a]);
2358    for j in b + p..=m {
2359        refined_knots[j + r + 1] = knots[j];
2360    }
2361    let mut i = b + p - 1;
2362    let mut k = b + p + r;
2363    for j in (0..=r).rev() {
2364        while inserted[j] <= knots[i] && i > a {
2365            refined[k - p - 1] = net[i - p - 1].clone();
2366            refined_knots[k] = knots[i];
2367            k -= 1;
2368            i -= 1;
2369        }
2370        refined[k - p - 1] = refined[k - p].clone();
2371        for l in 1..=p {
2372            let index = k - p + l;
2373            let numerator = refined_knots[k + l] - inserted[j];
2374            if numerator == 0.0 {
2375                refined[index - 1] = refined[index].clone();
2376            } else {
2377                let alpha = numerator / (refined_knots[k + l] - knots[i - p + l]);
2378                let (head, tail) = refined.split_at_mut(index);
2379                for (before, &here) in head[index - 1].iter_mut().zip(&tail[0]) {
2380                    *before = before.scale(alpha).add(here.scale(1.0 - alpha));
2381                }
2382            }
2383        }
2384        refined_knots[k] = inserted[j];
2385        k = k.saturating_sub(1);
2386    }
2387    *net = refined;
2388    *knots = refined_knots;
2389}
2390
2391/// The control-point index range supporting the parameter interval
2392/// `[low, high]`: every basis function non-zero anywhere on it.
2393fn supporting_range(knots: &[f64], degree: usize, count: usize, low: f64, high: f64) -> (usize, usize) {
2394    let first_span = knots.partition_point(|&knot| knot <= low).saturating_sub(1);
2395    let last_span = knots.partition_point(|&knot| knot < high).saturating_sub(1);
2396    (
2397        first_span.saturating_sub(degree).min(count - 1),
2398        last_span.max(first_span).min(count - 1),
2399    )
2400}
2401
2402fn unit_or(vector: Vec3, fallback: Vec3) -> Vec3 {
2403    let length = vector.length();
2404    if length > 0.0 && length.is_finite() {
2405        vector.scale(1.0 / length)
2406    } else {
2407        fallback
2408    }
2409}
2410
2411fn enclosing_sphere(a: (Vec3, f64), b: (Vec3, f64)) -> (Vec3, f64) {
2412    let offset = b.0.sub(a.0);
2413    let separation = offset.length();
2414    if separation + b.1 <= a.1 {
2415        return a;
2416    }
2417    if separation + a.1 <= b.1 {
2418        return b;
2419    }
2420    let radius = (separation + a.1 + b.1) * 0.5;
2421    let centre = a.0.add(offset.scale((radius - a.1) / separation));
2422    (centre, radius)
2423}
2424
2425/// What [`build_cell_tree`] reads besides the spheres: the cells' boxes and
2426/// the lattice points (row-major, `lattice_columns` per row) that frame each
2427/// internal node's box, and the margin each internal box grows by.
2428struct NodeBoxInputs<'a> {
2429    boxes: &'a [CellBox],
2430    nodes: &'a [Vec3],
2431    lattice_columns: usize,
2432    margin: f64,
2433}
2434
2435/// The box of a control grid (`columns` per row, rows along u), framed as a
2436/// lattice cell's is (along u, then the normal of its corners) and grown by
2437/// `margin` on every side; `None` where a frame or an extent is not finite.
2438fn framed_box(points: &[Vec3], columns: usize, margin: f64) -> Option<CellBox> {
2439    if columns == 0 || points.len() < columns || points.len() % columns != 0 {
2440        return None;
2441    }
2442    let last = points.len() - columns;
2443    let (c00, c01, c10, c11) = (points[0], points[columns - 1], points[last], points[last + columns - 1]);
2444    let along_u = c10.sub(c00).add(c11.sub(c01));
2445    let along_v = c01.sub(c00).add(c11.sub(c10));
2446    let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2447    let fallback = e1.perpendicular().ok()?;
2448    let normal = unit_or(e1.cross(along_v), fallback);
2449    let e2 = unit_or(normal.cross(e1), fallback);
2450    let e3 = e1.cross(e2);
2451    let axes = [e1, e2, e3];
2452    let mut low = [f64::INFINITY; 3];
2453    let mut high = [f64::NEG_INFINITY; 3];
2454    for point in points {
2455        for axis in 0..3 {
2456            let coordinate = point.dot(axes[axis]);
2457            low[axis] = low[axis].min(coordinate);
2458            high[axis] = high[axis].max(coordinate);
2459        }
2460    }
2461    for axis in 0..3 {
2462        low[axis] -= margin;
2463        high[axis] += margin;
2464    }
2465    low.iter().chain(high.iter()).all(|value| value.is_finite()).then_some(CellBox { axes, low, high })
2466}
2467
2468/// The box of an internal node: framed like a cell's (along u, then the
2469/// normal of the region's lattice corners), spanning every corner of both
2470/// children's boxes, grown by `margin` on every side. Unbounded when a frame or
2471/// an extent is not finite, so it never prunes.
2472fn enclosing_node_box(corners: [Vec3; 4], children: [&CellBox; 2], margin: f64) -> CellBox {
2473    let unbounded = || CellBox {
2474        axes: [Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0)],
2475        low: [f64::NEG_INFINITY; 3],
2476        high: [f64::INFINITY; 3],
2477    };
2478    let [c00, c10, c01, c11] = corners;
2479    let along_u = c10.sub(c00).add(c11.sub(c01));
2480    let along_v = c01.sub(c00).add(c11.sub(c10));
2481    let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2482    let Ok(fallback) = e1.perpendicular() else {
2483        return unbounded();
2484    };
2485    let normal = unit_or(e1.cross(along_v), fallback);
2486    let e2 = unit_or(normal.cross(e1), fallback);
2487    let e3 = e1.cross(e2);
2488    let axes = [e1, e2, e3];
2489    let mut low = [f64::INFINITY; 3];
2490    let mut high = [f64::NEG_INFINITY; 3];
2491    for child in children {
2492        for corner in 0..8 {
2493            let mut point = Vec3::default();
2494            for axis in 0..3 {
2495                let value = if corner >> axis & 1 == 0 { child.low[axis] } else { child.high[axis] };
2496                point = point.add(child.axes[axis].scale(value));
2497            }
2498            for axis in 0..3 {
2499                let coordinate = point.dot(axes[axis]);
2500                low[axis] = low[axis].min(coordinate);
2501                high[axis] = high[axis].max(coordinate);
2502            }
2503        }
2504    }
2505    for axis in 0..3 {
2506        low[axis] -= margin;
2507        high[axis] += margin;
2508    }
2509    if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2510        return unbounded();
2511    }
2512    CellBox { axes, low, high }
2513}
2514
2515fn build_cell_tree(
2516    tree: &mut Vec<CellTreeNode>,
2517    node_boxes: &mut Vec<CellBox>,
2518    inputs: &NodeBoxInputs<'_>,
2519    spheres: &[(Vec3, f64)],
2520    columns: usize,
2521    [row_low, row_high, column_low, column_high]: [usize; 4],
2522) -> u32 {
2523    if row_high - row_low == 1 && column_high - column_low == 1 {
2524        let cell = row_low * columns + column_low;
2525        node_boxes.push(inputs.boxes[cell].clone());
2526        tree.push(CellTreeNode {
2527            centre: spheres[cell].0,
2528            radius: spheres[cell].1,
2529            children: None,
2530            cell: cell as u32,
2531        });
2532        return (tree.len() - 1) as u32;
2533    }
2534    let (first, second) = if row_high - row_low >= column_high - column_low {
2535        let middle = (row_low + row_high) / 2;
2536        (
2537            [row_low, middle, column_low, column_high],
2538            [middle, row_high, column_low, column_high],
2539        )
2540    } else {
2541        let middle = (column_low + column_high) / 2;
2542        (
2543            [row_low, row_high, column_low, middle],
2544            [row_low, row_high, middle, column_high],
2545        )
2546    };
2547    let first = build_cell_tree(tree, node_boxes, inputs, spheres, columns, first);
2548    let second = build_cell_tree(tree, node_boxes, inputs, spheres, columns, second);
2549    let a = tree[first as usize];
2550    let b = tree[second as usize];
2551    let lattice = |row: usize, column: usize| inputs.nodes[row * inputs.lattice_columns + column];
2552    node_boxes.push(enclosing_node_box(
2553        [
2554            lattice(row_low, column_low),
2555            lattice(row_high, column_low),
2556            lattice(row_low, column_high),
2557            lattice(row_high, column_high),
2558        ],
2559        [&node_boxes[first as usize], &node_boxes[second as usize]],
2560        inputs.margin,
2561    ));
2562    // The resolution-inflated leaf spheres already absorb rounding; the merge
2563    // adds one more rounding of the same order, absorbed by growing the radius
2564    // by the larger child's own ulp.
2565    let (centre, radius) = enclosing_sphere((a.centre, a.radius), (b.centre, b.radius));
2566    tree.push(CellTreeNode {
2567        centre,
2568        radius: radius * (1.0 + 4.0 * f64::EPSILON),
2569        children: Some((first, second)),
2570        cell: u32::MAX,
2571    });
2572    (tree.len() - 1) as u32
2573}
2574
2575fn projection_cells(surface: &NurbsSurface) -> Result<Option<&ProjectionCells>, String> {
2576    if let Some(cells) = surface.projection_cells.get() {
2577        return Ok(cells.as_ref());
2578    }
2579    tables_within_limit(surface)?;
2580    let cells = build_projection_cells_at(surface, coarse_lattice_enabled())?;
2581    Ok(surface.projection_cells.get_or_init(|| cells).as_ref())
2582}
2583
2584/// Stations per knot span of an open direction of degree four or more under
2585/// [`coarse_lattice_enabled`]. The default `degree + 1` cut a quintic sweep
2586/// net's 124 spans into 745 stations, and a 745 × 97 lattice (72k cells, a
2587/// refined net of 1.8M control points) cost 300 ms to build, a third of
2588/// brep-bench swept/ball-on-a-leaning-stem-swung-partway.
2589const COARSE_SAMPLES: usize = 3;
2590
2591/// `BREP_PROJECTION_COARSE_LATTICE` (default on; `=0` restores the default
2592/// lattice): the projection lattice of a
2593/// direction of degree four or more takes [`COARSE_SAMPLES`] stations per span.
2594/// Every cell's box still encloses its piece of the surface (the hull bound
2595/// holds at any cell size), so no cell a nearer point could lie in is skipped;
2596/// a larger cell is a larger region one descent is seeded in.
2597/// `BREP_PROJECTION_COARSE_LATTICE_CHECK=1` turns it on and also runs every
2598/// global stage on the default lattice, panicking where the coarse answer is
2599/// farther than the default's by more than the bar of [`coarse_check_bar`].
2600fn coarse_lattice_enabled() -> bool {
2601    coarse_lattice_check() || crate::switch!("BREP_PROJECTION_COARSE_LATTICE", true)
2602}
2603
2604fn coarse_lattice_check() -> bool {
2605    crate::switch!("BREP_PROJECTION_COARSE_LATTICE_CHECK", false)
2606}
2607
2608/// How much farther than the default lattice's answer the coarse lattice's may
2609/// read before the check stops: the surface's own resolution, the most the
2610/// global stage ever leaves on the table, and the on-surface floor.
2611fn coarse_check_bar(resolution: f64) -> f64 {
2612    LINEAR_TOLERANCE.max(16.0 * resolution)
2613}
2614
2615thread_local! {
2616    /// The default lattice's cells for the check, by surface content.
2617    static DEFAULT_CELLS_FOR_CHECK: std::cell::RefCell<rustc_hash::FxHashMap<[u64; 2], std::rc::Rc<Option<ProjectionCells>>>> = std::cell::RefCell::new(rustc_hash::FxHashMap::default());
2618}
2619
2620fn default_cells_for_check(surface: &NurbsSurface) -> Result<std::rc::Rc<Option<ProjectionCells>>, String> {
2621    let key = surface.content_key();
2622    if let Some(cells) = DEFAULT_CELLS_FOR_CHECK.with(|map| map.borrow().get(&key).cloned()) {
2623        return Ok(cells);
2624    }
2625    let cells = std::rc::Rc::new(build_projection_cells_at(surface, false)?);
2626    DEFAULT_CELLS_FOR_CHECK.with(|map| {
2627        let mut map = map.borrow_mut();
2628        // The check holds a bounded set; a test battery meets far more surfaces.
2629        if map.len() >= 256 { map.clear(); }
2630        map.insert(key, cells.clone());
2631    });
2632    Ok(cells)
2633}
2634
2635/// About how many bytes the projector's tables of this surface take while
2636/// they are built, read from the builders' own counts and without building
2637/// anything: the seed grid ([`projection_seed_grid`]), the dense grid
2638/// ([`projection_dense_grid`]) and the global stage's cells
2639/// ([`build_projection_cells_at`]: the net refined to one Bézier piece per
2640/// cell, held twice while it is transposed and once more as points, then the
2641/// lattice, the boxes and the tree). 0 for a surface whose closedness cannot
2642/// be read (the builders refuse it before they allocate), and for a finely
2643/// divided surface the projector answers in closed form.
2644///
2645/// A caller about to project onto operands it did not build reads this to
2646/// refuse by name what it could only run out of memory on: a lofted wall of
2647/// 488 × 490 quintic spans reads 6.6 GB here, and a boolean of two bodies
2648/// carrying three such walls stopped on a failed 1.3 GB allocation at 14.7 GB.
2649pub fn projection_tables_bytes(surface: &NurbsSurface) -> u64 {
2650    let bytes = general_tables_bytes(surface);
2651    // A carrier with a closed-form projection ([`project_point_to_surface`])
2652    // builds none of the tables. Asked only of a surface whose tables would
2653    // matter, so an ordinary surface is not recognised here before its time.
2654    let closed_form = || surface.analytic().is_some() || surface.affine_sphere().is_some() || surface.linear_extrusion().is_some();
2655    if bytes >= 1 << 20 && closed_form() { 0 } else { bytes }
2656}
2657
2658/// The most the general projector's tables of ONE surface may take
2659/// ([`general_tables_bytes`]): above it every table builder refuses, and a
2660/// projection onto the surface is an error its caller reads as no foot. A
2661/// browser build cannot address what a native one can.
2662pub const PROJECTION_TABLES_LIMIT: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
2663
2664/// Refuse to build a table of a surface over [`PROJECTION_TABLES_LIMIT`],
2665/// before anything is allocated. Read where a table is built (once per
2666/// surface that has one), never on a projection that finds its tables.
2667fn tables_within_limit(surface: &NurbsSurface) -> Result<(), String> {
2668    let bytes = general_tables_bytes(surface);
2669    if bytes <= PROJECTION_TABLES_LIMIT {
2670        return Ok(());
2671    }
2672    Err(format!(
2673        "surface too finely divided to project onto: its projection tables take about {} MB (limit {} MB)",
2674        bytes >> 20,
2675        PROJECTION_TABLES_LIMIT >> 20
2676    ))
2677}
2678
2679/// [`projection_tables_bytes`] of the general projector, whatever closed form
2680/// the carrier has.
2681fn general_tables_bytes(surface: &NurbsSurface) -> u64 {
2682    let Ok((closed_u, closed_v)) = surface.closed_directions() else { return 0 };
2683    let coarse = coarse_lattice_enabled();
2684    let spans = |knots: &[f64], degree: usize| interior_knots(knots, degree).len() as u64 + 1;
2685    let (spans_u, spans_v) = (spans(&surface.knots_u, surface.degree_u), spans(&surface.knots_v, surface.degree_v));
2686    let seed = |closed: bool, degree: usize| if closed { 8usize.max(degree * 4) } else { 3usize.max(degree + 1) } as u64 + 1;
2687    let sample = std::mem::size_of::<(f64, f64, Vec3)>() as u64;
2688    let seed_grid = (spans_u * spans_v).saturating_mul(seed(closed_u, surface.degree_u) * seed(closed_v, surface.degree_v)).saturating_mul(sample);
2689    let dense_grid = (32u64.max(spans_u * 8) + 1).saturating_mul(16u64.max(spans_v * 8) + 1).saturating_mul(sample);
2690    let cells_u = spans_u * lattice_samples(surface.degree_u, closed_u, coarse) as u64;
2691    let cells_v = spans_v * lattice_samples(surface.degree_v, closed_v, coarse) as u64;
2692    let refined = (cells_u * surface.degree_u as u64 + 1).saturating_mul(cells_v * surface.degree_v as u64 + 1);
2693    let net = refined.saturating_mul(2 * std::mem::size_of::<Vec4>() as u64 + std::mem::size_of::<Vec3>() as u64);
2694    let per_cell = 3 * std::mem::size_of::<CellBox>() as u64 + 2 * std::mem::size_of::<CellTreeNode>() as u64 + std::mem::size_of::<(Vec3, f64)>() as u64 + std::mem::size_of::<Vec3>() as u64;
2695    let cells = (cells_u * cells_v).saturating_mul(per_cell);
2696    seed_grid.saturating_add(dense_grid).saturating_add(net).saturating_add(cells)
2697}
2698
2699fn build_projection_cells(surface: &NurbsSurface) -> Result<Option<ProjectionCells>, String> {
2700    build_projection_cells_at(surface, false)
2701}
2702
2703fn build_projection_cells_at(surface: &NurbsSurface, coarse: bool) -> Result<Option<ProjectionCells>, String> {
2704    let (closed_u, closed_v) = surface.closed_directions()?;
2705    let us = lattice_parameters_at(&surface.knots_u, surface.degree_u, closed_u, coarse);
2706    let vs = lattice_parameters_at(&surface.knots_v, surface.degree_v, closed_v, coarse);
2707    if us.len() < 2 || vs.len() < 2 {
2708        return Ok(None);
2709    }
2710    let mut scale = 0.0f64;
2711    for control in surface.control_points.iter().flatten() {
2712        let point = control.point()?;
2713        scale = scale.max(point.x.abs()).max(point.y.abs()).max(point.z.abs());
2714    }
2715    let resolution =
2716        ((surface.degree_u + 1) * (surface.degree_v + 1)) as f64 * f64::EPSILON * scale;
2717
2718    // Refine u (the net's rows), then v (its columns, as rows of the transpose).
2719    let mut net = surface.control_points.clone();
2720    let mut knots_u = surface.knots_u.clone();
2721    refine_to_lattice(&mut net, &mut knots_u, surface.degree_u, &us);
2722    let columns = net.first().map(Vec::len).unwrap_or(0);
2723    let mut transposed: Vec<Vec<Vec4>> =
2724        (0..columns).map(|column| net.iter().map(|row| row[column]).collect()).collect();
2725    let mut knots_v = surface.knots_v.clone();
2726    refine_to_lattice(&mut transposed, &mut knots_v, surface.degree_v, &vs);
2727    let rows = transposed.first().map(Vec::len).unwrap_or(0);
2728    let columns = transposed.len();
2729    if rows == 0 || columns == 0 {
2730        return Ok(None);
2731    }
2732    let split = [coarse_split(surface.degree_u, closed_u, coarse), coarse_split(surface.degree_v, closed_v, coarse)];
2733    let mut points = vec![Vec3::default(); rows * columns];
2734    for (column, fibre) in transposed.iter().enumerate() {
2735        for (row, control) in fibre.iter().enumerate() {
2736            points[row * columns + column] = control.point()?;
2737        }
2738    }
2739
2740    let mut nodes = Vec::with_capacity(us.len() * vs.len());
2741    for &u in &us {
2742        for &v in &vs {
2743            nodes.push(surface.evaluate(u, v)?);
2744        }
2745    }
2746
2747    let cell_rows = us.len() - 1;
2748    let cell_columns = vs.len() - 1;
2749    let mut boxes = Vec::with_capacity(cell_rows * cell_columns);
2750    let mut spheres = Vec::with_capacity(cell_rows * cell_columns);
2751    for i in 0..cell_rows {
2752        let (row_low, row_high) =
2753            supporting_range(&knots_u, surface.degree_u, rows, us[i], us[i + 1]);
2754        for j in 0..cell_columns {
2755            let (column_low, column_high) =
2756                supporting_range(&knots_v, surface.degree_v, columns, vs[j], vs[j + 1]);
2757            let at = |row: usize, column: usize| points[row * columns + column];
2758            let c00 = at(row_low, column_low);
2759            let c10 = at(row_high, column_low);
2760            let c01 = at(row_low, column_high);
2761            let c11 = at(row_high, column_high);
2762            let along_u = c10.sub(c00).add(c11.sub(c01));
2763            let along_v = c01.sub(c00).add(c11.sub(c10));
2764            let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2765            let normal = unit_or(e1.cross(along_v), e1.perpendicular()?);
2766            let e2 = unit_or(normal.cross(e1), e1.perpendicular()?);
2767            let e3 = e1.cross(e2);
2768            let axes = [e1, e2, e3];
2769            let mut low = [f64::INFINITY; 3];
2770            let mut high = [f64::NEG_INFINITY; 3];
2771            for row in row_low..=row_high {
2772                for column in column_low..=column_high {
2773                    let point = at(row, column);
2774                    for axis in 0..3 {
2775                        let coordinate = point.dot(axes[axis]);
2776                        low[axis] = low[axis].min(coordinate);
2777                        high[axis] = high[axis].max(coordinate);
2778                    }
2779                }
2780            }
2781            for axis in 0..3 {
2782                low[axis] -= resolution;
2783                high[axis] += resolution;
2784            }
2785            let mut centre = Vec3::default();
2786            let mut half_diagonal_squared = 0.0;
2787            for axis in 0..3 {
2788                centre = centre.add(axes[axis].scale((low[axis] + high[axis]) * 0.5));
2789                let half = (high[axis] - low[axis]) * 0.5;
2790                half_diagonal_squared += half * half;
2791            }
2792            if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2793                return Ok(None);
2794            }
2795            spheres.push((centre, half_diagonal_squared.sqrt() + resolution));
2796            boxes.push(CellBox { axes, low, high });
2797        }
2798    }
2799    let mut tree = Vec::with_capacity(2 * boxes.len());
2800    let mut node_boxes = Vec::with_capacity(2 * boxes.len());
2801    // Each internal box grows by a billionth of the surface's scale over its
2802    // children: far above the rounding of the corners it spans and of the
2803    // bound read from it, so a box that excludes a point excludes every cell
2804    // under it (see `hull_candidates`).
2805    let node_margin = NODE_BOX_MARGIN * scale;
2806    let inputs = NodeBoxInputs { boxes: &boxes, nodes: &nodes, lattice_columns: vs.len(), margin: node_margin };
2807    build_cell_tree(&mut tree, &mut node_boxes, &inputs, &spheres, cell_columns, [0, cell_rows, 0, cell_columns]);
2808    if !(node_margin > 0.0 && node_margin.is_finite()) {
2809        node_boxes = Vec::new();
2810    }
2811    Ok(Some(ProjectionCells {
2812        us: us.into(),
2813        vs: vs.into(),
2814        nodes: nodes.into(),
2815        boxes: boxes.into(),
2816        tree: tree.into(),
2817        node_boxes: node_boxes.into(),
2818        node_margin,
2819        scale,
2820        resolution,
2821        split,
2822        sub_nodes: Default::default(),
2823        sub_boxes: Default::default(),
2824        samples: [
2825            lattice_samples(surface.degree_u, closed_u, coarse),
2826            lattice_samples(surface.degree_v, closed_v, coarse),
2827        ],
2828    }))
2829}
2830
2831/// First- and second-order optimality of `(u, v)` for the distance over the
2832/// rectangle: stationary on the coordinates the rectangle leaves free (the
2833/// descent's own cosine test), with a positive definite Hessian there. A
2834/// `periodic` direction has no edge to be pinned against: its seam is interior.
2835fn optimality(
2836    derivatives: &[[Vec3; 3]; 3],
2837    point: Vec3,
2838    (u, v): (f64, f64),
2839    [ua, ub, va, vb]: [f64; 4],
2840    periodic: (bool, bool),
2841) -> Optimality {
2842    let residual = derivatives[0][0].sub(point);
2843    let residual_length = residual.length();
2844    let su = derivatives[1][0];
2845    let sv = derivatives[0][1];
2846    let f = su.dot(residual);
2847    let g = sv.dot(residual);
2848    let metric_u = su.length_squared();
2849    let metric_v = sv.length_squared();
2850    let stationary_u = metric_u.sqrt() * residual_length <= EPSILON
2851        || f.abs() <= 1e-10 * metric_u.sqrt() * residual_length;
2852    let stationary_v = metric_v.sqrt() * residual_length <= EPSILON
2853        || g.abs() <= 1e-10 * metric_v.sqrt() * residual_length;
2854    let pinned_u = !periodic.0 && ((u <= ua && f > 0.0) || (u >= ub && f < 0.0));
2855    let pinned_v = !periodic.1 && ((v <= va && g > 0.0) || (v >= vb && g < 0.0));
2856    let j00 = derivatives[2][0].dot(residual) + metric_u;
2857    let j01 = derivatives[1][1].dot(residual) + su.dot(sv);
2858    let j11 = derivatives[0][2].dot(residual) + metric_v;
2859    let determinant = j00 * j11 - j01 * j01;
2860    let convex = match (!pinned_u, !pinned_v) {
2861        (true, true) => j00 > 0.0 && determinant > 0.0,
2862        (true, false) => j00 > 0.0,
2863        (false, true) => j11 > 0.0,
2864        (false, false) => true,
2865    };
2866    Optimality {
2867        residual_length,
2868        gradient: (f, g),
2869        metric: (metric_u, metric_v),
2870        hessian: (j00, j01, j11),
2871        determinant,
2872        pinned: (pinned_u, pinned_v),
2873        convex,
2874        minimum: residual_length <= LINEAR_TOLERANCE
2875            || ((stationary_u || pinned_u) && (stationary_v || pinned_v) && convex),
2876    }
2877}
2878
2879struct Optimality {
2880    residual_length: f64,
2881    gradient: (f64, f64),
2882    metric: (f64, f64),
2883    hessian: (f64, f64, f64),
2884    determinant: f64,
2885    pinned: (bool, bool),
2886    convex: bool,
2887    minimum: bool,
2888}
2889
2890fn is_verified_minimum(
2891    surface: &NurbsSurface,
2892    point: Vec3,
2893    at: (f64, f64),
2894    rectangle: [f64; 4],
2895    periodic: (bool, bool),
2896) -> Result<bool, String> {
2897    let derivatives = surface.derivatives_small(at.0, at.1, 2)?;
2898    Ok(optimality(&derivatives, point, at, rectangle, periodic).minimum)
2899}
2900
2901/// A descent to a local minimum of the distance over the rectangle
2902/// `[ua, ub] × [va, vb]`, from a seed inside it.
2903///
2904/// Newton on the gradient converges to ANY critical point — a saddle or a
2905/// maximum as readily as a minimum — and reads convergence there, so every
2906/// step here must lower the distance: the Newton step where the Hessian is
2907/// positive definite on the free coordinates, the metric-scaled gradient step
2908/// where it is not, halved until the distance does not rise. A coordinate
2909/// pinned at the rectangle's edge by a gradient pointing out of it is held
2910/// there and the other takes the one-dimensional step, so a minimum ON the edge
2911/// converges as one (the Karush-Kuhn-Tucker point) instead of stalling.
2912///
2913/// Returns the best iterate, whether it is a verified minimum (stationary on
2914/// the free coordinates with a positive definite Hessian there, or within the
2915/// on-surface floor), and whether it lies on the rectangle's edge.
2916fn confined_descent(
2917    surface: &NurbsSurface,
2918    point: Vec3,
2919    seed: (f64, f64),
2920    rectangle: [f64; 4],
2921    periodic: (bool, bool),
2922) -> Result<(NewtonResult, bool), String> {
2923    let [ua, ub, va, vb] = rectangle;
2924    let mut u = fit_parameter(seed.0, ua, ub, periodic.0);
2925    let mut v = fit_parameter(seed.1, va, vb, periodic.1);
2926    let mut converged = false;
2927    let mut current = surface.evaluate(u, v)?.sub(point).length_squared();
2928    for _ in 0..MAX_NEWTON_ITERATIONS {
2929        let derivatives = surface.derivatives_small(u, v, 2)?;
2930        let state = optimality(&derivatives, point, (u, v), rectangle, periodic);
2931        current = state.residual_length * state.residual_length;
2932        if state.minimum {
2933            converged = true;
2934            break;
2935        }
2936        let (f, g) = state.gradient;
2937        let (metric_u, metric_v) = state.metric;
2938        let (j00, j01, j11) = state.hessian;
2939        let determinant = state.determinant;
2940        let (free_u, free_v) = (!state.pinned.0, !state.pinned.1);
2941        let (mut du, mut dv) = match (free_u, free_v) {
2942            (true, true) if state.convex => (
2943                (-f * j11 + g * j01) / determinant,
2944                (-g * j00 + f * j01) / determinant,
2945            ),
2946            (true, false) if state.convex => (-f / j00, 0.0),
2947            (false, true) if state.convex => (0.0, -g / j11),
2948            _ => (
2949                if free_u && metric_u > 0.0 { -f / metric_u } else { 0.0 },
2950                if free_v && metric_v > 0.0 { -g / metric_v } else { 0.0 },
2951            ),
2952        };
2953        if !(du.is_finite() && dv.is_finite()) || (du == 0.0 && dv == 0.0) {
2954            break;
2955        }
2956        let mut moved = false;
2957        // The step actually taken, a whole period removed across a seam.
2958        let taken = |next: f64, here: f64, low: f64, high: f64, wraps: bool| {
2959            let raw = next - here;
2960            if wraps {
2961                raw - (high - low) * (raw / (high - low)).round()
2962            } else {
2963                raw
2964            }
2965        };
2966        for _ in 0..40 {
2967            let next_u = fit_parameter(u + du, ua, ub, periodic.0);
2968            let next_v = fit_parameter(v + dv, va, vb, periodic.1);
2969            if next_u == u && next_v == v {
2970                break;
2971            }
2972            let trial = surface.evaluate(next_u, next_v)?.sub(point).length_squared();
2973            if trial <= current {
2974                moved = taken(next_u, u, ua, ub, periodic.0).abs() > 1e-15 * (ub - ua)
2975                    || taken(next_v, v, va, vb, periodic.1).abs() > 1e-15 * (vb - va);
2976                u = next_u;
2977                v = next_v;
2978                current = trial;
2979                break;
2980            }
2981            du *= 0.5;
2982            dv *= 0.5;
2983        }
2984        if !moved {
2985            break;
2986        }
2987    }
2988    let result = NewtonResult {
2989        u,
2990        v,
2991        distance_squared: current,
2992        converged,
2993    };
2994    let on_edge =
2995        (!periodic.0 && (u <= ua || u >= ub)) || (!periodic.1 && (v <= va || v >= vb));
2996    Ok((result, on_edge))
2997}
2998
2999/// The growth of an internal node's box over its children's, per unit of
3000/// the surface's scale.
3001const NODE_BOX_MARGIN: f64 = 1e-9;
3002
3003/// `BREP_PROJECTION_NODE_BOXES` (default on): the cell-tree walk also reads
3004/// each internal node's box, not only its sphere. `=0` walks on spheres alone,
3005/// as before. Read once.
3006fn node_boxes_enabled() -> bool {
3007    switch!("BREP_PROJECTION_NODE_BOXES", true)
3008}
3009
3010/// The walk of the global stage: every cell whose box comes nearer `point`
3011/// than `bound`, with its box bound, in the walk's order, and the least bound
3012/// over everything the walk excluded.
3013///
3014/// A node is excluded when its sphere is no nearer than `bound`, and, with
3015/// `node_boxes`, when its box is not either. Cell spheres are loose on long,
3016/// thin cells (a 16 × 5632 lattice: about 3000 nodes visited and 200 cells
3017/// read per query to admit one), and an internal box is not. The box test
3018/// only removes subtrees whose every cell the cell test would reject, in the
3019/// same order, so the candidates are the same list to the bit with and
3020/// without it. Each internal box holds its children's boxes grown by
3021/// `node_margin` (`m`), and both bounds are read within `e` of their exact
3022/// value, `e` (below) set by the point's and the surface's magnitudes. A
3023/// box read at `b ≥ bound` with `b > 2e` is truly at least `b − e > 0` away,
3024/// so each cell box under it is truly at least `b − e + m` away and reads at
3025/// least `b − 2e + m ≥ bound` whenever `m ≥ 2e`; the test is skipped for a
3026/// point so far out that `4e > m` (beyond about 3·10⁴ scales), keeping half
3027/// of `m` for the rounding of the box corners themselves. Only the excluded
3028/// bound (the certificate in `GlobalStats::hull_lower_bound`) can differ: it
3029/// is still a lower bound, read from a tighter box.
3030fn hull_candidates(cells: &ProjectionCells, point: Vec3, bound: f64, node_boxes: bool) -> (Vec<(f64, usize)>, f64) {
3031    let read_error = 32.0 * f64::EPSILON * (point.x.abs() + point.y.abs() + point.z.abs() + 4.0 * cells.scale);
3032    let boxes = node_boxes && !cells.node_boxes.is_empty() && 4.0 * read_error <= cells.node_margin;
3033    let mut candidates: Vec<(f64, usize)> = Vec::new();
3034    let mut excluded = f64::INFINITY;
3035    let mut stack: Vec<u32> = Vec::with_capacity(64);
3036    stack.push((cells.tree.len() - 1) as u32);
3037    while let Some(index) = stack.pop() {
3038        let node = cells.tree[index as usize];
3039        let sphere_bound = (point.sub(node.centre).length() - node.radius).max(0.0);
3040        if sphere_bound >= bound {
3041            excluded = excluded.min(sphere_bound);
3042            continue;
3043        }
3044        match node.children {
3045            Some((first, second)) => {
3046                if boxes {
3047                    let box_bound = cells.node_boxes[index as usize].lower_bound(point);
3048                    if box_bound >= bound && box_bound > 2.0 * read_error {
3049                        excluded = excluded.min(box_bound);
3050                        continue;
3051                    }
3052                }
3053                stack.push(first);
3054                stack.push(second);
3055            }
3056            None => {
3057                let cell = node.cell as usize;
3058                let box_bound = cells.boxes[cell].lower_bound(point);
3059                if box_bound < bound {
3060                    candidates.push((box_bound, cell));
3061                } else {
3062                    excluded = excluded.min(box_bound);
3063                }
3064            }
3065        }
3066    }
3067    (candidates, excluded)
3068}
3069
3070/// The global stage of [`project_point_to_surface_general`]: replace `best`
3071/// with the least local minimum over every cell the hull bound admits.
3072#[allow(clippy::too_many_arguments)]
3073fn global_minimum(
3074    surface: &NurbsSurface,
3075    point: Vec3,
3076    domains: [f64; 4],
3077    periodic: (bool, bool),
3078    best: &mut NewtonResult,
3079    stats: &mut GlobalStats,
3080) -> Result<(), String> {
3081    if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
3082        stats.settled_by_floor = true;
3083        return Ok(());
3084    }
3085    let Some(cells) = projection_cells(surface)? else {
3086        return Ok(());
3087    };
3088    if coarse_lattice_check() {
3089        let start = *best;
3090        global_minimum_with(surface, cells, point, domains, periodic, best, stats)?;
3091        if let Some(default) = default_cells_for_check(surface)?.as_ref() {
3092            let mut reference = start;
3093            global_minimum_with(surface, default, point, domains, periodic, &mut reference, &mut GlobalStats::default())?;
3094            let (coarse, fine) = (best.distance_squared.sqrt(), reference.distance_squared.sqrt());
3095            if coarse > fine + coarse_check_bar(default.resolution) {
3096                panic!("BREP_PROJECTION_COARSE_LATTICE_CHECK: the coarse lattice reads {coarse:e} where the default reads {fine:e} for {point:?} (degrees {}x{})", surface.degree_u, surface.degree_v);
3097            }
3098        }
3099        return Ok(());
3100    }
3101    global_minimum_with(surface, cells, point, domains, periodic, best, stats)
3102}
3103
3104/// [`global_minimum`] over the given cells.
3105#[allow(clippy::too_many_arguments)]
3106fn global_minimum_with(
3107    surface: &NurbsSurface,
3108    cells: &ProjectionCells,
3109    point: Vec3,
3110    domains: [f64; 4],
3111    periodic: (bool, bool),
3112    best: &mut NewtonResult,
3113    stats: &mut GlobalStats,
3114) -> Result<(), String> {
3115    let resolution = cells.resolution;
3116    let columns = cells.vs.len() - 1;
3117    let columns_u = cells.us.len() - 1;
3118    let mut bound = best.distance_squared.sqrt() - resolution;
3119
3120    // Every cell whose box comes nearer than the answer; the least bound over
3121    // what the walk excluded is the certificate.
3122    let (mut candidates, excluded) = hull_candidates(cells, point, bound, node_boxes_enabled());
3123    stats.candidates = candidates.len();
3124    candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
3125    stats.hull_lower_bound = candidates
3126        .first()
3127        .map_or(excluded, |&(least, _)| least.min(excluded));
3128
3129    // Cells already holding a verified minimum need no second descent. A foot
3130    // names ONE cell even when it sits on a lattice line shared by up to four:
3131    // a neighbour can hold a better basin of its own in its interior, and it
3132    // was admitted precisely because its bound beat this answer. The local
3133    // answer is one when it passes the same test the descent applies.
3134    let cell_of = |u: f64, v: f64| {
3135        let row = (cells.us.partition_point(|&value| value <= u).max(1) - 1).min(columns_u - 1);
3136        let column = (cells.vs.partition_point(|&value| value <= v).max(1) - 1).min(columns - 1);
3137        row * columns + column
3138    };
3139    let mut settled: Vec<usize> = Vec::new();
3140    if is_verified_minimum(surface, point, (best.u, best.v), domains, periodic)? {
3141        settled.push(cell_of(best.u, best.v));
3142    }
3143    for (cell_bound, cell) in candidates {
3144        if cell_bound >= bound {
3145            break;
3146        }
3147        let row = cell / columns;
3148        let column = cell % columns;
3149        let rectangle = [
3150            cells.us[row],
3151            cells.us[row + 1],
3152            cells.vs[column],
3153            cells.vs[column + 1],
3154        ];
3155        if settled.contains(&cell) {
3156            continue;
3157        }
3158        if cells.split == [1, 1] {
3159            let mut seed = (rectangle[0], rectangle[2]);
3160            let mut seed_distance = f64::INFINITY;
3161            for (node_row, node_column) in
3162                [(row, column), (row + 1, column), (row, column + 1), (row + 1, column + 1)]
3163            {
3164                let distance = cells.nodes[node_row * cells.vs.len() + node_column]
3165                    .sub(point)
3166                    .length_squared();
3167                if distance < seed_distance {
3168                    seed_distance = distance;
3169                    seed = (cells.us[node_row], cells.vs[node_column]);
3170                }
3171            }
3172            if descend_cell(surface, point, seed, rectangle, domains, periodic, best, &mut bound, resolution, &mut settled, &cell_of, stats)? {
3173                return Ok(());
3174            }
3175            continue;
3176        }
3177        // A coarse cell: one descent per sub-rectangle, seeded at its nearest
3178        // corner, as the default lattice's cells there would be.
3179        let [split_u, split_v] = cells.split;
3180        let at = |low: f64, high: f64, index: usize, count: usize| if index == count { high } else { low + (high - low) * index as f64 / count as f64 };
3181        for i in 0..split_u {
3182            for j in 0..split_v {
3183                let sub = [
3184                    at(rectangle[0], rectangle[1], i, split_u),
3185                    at(rectangle[0], rectangle[1], i + 1, split_u),
3186                    at(rectangle[2], rectangle[3], j, split_v),
3187                    at(rectangle[2], rectangle[3], j + 1, split_v),
3188                ];
3189                // A sub-rectangle whose hull box stands farther than the bound
3190                // holds no nearer point; the cushion covers the split's and
3191                // the division's rounding.
3192                let index = (cell * split_u + i) * split_v + j;
3193                let cached = cells.sub_boxes.lock().ok().and_then(|boxes| boxes.get(&index).cloned());
3194                let hull = match cached {
3195                    Some(hull) => hull,
3196                    None => {
3197                        let [su, sv] = cells.samples;
3198                        let piece = |cell_index: usize, samples: usize, split: usize, sub: usize| {
3199                            let (span, k) = (cell_index / samples, cell_index % samples);
3200                            let steps = (samples * split) as f64;
3201                            (span, [(k * split + sub) as f64 / steps, (k * split + sub + 1) as f64 / steps])
3202                        };
3203                        let (span_u, range_u) = piece(row, su, split_u, i);
3204                        let (span_v, range_v) = piece(column, sv, split_v, j);
3205                        let hull = crate::curve_clear::patch_piece_controls(surface, span_u, span_v, range_u, range_v)
3206                            .and_then(|(controls, columns)| framed_box(&controls, columns, 64.0 * resolution));
3207                        if let Ok(mut boxes) = cells.sub_boxes.lock() { boxes.insert(index, hull.clone()); }
3208                        hull
3209                    }
3210                };
3211                if let Some(hull) = hull {
3212                    if hull.lower_bound(point) >= bound {
3213                        continue;
3214                    }
3215                }
3216                let mut seed = (sub[0], sub[2]);
3217                let mut seed_distance = f64::INFINITY;
3218                for (di, dj) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
3219                    let (u, v) = (sub[di], sub[2 + dj]);
3220                    let key = ((row * split_u + i + di) as u32, (column * split_v + j + dj) as u32);
3221                    let cached = cells.sub_nodes.lock().ok().and_then(|nodes| nodes.get(&key).copied());
3222                    let node = match cached {
3223                        Some(node) => node,
3224                        None => {
3225                            let node = surface.evaluate(u, v)?;
3226                            if let Ok(mut nodes) = cells.sub_nodes.lock() { nodes.insert(key, node); }
3227                            node
3228                        }
3229                    };
3230                    let distance = node.sub(point).length_squared();
3231                    if distance < seed_distance {
3232                        seed_distance = distance;
3233                        seed = (u, v);
3234                    }
3235                }
3236                if descend_cell(surface, point, seed, sub, domains, periodic, best, &mut bound, resolution, &mut settled, &cell_of, stats)? {
3237                    return Ok(());
3238                }
3239            }
3240        }
3241    }
3242    Ok(())
3243}
3244
3245/// One confined descent of [`global_minimum_with`] over `rectangle` from
3246/// `seed`, continued over the domain when its least point is on the
3247/// rectangle's edge; `best` and `bound` take an answer nearer than `bound`.
3248/// True when the answer reaches the on-surface floor.
3249#[allow(clippy::too_many_arguments)]
3250fn descend_cell(
3251    surface: &NurbsSurface,
3252    point: Vec3,
3253    seed: (f64, f64),
3254    rectangle: [f64; 4],
3255    domains: [f64; 4],
3256    periodic: (bool, bool),
3257    best: &mut NewtonResult,
3258    bound: &mut f64,
3259    resolution: f64,
3260    settled: &mut Vec<usize>,
3261    cell_of: &dyn Fn(f64, f64) -> usize,
3262    stats: &mut GlobalStats,
3263) -> Result<bool, String> {
3264    stats.refinements += 1;
3265    let (confined, on_edge) = confined_descent(surface, point, seed, rectangle, (false, false))?;
3266    let mut found = confined;
3267    if on_edge && confined.distance_squared.sqrt() < *bound {
3268        // The cell's least point is on its edge and beats the answer:
3269        // the basin continues past the cell.
3270        stats.continuations += 1;
3271        let (continued, _) =
3272            confined_descent(surface, point, (confined.u, confined.v), domains, periodic)?;
3273        if continued.distance_squared < found.distance_squared {
3274            found = continued;
3275        }
3276        if continued.converged {
3277            settled.push(cell_of(continued.u, continued.v));
3278        }
3279    }
3280    if found.distance_squared.sqrt() < *bound {
3281        *best = found;
3282        *bound = best.distance_squared.sqrt() - resolution;
3283        stats.replaced = true;
3284        if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
3285            return Ok(true);
3286        }
3287    }
3288    Ok(false)
3289}
3290
3291
3292
3293/// Domain handling for a local foot-point Newton walk.
3294#[derive(Clone, Copy)]
3295pub enum FootDomain {
3296    Clamp,
3297    Wrap,
3298    Extended,
3299}
3300
3301#[derive(Clone, Copy)]
3302pub struct CurveFootPolicy {
3303    pub domain: FootDomain,
3304    pub iterations: usize,
3305    pub slope_guard: f64,
3306    pub step_limit: f64,
3307    pub parameter_tolerance: f64,
3308    pub mode: FootMode,
3309}
3310
3311/// Acceptance and convergence differ between a distance minimum and a stationary root.
3312#[derive(Clone, Copy)]
3313pub enum FootMode {
3314    Monotone,
3315    Witness,
3316    Stationary { positive_slope: bool, relative_step: bool },
3317    Backtracked,
3318    Planar,
3319}
3320
3321/// Local Newton foot. Seeding and enumeration of local minima belong to the caller.
3322/// Returns the last parameter, best witnessed parameter, and squared distance.
3323fn curve_foot_newton_state(
3324    curve: &NurbsCurve,
3325    point: Vec3,
3326    seed: f64,
3327    bracket: [f64; 2],
3328    policy: CurveFootPolicy,
3329) -> Result<(f64, f64, f64), String> {
3330    let fit = |u| match policy.domain {
3331        FootDomain::Clamp => fit_parameter(u, bracket[0], bracket[1], false),
3332        FootDomain::Wrap => fit_parameter(u, bracket[0], bracket[1], true),
3333        FootDomain::Extended => u,
3334    };
3335    let extended = matches!(policy.domain, FootDomain::Extended) || matches!(policy.mode, FootMode::Backtracked);
3336    let planar = matches!(policy.mode, FootMode::Planar);
3337    let project = |p: Vec3| if planar { Vec3::new(p.x, p.y, 0.0) } else { p };
3338    let point = project(point);
3339    let distance = |u| -> Result<f64, String> {
3340        let p = if extended { curve.derivatives_extended(u, 0)?[0] } else { curve.evaluate(u)? };
3341        Ok(project(p).sub(point).length())
3342    };
3343    let monotone = matches!(policy.mode, FootMode::Monotone | FootMode::Backtracked);
3344    let witness = matches!(policy.mode, FootMode::Witness);
3345    let mut u = if witness { seed } else { fit(seed) };
3346    let mut nearest_u = seed;
3347    let mut nearest_squared = f64::INFINITY;
3348    let mut best = if monotone { distance(u)? } else { f64::INFINITY };
3349    for _ in 0..policy.iterations {
3350        let derivatives = if extended {
3351            let values = curve.derivatives_extended(u, 2)?;
3352            [values[0], values[1], values[2]]
3353        } else if matches!(policy.mode, FootMode::Stationary { .. })
3354            || (planar && !crate::curve::small_curve_derivatives_enabled()) {
3355            let values = curve.derivatives(u, 2)?;
3356            [values[0], values[1], values[2]]
3357        } else {
3358            curve.derivatives_small(u, 2)?
3359        }.map(project);
3360        let offset = derivatives[0].sub(point);
3361        let numerator = offset.dot(derivatives[1]);
3362        let denominator = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
3363        if witness {
3364            let squared = offset.length_squared();
3365            if squared < nearest_squared {
3366                nearest_u = u;
3367                nearest_squared = squared;
3368            }
3369            let residual_length = squared.sqrt();
3370            if residual_length <= LINEAR_TOLERANCE
3371                || numerator.abs() <= EPSILON + 1e-10 * derivatives[1].length() * residual_length {
3372                break;
3373            }
3374        }
3375        let singular = if planar { denominator.abs() < policy.slope_guard }
3376            else { denominator.abs() <= policy.slope_guard };
3377        if singular || (matches!(policy.mode, FootMode::Stationary { positive_slope: true, .. }) && !(denominator > 0.0)) { break; }
3378        let mut step = if matches!(policy.mode, FootMode::Backtracked) && !(denominator > 0.0) {
3379            policy.step_limit.copysign(numerator)
3380        } else {
3381            (numerator / denominator).clamp(-policy.step_limit, policy.step_limit)
3382        };
3383        let mut next = fit(u - step);
3384        let mut next_distance = if monotone { distance(next)? } else { f64::INFINITY };
3385        if matches!(policy.mode, FootMode::Backtracked) {
3386            for _ in 0..30 {
3387                if next_distance < best { break; }
3388                step *= 0.5;
3389                next = fit(u - step);
3390                next_distance = distance(next)?;
3391            }
3392            if !(next_distance < best) { break; }
3393        } else if monotone && next_distance >= best { break; }
3394        let moved = if planar || matches!(policy.domain, FootDomain::Extended) { step }
3395            else if matches!(policy.domain, FootDomain::Wrap) {
3396                let period = bracket[1] - bracket[0];
3397                let raw = next - u;
3398                raw - period * (raw / period).round()
3399            } else { next - u };
3400        let tolerance = if matches!(policy.mode, FootMode::Stationary { relative_step: true, .. }) {
3401            policy.parameter_tolerance * (1.0 + u.abs())
3402        } else { policy.parameter_tolerance };
3403        let small = if planar || matches!(policy.mode, FootMode::Backtracked) { moved.abs() < tolerance }
3404            else { moved.abs() <= tolerance };
3405        if small && matches!(policy.mode, FootMode::Monotone) { break; }
3406        u = next;
3407        best = next_distance;
3408        if small { break; }
3409    }
3410    if witness { return Ok((u, nearest_u, nearest_squared)); }
3411    if !monotone { best = distance(u)?; }
3412    Ok((u, u, best * best))
3413}
3414
3415pub fn curve_foot_newton(
3416    curve: &NurbsCurve, point: Vec3, seed: f64, bracket: [f64; 2], policy: CurveFootPolicy,
3417) -> Result<(f64, f64), String> {
3418    let (_, nearest, squared) = curve_foot_newton_state(curve, point, seed, bracket, policy)?;
3419    Ok((nearest, squared))
3420}
3421
3422
3423
3424
3425