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, cad-bot). 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
180type CurveSeeds = std::rc::Rc<Vec<(f64, Vec3)>>;
181const CURVE_SEED_BUDGET: usize = 262_144;
182thread_local! {
183    static CURVE_SEEDS: std::cell::RefCell<(rustc_hash::FxHashMap<[u64; 2], CurveSeeds>, usize)> = Default::default();
184}
185
186/// Discard the bounded per-thread seed geometry at a cold history boundary.
187pub fn clear_curve_seed_cache() {
188    CURVE_SEEDS.with(|memo| *memo.borrow_mut() = Default::default());
189}
190
191fn visit_curve_seeds(curve: &NurbsCurve, start: f64, end: f64, mut visit: impl FnMut(f64, Vec3)) -> Result<(), String> {
192    let mut breaks = vec![start];
193    breaks.extend(interior_knots(&curve.knots, curve.degree));
194    breaks.push(end);
195    let samples_per_span = 4usize.max(curve.degree + 2);
196    for pair in breaks.windows(2) {
197        for index in 0..=samples_per_span {
198            let parameter = pair[0] + (pair[1] - pair[0]) * index as f64 / samples_per_span as f64;
199            visit(parameter, curve.evaluate(parameter)?);
200        }
201    }
202    Ok(())
203}
204
205/// Cache only the curve-dependent seed geometry, in its original sequence.
206/// Every query still performs the same distance comparisons, witness search,
207/// Newton iterations and tie breaking. The content key includes every knot
208/// and homogeneous control bit; failed sampling is never retained.
209fn cached_curve_seeds(curve: &NurbsCurve, start: f64, end: f64) -> Result<Option<CurveSeeds>, String> {
210    if !switch!("BREP_CURVE_PROJECTION_SEEDS", false) { return Ok(None); }
211    // Avoid allocating a giant one-off vector even when it would not be kept.
212    let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
213    if bound > CURVE_SEED_BUDGET { return Ok(None); }
214    let mut key = crate::identity_hash::TwoLane::new();
215    crate::identity_hash::hash_curve(&mut key, curve);
216    key.f64(start); key.f64(end);
217    let key = key.finish();
218    if let Some(seeds) = CURVE_SEEDS.with(|memo| memo.borrow().0.get(&key).cloned()) {
219        return Ok(Some(seeds));
220    }
221    let mut seeds = Vec::new();
222    visit_curve_seeds(curve, start, end, |u, point| seeds.push((u, point)))?;
223    let seeds = std::rc::Rc::new(seeds);
224    CURVE_SEEDS.with(|memo| {
225        let mut memo = memo.borrow_mut();
226        if memo.0.len() >= PROJECTION_MEMO_ENTRIES || memo.1 + seeds.len() > CURVE_SEED_BUDGET {
227            memo.0.clear(); memo.1 = 0;
228        }
229        memo.1 += seeds.len();
230        memo.0.insert(key, seeds.clone());
231    });
232    Ok(Some(seeds))
233}
234
235fn project_point_to_curve_uncached(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
236    let [start, end] = curve.domain()?;
237    let mut best_u = start;
238    let mut best_distance_squared = f64::INFINITY;
239    // The sweep's FIRST sample is exactly `start` and its LAST is exactly `end`
240    // (`breaks` opens at `start` and closes at `end`, and index 0 / index
241    // `samples_per_span` hit a span's own ends), so closure costs no extra
242    // evaluation: keep those two points and compare them.
243    let mut start_point = None;
244    let mut end_point = None;
245    // The sampled polyline's own nearest approach, and the seed interval that
246    // achieves it. Squared throughout, so the sweep pays no square root.
247    let mut previous: Option<(f64, Vec3)> = None;
248    let mut witness_distance_squared = f64::INFINITY;
249    let mut witness_low = start;
250    let mut witness_high = start;
251    let mut visit = |parameter, sample: Vec3| {
252        if start_point.is_none() {
253            start_point = Some(sample);
254        }
255        end_point = Some(sample);
256        let distance_squared = sample.sub(point).length_squared();
257        if distance_squared < best_distance_squared {
258            best_distance_squared = distance_squared;
259            best_u = parameter;
260        }
261        if let Some((previous_parameter, previous_sample)) = previous {
262            let segment = point_segment_distance_squared(point, previous_sample, sample);
263            if segment < witness_distance_squared {
264                witness_distance_squared = segment;
265                witness_low = previous_parameter;
266                witness_high = parameter;
267            }
268        }
269        previous = Some((parameter, sample));
270    };
271    if let Some(seeds) = cached_curve_seeds(curve, start, end)? {
272        for &(parameter, sample) in seeds.iter() { visit(parameter, sample); }
273    } else {
274        visit_curve_seeds(curve, start, end, visit)?;
275    }
276    // A closed curve's domain is PERIODIC, so Newton must wrap across the seam
277    // rather than stop at it. Clamping made the projector return the seam for
278    // any query whose foot sits within half a seed spacing of it: `start` and
279    // `end` are the same POINT, the sweep keeps the first of equal distances and
280    // so seeds at `start`, and a Newton step toward a foot just BEFORE the seam
281    // is then clamped back to `start`, reads as a zero-length step, and breaks.
282    // Measured on a rational-quadratic circle of radius 20: 4.796 mm out, for a
283    // point taken off the curve itself. Swapping the sweep's tie-break to keep
284    // the LAST equal sample does not fix this — it mirrors it, returning the
285    // same 4.796 mm for queries just AFTER the seam. The surface projector has
286    // always wrapped (`fit_parameter` at the `project_point_to_surface` Newton
287    // step); this is the curve side catching up.
288    const CLOSED_SEAM_TOLERANCE: f64 = 1e-6;
289    let closed = match (start_point, end_point) {
290        (Some(first), Some(last)) => first.sub(last).length() <= CLOSED_SEAM_TOLERANCE,
291        _ => false,
292    };
293
294    let parameter = curve_newton(
295        curve,
296        point,
297        best_u,
298        start,
299        end,
300        closed,
301        &mut best_u,
302        &mut best_distance_squared,
303    )?;
304    for candidate in [start, end, parameter] {
305        let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
306        if distance_squared < best_distance_squared {
307            best_distance_squared = distance_squared;
308            best_u = candidate;
309        }
310    }
311    // AN ANSWER THE SEED POLYLINE REFUTES IS NOT AN ANSWER. The sweep's
312    // consecutive samples are a polyline that approximates the curve, so the
313    // nearest that polyline passes to the query is a witness: the curve
314    // demonstrably comes about that close. When the answer is FARTHER than the
315    // witness by more than a factor of two, Newton converged in the wrong basin
316    // and the seed interval the witness names is where the foot really is.
317    //
318    // Two different defects reach here, both of them "a point ON the curve does
319    // not project to its own parameter", and both measured on real geometry:
320    //
321    // * A STATIONARY seed. Newton is a first-order method and
322    //   `f = C'(t) · (C(t) - P)` vanishes at a stationary parameter for EVERY
323    //   `P`, so the iteration reads convergence there whatever the point is, and
324    //   the step it would otherwise take is `-f/f''`, a second-order quantity
325    //   whose sign has nothing to do with where the foot is. The 2026-09-14
326    //   herringbone document is full of them: a flank pcurve is a two-span cubic
327    //   whose first two control points COINCIDE (an involute's speed is
328    //   `r_base * t`, so its Hermite start tangent is exactly zero), the sweep's
329    //   nearest sample to a query near the start IS that cusp, and a point lying
330    //   exactly on the curve at t = 0.125 answered t = 0, 2.159e-2 out in uv.
331    //   That is the wrong answer `build_loop`'s partial-run rescue declined on.
332    // * A seed grid coarser in ONE span than in the rest. An imported pcurve
333    //   from `abc_00000013.step` carries 511 interior knots whose first span is
334    //   eighty times the width of the median, and five samples per span leave
335    //   its samples 4.6e-3 of uv apart — so a point on the curve at fraction
336    //   0.01 read as 3.969e-3 from a DIFFERENT branch at fraction 0.99, which
337    //   was genuinely nearer than any sample of its own.
338    //
339    // The witness refuted both by 71x and by 293000x. Every update below is a
340    // strict improvement on the distance already found, so a rescue that finds
341    // nothing better leaves the answer exactly where it was.
342    const WITNESS_FACTOR: f64 = 2.0;
343    if witness_distance_squared * (WITNESS_FACTOR * WITNESS_FACTOR) < best_distance_squared
344        && witness_rescue_enabled()
345    {
346        let bracketed = bracketed_nearest(curve, point, witness_low, witness_high)?;
347        let polished = curve_newton(
348            curve,
349            point,
350            bracketed,
351            start,
352            end,
353            closed,
354            &mut best_u,
355            &mut best_distance_squared,
356        )?;
357        for candidate in [bracketed, polished] {
358            let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
359            if distance_squared < best_distance_squared {
360                best_distance_squared = distance_squared;
361                best_u = candidate;
362            }
363        }
364    }
365    let projected = curve.evaluate(best_u)?;
366    Ok(CurveProjection {
367        u: best_u,
368        point: projected,
369        distance: projected.sub(point).length(),
370    })
371}
372
373fn project_linear_revolution(
374    surface: &NurbsSurface,
375    point: Vec3,
376) -> Result<Option<SurfaceProjection>, String> {
377    let rows = &surface.control_points;
378    if surface.degree_u != 2
379        || surface.degree_v != 1
380        || rows.len() < 5
381        || rows[0].len() != 2
382        || !surface.closed_directions()?.0
383    {
384        return Ok(None);
385    }
386    let base = rows[0][0].point()?.add(rows[4][0].point()?).scale(0.5);
387    let top = rows[0][1].point()?.add(rows[4][1].point()?).scale(0.5);
388    let axis_vector = top.sub(base);
389    let height = axis_vector.length();
390    if height <= EPSILON {
391        return Ok(None);
392    }
393    let axis = axis_vector.normalized()?;
394    let [v0, v1] = surface.domain_v()?;
395    let axial = point.sub(base).dot(axis).clamp(0.0, height);
396    let v = v0 + (v1 - v0) * axial / height;
397    let circle = surface.iso_curve_v(v)?;
398    let projection = project_point_to_curve(&circle, point)?;
399    let [u0, u1] = surface.domain_u()?;
400    let u = projection.u.clamp(u0, u1);
401    let projected = surface.evaluate(u, v)?;
402    Ok(Some(SurfaceProjection {
403        u,
404        v,
405        point: projected,
406        distance: projected.sub(point).length(),
407    }))
408}
409
410#[derive(Clone, Copy)]
411struct NewtonResult {
412    u: f64,
413    v: f64,
414    distance_squared: f64,
415    converged: bool,
416}
417
418fn surface_newton(
419    surface: &NurbsSurface,
420    point: Vec3,
421    seed_u: f64,
422    seed_v: f64,
423    domains: [f64; 4],
424    closed_u: bool,
425    closed_v: bool,
426) -> Result<NewtonResult, String> {
427    surface_newton_impl(surface, point, seed_u, seed_v, domains, closed_u, closed_v,
428        switch!("BREP_PROJECTION_LAZY_DERIVATIVES", false), LINEAR_TOLERANCE)
429}
430
431/// Most seeded verification queries are already on the carrier. Row zero
432/// uses the same basis and rational arithmetic at counts zero and two; read
433/// it first, preserving the best-point and distance exit, and compute the
434/// remaining derivatives only when Newton actually needs to take a step.
435fn surface_newton_impl(
436    surface: &NurbsSurface,
437    point: Vec3,
438    seed_u: f64,
439    seed_v: f64,
440    domains: [f64; 4],
441    closed_u: bool,
442    closed_v: bool,
443    lazy: bool,
444    linear_tolerance: f64,
445) -> Result<NewtonResult, String> {
446    let [u0, u1, v0, v1] = domains;
447    let mut u = seed_u;
448    let mut v = seed_v;
449    let mut converged = false;
450    let mut best = NewtonResult {
451        u,
452        v,
453        distance_squared: surface.evaluate(u, v)?.sub(point).length_squared(),
454        converged,
455    };
456    // A step is a function of (u, v) alone, so an iterate that returns to an
457    // earlier one bit for bit repeats that stretch until the iteration cap:
458    // no exit fires (none did on the first pass through it), the best point
459    // cannot improve (every state of the stretch has been read, and the
460    // comparison is strict), and the state the cap would leave is the stretch's
461    // state at the cap's index. Take that state now instead of walking there
462    // (`BREP_PROJECTION_NEWTON_CYCLE_EXIT`, default on; `=0` walks). Measured
463    // on one import with fitted high-degree carriers and the projected-foot
464    // refine on: about one Newton call in eighteen ran to the cap, those calls
465    // held half of all Newton iterations, and at least three in five of them
466    // were repeating a stretch of eight states or fewer.
467    let cycle_exit = switch!("BREP_PROJECTION_NEWTON_CYCLE_EXIT", true);
468    let mut trail = [(0u64, 0u64); MAX_NEWTON_ITERATIONS];
469    for iteration in 0..MAX_NEWTON_ITERATIONS {
470        if cycle_exit {
471            let state = (u.to_bits(), v.to_bits());
472            if let Some(first) = trail[..iteration].iter().position(|earlier| *earlier == state) {
473                let period = iteration - first;
474                let (last_u, last_v) = trail[first + (MAX_NEWTON_ITERATIONS - first) % period];
475                u = f64::from_bits(last_u);
476                v = f64::from_bits(last_v);
477                crate::work_counts::add(|c| c.newton_iterations += (MAX_NEWTON_ITERATIONS - iteration) as u64);
478                break;
479            }
480            trail[iteration] = state;
481        }
482        crate::work_counts::add(|c| c.newton_iterations += 1);
483        let derivatives = surface.derivatives_small(u, v, if lazy { 0 } else { 2 })?;
484        let residual = derivatives[0][0].sub(point);
485        let distance_squared = residual.length_squared();
486        if distance_squared < best.distance_squared {
487            best.u = u;
488            best.v = v;
489            best.distance_squared = distance_squared;
490        }
491        let residual_length = distance_squared.sqrt();
492        if residual_length <= linear_tolerance {
493            crate::work_counts::add(|c| { c.newton_unused += 1; c.newton_unused_first += u64::from(iteration == 0); });
494            converged = true;
495            break;
496        }
497        let derivatives = if lazy { surface.derivatives_small(u, v, 2)? } else { derivatives };
498        let f = derivatives[1][0].dot(residual);
499        let g = derivatives[0][1].dot(residual);
500        let tangent_u_length = derivatives[1][0].length();
501        let tangent_v_length = derivatives[0][1].length();
502        let cosine_u = if tangent_u_length * residual_length <= EPSILON {
503            0.0
504        } else {
505            f.abs() / (tangent_u_length * residual_length)
506        };
507        let cosine_v = if tangent_v_length * residual_length <= EPSILON {
508            0.0
509        } else {
510            g.abs() / (tangent_v_length * residual_length)
511        };
512        if cosine_u <= 1e-10 && cosine_v <= 1e-10 {
513            converged = true;
514            break;
515        }
516        let j00 = derivatives[2][0].dot(residual) + derivatives[1][0].length_squared();
517        let j01 = derivatives[1][1].dot(residual) + derivatives[1][0].dot(derivatives[0][1]);
518        let j11 = derivatives[0][2].dot(residual) + derivatives[0][1].length_squared();
519        let determinant = j00 * j11 - j01 * j01;
520        if determinant.abs() <= EPSILON {
521            break;
522        }
523        let mut du = (-f * j11 + g * j01) / determinant;
524        let mut dv = (-g * j00 + f * j01) / determinant;
525        du = du.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
526        dv = dv.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
527        let next_u = fit_parameter(u + du, u0, u1, closed_u);
528        let next_v = fit_parameter(v + dv, v0, v1, closed_v);
529        let stalled =
530            (next_u - u).abs() <= 1e-15 * (u1 - u0) && (next_v - v).abs() <= 1e-15 * (v1 - v0);
531        u = next_u;
532        v = next_v;
533        if stalled {
534            break;
535        }
536    }
537    let final_distance_squared = surface.evaluate(u, v)?.sub(point).length_squared();
538    if final_distance_squared < best.distance_squared {
539        best.u = u;
540        best.v = v;
541        best.distance_squared = final_distance_squared;
542    }
543    best.converged = converged;
544    Ok(best)
545}
546
547/// Refine an existing branch foot for precision trim construction. The normal
548/// projector's distance exit is an on-carrier admission test, not a bound on
549/// tangential placement suitable for interpolating a more accurate trim.
550pub fn refine_trim_foot(
551    surface: &NurbsSurface, point: Vec3, foot: SurfaceProjection,
552) -> Result<SurfaceProjection, String> {
553    let [u0, u1] = surface.domain_u()?;
554    let [v0, v1] = surface.domain_v()?;
555    let (cu, cv) = surface.closed_directions()?;
556    let result = surface_newton_impl(surface, point, foot.u, foot.v,
557        [u0, u1, v0, v1], cu, cv, false, 1e-11)?;
558    let projected = surface.evaluate(result.u, result.v)?;
559    Ok(SurfaceProjection { u: result.u, v: result.v, point: projected,
560        distance: projected.sub(point).length() })
561}
562
563/// The point of `surface` nearest `point`, over the surface's whole domain.
564///
565/// Analytic carriers answer in closed form; every other surface goes through
566/// `project_point_to_surface_general`, which says what it guarantees.
567/// `#[track_caller]` names the call site in the `BREP_PROJECTION_AUDIT` log.
568#[track_caller]
569pub fn project_point_to_surface(
570    surface: &NurbsSurface,
571    point: Vec3,
572) -> Result<SurfaceProjection, String> {
573    crate::work_counts::add(|c| c.projection_global += 1);
574    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_PROJECT, surface);
575    // Recognized analytic carriers (plane / cylinder / cone / sphere /
576    // torus) have exact closed-form projections in the surface's own
577    // rational parameterization — skip grid seeding and Newton entirely.
578    if let Some(analytic) = surface.analytic() {
579        if let Some(projection) = analytic.project(surface, point) {
580            return Ok(projection);
581        }
582    }
583    if let Some(ellipsoid) = surface.affine_sphere() {
584        if let Some(projection) = ellipsoid.project(surface, point) {
585            return Ok(projection);
586        }
587    }
588    project_point_to_surface_general(surface, point)
589}
590
591/// Project a point onto a surface starting Newton from an explicit `(u, v)`
592/// guess, WITHOUT the global grid seed. This is a footpoint refiner for
593/// continuity-preserving curve-on-surface tracing: seeding each edge sample
594/// from its neighbour's parameters keeps the fit on ONE branch of a surface
595/// that folds back over the small trimmed patch, where an independent global
596/// search would snap to whichever fold is momentarily closest and tear the
597/// pcurve into a self-crossing zig-zag. The caller compares the returned
598/// `distance` against the global answer and only adopts this result when it is
599/// geometrically just as valid, so a bad seed can never make a fit worse.
600pub fn project_point_to_surface_seeded(
601    surface: &NurbsSurface,
602    point: Vec3,
603    seed_u: f64,
604    seed_v: f64,
605) -> Result<SurfaceProjection, String> {
606    crate::work_counts::add(|c| c.projection_seeded += 1);
607    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
608    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_SEEDED, surface);
609    // An ellipsoid's foot is unique off its medial axis: the closed form IS
610    // the branch answer, as it is for the analytic carriers at the seeded
611    // entry (`project_point_to_surface_from_seed`).
612    if let Some(ellipsoid) = surface.affine_sphere() {
613        if let Some(projection) = ellipsoid.project(surface, point) {
614            return Ok(projection);
615        }
616    }
617    let [u0, u1] = surface.domain_u()?;
618    let [v0, v1] = surface.domain_v()?;
619    let (closed_u, closed_v) = surface.closed_directions()?;
620    let result = surface_newton(
621        surface,
622        point,
623        seed_u,
624        seed_v,
625        [u0, u1, v0, v1],
626        closed_u,
627        closed_v,
628    )?;
629    let projected = surface.evaluate(result.u, result.v)?;
630    Ok(SurfaceProjection {
631        u: result.u,
632        v: result.v,
633        point: projected,
634        distance: projected.sub(point).length(),
635    })
636}
637
638/// The foot of `point` on the branch of `seed`: the closed form on an analytic
639/// carrier, otherwise Newton from the caller's own `(u, v)`
640/// ([`project_point_to_surface_seeded`]), WITHOUT the global search.
641///
642/// **Which callers.** One that already holds a foot on this surface from a
643/// geometrically adjacent query and whose output needs continuity with it: a
644/// pcurve's previous sample, a march's previous station, a Newton's previous
645/// iterate. [`project_point_to_surface`] answers a different question — where
646/// on the WHOLE surface the point is nearest — and on a carrier that comes back
647/// near itself, or for an off-surface query about as far from two sheets, that
648/// answer is a foot on another branch: a pcurve sample on the wrong sheet, an
649/// iterate that jumps. A caller with no such foot (a vertex, a probe, the first
650/// station) asks the nearest-point question and calls the projector.
651///
652/// **An analytic carrier** answers in closed form, as the projector does. Its
653/// only places with two equally valid feet are its seam, its poles and its focal
654/// set (axis, centre, tube circle), and the closed form answers those exactly as
655/// the nearest-point query always has; no march on one changes.
656///
657/// **What it does not promise.** It is a local answer: its distance is an upper
658/// bound, and a Newton that stalls returns its best iterate without saying so.
659/// Every caller keeps its own on-surface check.
660///
661/// **Instruments**, each read once. `BREP_PROJECTION_FROM_SEED=0` returns
662/// [`project_point_to_surface`]'s answer at every caller (the reading before
663/// 2026-09-15, for a same-binary A/B); `BREP_PROJECTION_FROM_SEED_SITES=<a,b,…>`
664/// keeps the seeded answer only at the call sites whose `file:line` contains
665/// one of the substrings. Under `BREP_PROJECTION_AUDIT=<dir>` every query whose
666/// seeded foot lies farther than the on-surface floor from the nearest point's
667/// foot appends one line to `<dir>/projection-seed-audit-<pid>.tsv`. That
668/// comparand is the nearest-point projector under the same caller, so its own
669/// replacements land in `projection-audit-<pid>.tsv` at this site's line: they
670/// are the audit's, not an answer the caller took.
671#[track_caller]
672pub fn project_point_to_surface_from_seed(
673    surface: &NurbsSurface,
674    point: Vec3,
675    seed: [f64; 2],
676) -> Result<SurfaceProjection, String> {
677    crate::work_counts::add(|c| c.projection_from_seed += 1);
678    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
679    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_SEED, surface);
680    if let Some(analytic) = surface.analytic() {
681        if let Some(projection) = analytic.project(surface, point) {
682            return Ok(projection);
683        }
684    }
685    if let Some(ellipsoid) = surface.affine_sphere() {
686        if let Some(projection) = ellipsoid.project(surface, point) {
687            return Ok(projection);
688        }
689    }
690    let caller = std::panic::Location::caller();
691    if !seeded_answer_admitted(caller) {
692        return project_point_to_surface_general(surface, point);
693    }
694    let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
695    if seed_audit_enabled() {
696        let nearest = project_point_to_surface_general(surface, point)?;
697        if seeded.point.sub(nearest.point).length() > LINEAR_TOLERANCE {
698            seed_audit_record(caller, surface, seed, &seeded, &nearest);
699        }
700    }
701    Ok(seeded)
702}
703
704/// `BREP_PROJECTION_FROM_SEED=0` / `BREP_PROJECTION_FROM_SEED_SITES`: see
705/// [`project_point_to_surface_from_seed`].
706fn seeded_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
707    static SITES: std::sync::OnceLock<Option<Option<Vec<String>>>> = std::sync::OnceLock::new();
708    let sites = SITES.get_or_init(|| {
709        if std::env::var("BREP_PROJECTION_FROM_SEED").as_deref() == Ok("0") {
710            return None;
711        }
712        Some(std::env::var("BREP_PROJECTION_FROM_SEED_SITES").ok().map(|value| {
713            value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect()
714        }))
715    });
716    match sites {
717        None => false,
718        Some(None) => true,
719        Some(Some(only)) => {
720            let location = format!("{}:{}", caller.file(), caller.line());
721            only.iter().any(|site| location.contains(site.as_str()))
722        }
723    }
724}
725
726fn seed_audit_enabled() -> bool {
727    debug_flag!("BREP_PROJECTION_AUDIT")
728}
729
730/// One line per seeded answer whose foot is not the nearest point's: the call
731/// site, both distances, the seed, both feet's `(u, v)`, the separation of the
732/// two feet and the surface's shape.
733fn seed_audit_record(
734    caller: &std::panic::Location<'_>,
735    surface: &NurbsSurface,
736    seed: [f64; 2],
737    seeded: &SurfaceProjection,
738    nearest: &SurfaceProjection,
739) {
740    use std::io::Write;
741    static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
742        std::sync::OnceLock::new();
743    let sink = SINK.get_or_init(|| {
744        let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
745        let path = std::path::Path::new(&directory)
746            .join(format!("projection-seed-audit-{}.tsv", std::process::id()));
747        std::fs::OpenOptions::new()
748            .create(true)
749            .append(true)
750            .open(path)
751            .ok()
752            .map(std::sync::Mutex::new)
753    });
754    if let Some(file) = sink {
755        if let Ok(mut file) = file.lock() {
756            let _ = writeln!(
757                file,
758                "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.6e}\t{}x{} cp {}x{}",
759                caller.file(),
760                caller.line(),
761                seeded.distance,
762                nearest.distance,
763                seed[0],
764                seed[1],
765                seeded.u,
766                seeded.v,
767                nearest.u,
768                nearest.v,
769                seeded.point.sub(nearest.point).length(),
770                surface.degree_u,
771                surface.degree_v,
772                surface.control_points.len(),
773                surface.control_points.first().map(Vec::len).unwrap_or(0),
774            );
775        }
776    }
777}
778
779/// The Newton seed grid for general projection: (u, v, point) samples over
780/// every knot span. A pure function of the surface, cached on it — building
781/// the grid costs hundreds of evaluations and projection is the hottest
782/// entry point in the kernel.
783fn projection_seed_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
784    if let Some(grid) = surface.projection_grid.get() {
785        return Ok(grid);
786    }
787    let [u0, u1] = surface.domain_u()?;
788    let [v0, v1] = surface.domain_v()?;
789    let (closed_u, closed_v) = surface.closed_directions()?;
790    let mut breaks_u = vec![u0];
791    breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
792    breaks_u.push(u1);
793    let mut breaks_v = vec![v0];
794    breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
795    breaks_v.push(v1);
796    let samples_u = if closed_u {
797        8usize.max(surface.degree_u * 4)
798    } else {
799        3usize.max(surface.degree_u + 1)
800    };
801    let samples_v = if closed_v {
802        8usize.max(surface.degree_v * 4)
803    } else {
804        3usize.max(surface.degree_v + 1)
805    };
806    let mut grid = Vec::new();
807    for u_pair in breaks_u.windows(2) {
808        for v_pair in breaks_v.windows(2) {
809            for i in 0..=samples_u {
810                for j in 0..=samples_v {
811                    let u = u_pair[0] + (u_pair[1] - u_pair[0]) * i as f64 / samples_u as f64;
812                    let v = v_pair[0] + (v_pair[1] - v_pair[0]) * j as f64 / samples_v as f64;
813                    grid.push((u, v, surface.evaluate(u, v)?));
814                }
815            }
816        }
817    }
818    Ok(surface.projection_grid.get_or_init(|| SampleGrid::new(grid)))
819}
820
821/// The dense fallback grid for degenerate general projection: (u, v, point)
822/// over a `(count_u+1) × (count_v+1)` lattice with `count_u/count_v` derived
823/// from the surface's knot spans. A pure function of the surface, cached on
824/// it — on metre-unit-mm parts the degenerate fallback fires ~1.7M times and
825/// each re-evaluated all ~561 lattice points; caching them makes the argmin a
826/// pure distance scan over reused points (bit-identical seed).
827fn projection_dense_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
828    if let Some(grid) = surface.projection_dense_grid.get() {
829        return Ok(grid);
830    }
831    let [u0, u1] = surface.domain_u()?;
832    let [v0, v1] = surface.domain_v()?;
833    let mut breaks_u = vec![u0];
834    breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
835    breaks_u.push(u1);
836    let mut breaks_v = vec![v0];
837    breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
838    breaks_v.push(v1);
839    let count_u = 32usize.max((breaks_u.len() - 1) * 8);
840    let count_v = 16usize.max((breaks_v.len() - 1) * 8);
841    let mut grid = Vec::with_capacity((count_u + 1) * (count_v + 1));
842    for i in 0..=count_u {
843        for j in 0..=count_v {
844            let u = u0 + (u1 - u0) * i as f64 / count_u as f64;
845            let v = v0 + (v1 - v0) * j as f64 / count_v as f64;
846            grid.push((u, v, surface.evaluate(u, v)?));
847        }
848    }
849    Ok(surface.projection_dense_grid.get_or_init(|| SampleGrid::with_tree(grid)))
850}
851
852/// Samples per block of a [`SampleGrid`].
853const SAMPLE_BLOCK: usize = 32;
854
855/// Runs per group: the scan's second level, a box over [`GROUP_BLOCKS`]
856/// consecutive runs ([`SampleGrid::groups`]).
857const GROUP_BLOCKS: usize = 32;
858
859/// A cached `(u, v, point)` sample grid, with the axis-aligned box of each run
860/// of [`SAMPLE_BLOCK`] consecutive samples, so the nearest-sample scan
861/// ([`nearest_sample`]) skips a run none of whose samples can beat the answer
862/// it holds.
863#[derive(Clone, Debug)]
864pub struct SampleGrid {
865    samples: Vec<(f64, f64, Vec3)>,
866    blocks: Vec<SampleBlock>,
867    /// The union box of each [`GROUP_BLOCKS`] consecutive runs, prunable only
868    /// when every run in it is. A union box's floor is at most each of its
869    /// runs' floors as computed (the box faces are the runs' own, and the gap
870    /// to a face farther out is no larger, IEEE rounding being monotone).
871    groups: Vec<SampleBlock>,
872    /// The box tree over the runs ([`nearest_sample_tree`]): `tree[0]` boxes
873    /// each [`TREE_FANOUT`] consecutive runs, `tree[k]` each [`TREE_FANOUT`]
874    /// consecutive boxes of `tree[k - 1]`, up to a single root. Built only by
875    /// [`SampleGrid::with_tree`] (the dense grid), and empty when the grid has
876    /// at most one group of runs.
877    tree: Vec<Vec<SampleBlock>>,
878}
879
880/// Children per node of [`SampleGrid::tree`].
881const TREE_FANOUT: usize = 4;
882
883/// The union box of consecutive boxes, prunable only when each of them is.
884fn union_boxes(boxes: &[SampleBlock]) -> Vec<SampleBlock> {
885    boxes
886        .chunks(TREE_FANOUT)
887        .map(|chunk| {
888            let mut union = chunk[0];
889            for block in chunk {
890                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));
891                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));
892                union.prunable &= block.prunable;
893            }
894            union
895        })
896        .collect()
897}
898
899/// One run's box. `prunable` is false when a sample has a non-finite
900/// coordinate: the box says nothing about it, and the run is always scanned.
901#[derive(Clone, Copy, Debug)]
902struct SampleBlock {
903    low: Vec3,
904    high: Vec3,
905    prunable: bool,
906}
907
908impl SampleGrid {
909    fn new(samples: Vec<(f64, f64, Vec3)>) -> Self {
910        let blocks = samples
911            .chunks(SAMPLE_BLOCK)
912            .map(|chunk| {
913                let mut low = chunk[0].2;
914                let mut high = low;
915                let mut prunable = true;
916                for &(_, _, p) in chunk {
917                    prunable &= p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
918                    low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
919                    high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
920                }
921                SampleBlock { low, high, prunable }
922            })
923            .collect::<Vec<_>>();
924        let groups = blocks
925            .chunks(GROUP_BLOCKS)
926            .map(|chunk| {
927                let mut group = chunk[0];
928                for block in chunk {
929                    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));
930                    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));
931                    group.prunable &= block.prunable;
932                }
933                group
934            })
935            .collect();
936        Self { samples, blocks, groups, tree: Vec::new() }
937    }
938
939    /// The grid with its box tree, for a scan that starts from a held answer
940    /// (the dense fallback after a Newton): there the tree reads few floors.
941    /// A scan from no answer reads its bound from a greedy descent, which on a
942    /// surface whose boxes mostly hold the point lands on an arbitrary run;
943    /// ABC 00027566's seed scans took 75 s through the tree against 44 s
944    /// through the groups, so the seed grid keeps the groups.
945    fn with_tree(samples: Vec<(f64, f64, Vec3)>) -> Self {
946        let mut grid = Self::new(samples);
947        if grid.blocks.len() > GROUP_BLOCKS {
948            grid.tree.push(union_boxes(&grid.blocks));
949            while grid.tree.last().is_some_and(|level| level.len() > 1) {
950                let next = union_boxes(grid.tree.last().unwrap());
951                grid.tree.push(next);
952            }
953        }
954        grid
955    }
956}
957
958impl SampleBlock {
959    /// A floor on `sample.sub(point).length_squared()` over the run's samples,
960    /// as COMPUTED, not only as real numbers: per axis the gap from `point` to
961    /// the box is the same subtraction against the box face, and IEEE rounding
962    /// is monotone, so `|fl(s - p)| >= fl(face - p)`; squaring and the same
963    /// left-to-right sum of non-negative terms keep the order (`Vec3::dot`
964    /// has no fused multiply-add). A NaN `point` reads gaps of 0 and every
965    /// distance is NaN, which no scan takes, so skipping changes nothing.
966    fn lower_bound(&self, point: Vec3) -> f64 {
967        let gap = |p: f64, low: f64, high: f64| {
968            if p < low {
969                low - p
970            } else if p > high {
971                p - high
972            } else {
973                0.0
974            }
975        };
976        let x = gap(point.x, self.low.x, self.high.x);
977        let y = gap(point.y, self.low.y, self.high.y);
978        let z = gap(point.z, self.low.z, self.high.z);
979        x * x + y * y + z * z
980    }
981}
982
983/// `BREP_PROJECTION_PRUNED_SCAN=0` scans every sample, as before 2026-11-10,
984/// for a same-binary A/B. Read once per process.
985fn pruned_scan() -> bool {
986    switch!("BREP_PROJECTION_PRUNED_SCAN", true)
987}
988
989/// Replace `best` with the grid's nearest sample when that is strictly nearer,
990/// the first such in scan order: the bits of the linear scan, which this was
991/// until 2026-11-10. A run is skipped only when its box's floor is not below
992/// the distance held, so none of its samples could have replaced it (the
993/// strict `<`), or lies above the bound read first ([`bound_first_scan`]),
994/// and the runs are visited in scan order. ABC 00027566's
995/// 166-span rational faces take the dense fallback on 71% of their pcurve
996/// probes (the first Newton not converged), each scanning 22.7k samples: 9.1 s
997/// of a face's 11.5 s of local answers.
998fn nearest_sample(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
999    if !grid.tree.is_empty() && scan_tree() && pruned_scan() && bound_first_scan() {
1000        nearest_sample_tree(grid, point, best);
1001        return;
1002    }
1003    nearest_sample_with(grid, point, best, pruned_scan(), bound_first_scan());
1004}
1005
1006/// `BREP_PROJECTION_SCAN_TREE=0` scans through the two levels of groups and
1007/// runs alone, as before 2026-11-11, for a same-binary A/B. Read once per
1008/// process.
1009///
1010/// With it on, a grid built with a tree ([`SampleGrid::with_tree`]: the dense
1011/// grid, when it has more than one group) is scanned through
1012/// [`SampleGrid::tree`]. ABC 00027566's dense fallback on its 166-span faces
1013/// passed 52 of 287 group boxes per call (a group is a strip across the
1014/// surface, and many strips' boxes hold a point on it) and then read 1680 run
1015/// floors to scan 0.65 runs, never improving the answer it held: 26 s of floors
1016/// at one pcurve site.
1017fn scan_tree() -> bool {
1018    switch!("BREP_PROJECTION_SCAN_TREE", true)
1019}
1020
1021/// `BREP_PROJECTION_SCAN_HINT=0` reads the bound from the descent alone, as
1022/// before 2026-11-11, for a same-binary A/B. Read once per process.
1023///
1024/// With it on, a bound-first scan also reads the run that held the answer of
1025/// the last scan of the same grid on this thread. Consecutive queries are
1026/// mostly neighbours (a pcurve's probes): ABC 00027566's busiest pcurve site
1027/// found its answer in the previous answer's run on 98.8% of seed scans, while
1028/// the descent's run held it on 40%; with the hint the bound is the answer on
1029/// 99.4% and the seed scans there fell from 43.6 s to 18.4 s.
1030fn scan_hint() -> bool {
1031    switch!("BREP_PROJECTION_SCAN_HINT", true)
1032}
1033
1034const HINT_SLOTS: usize = 8;
1035
1036thread_local! {
1037    /// Direct-mapped by grid address: (grid samples address, run of its last answer).
1038    static SCAN_HINTS: std::cell::Cell<[(usize, usize); HINT_SLOTS]> =
1039        const { std::cell::Cell::new([(0, usize::MAX); HINT_SLOTS]) };
1040}
1041
1042fn hint_slot(grid: &SampleGrid) -> (usize, usize) {
1043    let address = grid.samples.as_ptr() as usize;
1044    (address, (address >> 4) % HINT_SLOTS)
1045}
1046
1047/// The bound lowered by the hinted run's samples. The hint is only a run
1048/// index: it is range-checked and read from the grid in hand, so a stale one
1049/// (another grid at a reused address) costs time, never bits. It lowers the
1050/// BOUND alone, never the answer held: each value it can take is a real
1051/// sample distance, at least the grid's least distance `m`, which is all the
1052/// bound-first argument asks of it.
1053fn hinted_bound(grid: &SampleGrid, point: Vec3, mut bound: f64) -> f64 {
1054    if !scan_hint() {
1055        return bound;
1056    }
1057    let (address, slot) = hint_slot(grid);
1058    let (held, run) = SCAN_HINTS.with(|hints| hints.get()[slot]);
1059    if held != address || run >= grid.blocks.len() || !grid.blocks[run].prunable {
1060        return bound;
1061    }
1062    let start = run * SAMPLE_BLOCK;
1063    let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1064    for &(_, _, sample) in &grid.samples[start..end] {
1065        let distance_squared = sample.sub(point).length_squared();
1066        if distance_squared < bound {
1067            bound = distance_squared;
1068        }
1069    }
1070    bound
1071}
1072
1073/// Remember the run that last improved the answer of a scan of `grid`.
1074fn remember_hint(grid: &SampleGrid, run: Option<usize>) {
1075    if let Some(run) = run.filter(|_| scan_hint()) {
1076        let (address, slot) = hint_slot(grid);
1077        SCAN_HINTS.with(|hints| {
1078            let mut all = hints.get();
1079            all[slot] = (address, run);
1080            hints.set(all);
1081        });
1082    }
1083}
1084
1085/// [`nearest_sample_with`]'s bound-first scan over the box tree: the bound is
1086/// read from the run reached by descending from the root through the child of
1087/// lowest floor (a real sample distance, or the incoming one, so never below
1088/// the grid's least distance `m`), then the tree is visited depth first in
1089/// scan order, skipping a box whose floor is at or above the distance held or
1090/// strictly above the bound. A union box's floor is at most each of its
1091/// children's as computed (the box faces are theirs, and IEEE rounding is
1092/// monotone), so a box is skipped only when every run under it would have
1093/// been, and the runs that are read are read in scan order: the bits of the
1094/// linear scan, by the argument [`nearest_sample_with`] gives for its groups.
1095fn nearest_sample_tree(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1096    let top = grid.tree.len() - 1;
1097    let mut bound = best.distance_squared;
1098    // Descend: at each level the child of lowest floor among the prunable ones.
1099    let mut node = 0usize;
1100    let mut reached = true;
1101    for level in (0..=top).rev() {
1102        let children = |count: usize| node * TREE_FANOUT..((node + 1) * TREE_FANOUT).min(count);
1103        let below = if level == 0 { &grid.blocks } else { &grid.tree[level - 1] };
1104        match lowest_floor(below, children(below.len()), point) {
1105            Some(child) => node = child,
1106            None => {
1107                reached = false;
1108                break;
1109            }
1110        }
1111    }
1112    if reached {
1113        let start = node * SAMPLE_BLOCK;
1114        let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1115        for &(_, _, sample) in &grid.samples[start..end] {
1116            let distance_squared = sample.sub(point).length_squared();
1117            if distance_squared < bound {
1118                bound = distance_squared;
1119            }
1120        }
1121    }
1122    let bound = hinted_bound(grid, point, bound);
1123    let skip = |box_: &SampleBlock, held: f64| {
1124        if !box_.prunable {
1125            return false;
1126        }
1127        let floor = box_.lower_bound(point);
1128        floor >= held || floor > bound
1129    };
1130    let mut answer_run = None;
1131    // Depth first in scan order: (level, index), level 0 of the stack meaning a run.
1132    let mut stack: Vec<(usize, usize)> = Vec::with_capacity(TREE_FANOUT * (top + 2));
1133    stack.push((top + 1, 0));
1134    while let Some((level, index)) = stack.pop() {
1135        if level == 0 {
1136            if skip(&grid.blocks[index], best.distance_squared) {
1137                continue;
1138            }
1139            let start = index * SAMPLE_BLOCK;
1140            let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1141            let held = best.distance_squared;
1142            scan_run(&grid.samples[start..end], point, best);
1143            if best.distance_squared < held {
1144                answer_run = Some(index);
1145            }
1146            continue;
1147        }
1148        if skip(&grid.tree[level - 1][index], best.distance_squared) {
1149            continue;
1150        }
1151        let count = if level == 1 { grid.blocks.len() } else { grid.tree[level - 2].len() };
1152        let children = index * TREE_FANOUT..((index + 1) * TREE_FANOUT).min(count);
1153        // Pushed last-first so they pop in scan order.
1154        for child in children.rev() {
1155            stack.push((level - 1, child));
1156        }
1157    }
1158    remember_hint(grid, answer_run);
1159}
1160
1161/// `BREP_PROJECTION_BOUND_FIRST=0` prunes against the distance held alone, as
1162/// on 2026-11-10 before this pass, for a same-binary A/B. Read once per
1163/// process.
1164///
1165/// With it on, the runs are boxed again in groups of [`GROUP_BLOCKS`]. The scan
1166/// first reads the run of lowest floor inside the group of lowest floor and
1167/// takes the nearest of its samples as a BOUND, then visits the groups and
1168/// their runs in scan order, skipping any whose floor is at or above the
1169/// distance held or strictly above that bound. The runs alone started the seed
1170/// scan from no answer (its incoming distance is infinite), so every run ahead
1171/// of the nearest sample was read before the held distance fell, and every
1172/// scan computed one floor per run: on ABC 00027566 the seed
1173/// scans averaged 63k samples (361 s over 5M calls) and the dense ones 180k
1174/// (167 s over 3.5M), while a bound over the runs alone cut the first to 190 s
1175/// but doubled the second to 311 s with its extra pass of floors.
1176fn bound_first_scan() -> bool {
1177    switch!("BREP_PROJECTION_BOUND_FIRST", true)
1178}
1179
1180/// The scan behind [`nearest_sample`]. With `bound_first`, the bound is the
1181/// smaller of the incoming distance and one real sample distance, so it is
1182/// never below the grid's least distance `m`. The first sample at `m` lies in
1183/// a run whose floor is at most `m`, hence not above the bound and not at or
1184/// above the distance held when the scan reaches it (every sample before it is
1185/// strictly farther than `m`): that run is read and the sample taken, as the
1186/// linear scan takes it, and nothing after it is strictly nearer. A run whose
1187/// floor is above the bound holds no sample at `m`. The bound pass reads only
1188/// prunable runs, and updates on a strict `<`, so a NaN never enters it.
1189fn nearest_sample_with(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult, pruned: bool, bound_first: bool) {
1190    if !(pruned && bound_first) {
1191        for (block, chunk) in grid.blocks.iter().zip(grid.samples.chunks(SAMPLE_BLOCK)) {
1192            if pruned && block.prunable && block.lower_bound(point) >= best.distance_squared {
1193                continue;
1194            }
1195            scan_run(chunk, point, best);
1196        }
1197        return;
1198    }
1199    // The bound: one real sample distance (or the incoming one), from the run
1200    // of lowest floor inside the group of lowest floor.
1201    let mut bound = best.distance_squared;
1202    let lowest_group = lowest_floor(&grid.groups, 0..grid.groups.len(), point);
1203    if let Some(group) = lowest_group {
1204        let runs = group * GROUP_BLOCKS..((group + 1) * GROUP_BLOCKS).min(grid.blocks.len());
1205        if let Some(run) = lowest_floor(&grid.blocks, runs, point) {
1206            let start = run * SAMPLE_BLOCK;
1207            let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1208            for &(_, _, sample) in &grid.samples[start..end] {
1209                let distance_squared = sample.sub(point).length_squared();
1210                if distance_squared < bound {
1211                    bound = distance_squared;
1212                }
1213            }
1214        }
1215    }
1216    let bound = hinted_bound(grid, point, bound);
1217    let skip = |box_: &SampleBlock, held: f64| {
1218        if !box_.prunable {
1219            return false;
1220        }
1221        let floor = box_.lower_bound(point);
1222        floor >= held || floor > bound
1223    };
1224    let mut answer_run = None;
1225    for (group_index, group) in grid.groups.iter().enumerate() {
1226        if skip(group, best.distance_squared) {
1227            continue;
1228        }
1229        let first = group_index * GROUP_BLOCKS;
1230        let last = (first + GROUP_BLOCKS).min(grid.blocks.len());
1231        for run in first..last {
1232            if skip(&grid.blocks[run], best.distance_squared) {
1233                continue;
1234            }
1235            let start = run * SAMPLE_BLOCK;
1236            let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1237            let held = best.distance_squared;
1238            scan_run(&grid.samples[start..end], point, best);
1239            if best.distance_squared < held {
1240                answer_run = Some(run);
1241            }
1242        }
1243    }
1244    remember_hint(grid, answer_run);
1245}
1246
1247/// The linear scan of one run: strict `<`, so the first of equal samples
1248/// stands.
1249fn scan_run(run: &[(f64, f64, Vec3)], point: Vec3, best: &mut NewtonResult) {
1250    for &(u, v, sample) in run {
1251        let distance_squared = sample.sub(point).length_squared();
1252        if distance_squared < best.distance_squared {
1253            best.u = u;
1254            best.v = v;
1255            best.distance_squared = distance_squared;
1256        }
1257    }
1258}
1259
1260/// The index, within `range`, of the prunable box of least floor (the first
1261/// on a tie), or None when none is prunable.
1262fn lowest_floor(boxes: &[SampleBlock], range: std::ops::Range<usize>, point: Vec3) -> Option<usize> {
1263    let mut lowest: Option<(usize, f64)> = None;
1264    for index in range {
1265        let box_ = &boxes[index];
1266        if !box_.prunable {
1267            continue;
1268        }
1269        let floor = box_.lower_bound(point);
1270        if lowest.is_none_or(|(_, held)| floor < held) {
1271            lowest = Some((index, floor));
1272        }
1273    }
1274    lowest.map(|(index, _)| index)
1275}
1276
1277// Boundary-ring cache geometry: 4 sides × 22 exponents × 33 indices. The scan
1278// positions depend only on the surface domain and these fixed integers, so the
1279// evaluated points are a pure function of the surface and cacheable.
1280const RING_EXPONENTS: usize = 22;
1281const RING_INDICES: usize = 33; // index 0..=32
1282
1283#[inline]
1284fn ring_slot(side: usize, exponent_index: usize, index: usize) -> usize {
1285    (side * RING_EXPONENTS + exponent_index) * RING_INDICES + index
1286}
1287
1288/// The boundary-ring sample points for the degenerate projection fallback,
1289/// flattened by `ring_slot(side, exponent-1, index)`. Sides: 0 = v-low
1290/// (`v = v0 + (v1-v0)·offset`), 1 = v-high (`v1 - (v1-v0)·offset`), 2 = u-low
1291/// (`u0 + (u1-u0)·offset`), 3 = u-high (`u1 - (u1-u0)·offset`), where
1292/// `offset = 1/2^exponent`. A pure function of the surface, cached on it — the
1293/// fallback's boundary ring re-evaluated these on every one of ~1.7M calls.
1294fn projection_ring_grid(surface: &NurbsSurface) -> Result<&[Vec3], String> {
1295    if let Some(grid) = surface.projection_ring_grid.get() {
1296        return Ok(grid);
1297    }
1298    let [u0, u1] = surface.domain_u()?;
1299    let [v0, v1] = surface.domain_v()?;
1300    let mut grid = vec![Vec3::default(); 4 * RING_EXPONENTS * RING_INDICES];
1301    for exponent in 1..=RING_EXPONENTS as i32 {
1302        let offset = 1.0 / 2f64.powi(exponent);
1303        let e = exponent as usize - 1;
1304        let v_lo = v0 + (v1 - v0) * offset;
1305        let v_hi = v1 - (v1 - v0) * offset;
1306        let u_lo = u0 + (u1 - u0) * offset;
1307        let u_hi = u1 - (u1 - u0) * offset;
1308        for index in 0..=32 {
1309            let u = u0 + (u1 - u0) * index as f64 / 32.0;
1310            grid[ring_slot(0, e, index as usize)] = surface.evaluate(u, v_lo)?;
1311            grid[ring_slot(1, e, index as usize)] = surface.evaluate(u, v_hi)?;
1312        }
1313        for index in 0..=32 {
1314            let v = v0 + (v1 - v0) * index as f64 / 32.0;
1315            grid[ring_slot(2, e, index as usize)] = surface.evaluate(u_lo, v)?;
1316            grid[ring_slot(3, e, index as usize)] = surface.evaluate(u_hi, v)?;
1317        }
1318    }
1319    Ok(surface.projection_ring_grid.get_or_init(|| grid))
1320}
1321
1322/// The LOCAL answer: Newton from the seed grid's single nearest sample (or the
1323/// linear-revolution foot), with the degenerate-parameterization fallbacks.
1324///
1325/// This is the whole of what the general projector returned before
1326/// 2026-09-14, and it is a local minimum, not the minimum: on a general patch
1327/// nearly closed in one direction the nearest sample can sit on the far end,
1328/// and Newton converges there (abc_00000026's thread flanks, 2.16e-2 .. 4.1e-2
1329/// against a true 1e-13). [`project_point_to_surface_general`] runs it first
1330/// and keeps its answer wherever no other basin beats it.
1331fn nearest_seed_answer(
1332    surface: &NurbsSurface,
1333    point: Vec3,
1334    [u0, u1, v0, v1]: [f64; 4],
1335    closed_u: bool,
1336    closed_v: bool,
1337) -> Result<NewtonResult, String> {
1338    let mut best = NewtonResult {
1339        u: u0,
1340        v: v0,
1341        distance_squared: f64::INFINITY,
1342        converged: false,
1343    };
1344    nearest_sample(projection_seed_grid(surface)?, point, &mut best);
1345    if let Some(revolution) = project_linear_revolution(surface, point)? {
1346        if revolution.distance * revolution.distance < best.distance_squared {
1347            best.u = revolution.u;
1348            best.v = revolution.v;
1349            best.distance_squared = revolution.distance * revolution.distance;
1350        }
1351    }
1352    let first_newton = surface_newton(
1353        surface,
1354        point,
1355        best.u,
1356        best.v,
1357        [u0, u1, v0, v1],
1358        closed_u,
1359        closed_v,
1360    )?;
1361    if first_newton.distance_squared < best.distance_squared {
1362        best = first_newton;
1363    }
1364    let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1365    let degenerate = su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length());
1366    if degenerate || !first_newton.converged {
1367        let mut grid = best;
1368        nearest_sample(projection_dense_grid(surface)?, point, &mut grid);
1369        if grid.distance_squared < best.distance_squared {
1370            best = grid;
1371        }
1372        let polished = surface_newton(
1373            surface,
1374            point,
1375            grid.u,
1376            grid.v,
1377            [u0, u1, v0, v1],
1378            closed_u,
1379            closed_v,
1380        )?;
1381        if polished.distance_squared < best.distance_squared {
1382            best = polished;
1383        }
1384
1385        let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1386        if su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length()) {
1387            let ring_grid = projection_ring_grid(surface)?;
1388            let mut ring = best;
1389            // Read the pre-evaluated ring points at the exact same parameter
1390            // positions the live scans used (side/exponent/index → `ring_slot`),
1391            // preserving scan order and argmin tie-breaking for bit-identity.
1392            let scan = |side: usize,
1393                        exponent_index: usize,
1394                        along_u: bool,
1395                        fixed: f64,
1396                        candidate: &mut NewtonResult| {
1397                for index in 0..=32 {
1398                    let moving = if along_u {
1399                        u0 + (u1 - u0) * index as f64 / 32.0
1400                    } else {
1401                        v0 + (v1 - v0) * index as f64 / 32.0
1402                    };
1403                    let (u, v) = if along_u {
1404                        (moving, fixed)
1405                    } else {
1406                        (fixed, moving)
1407                    };
1408                    let distance_squared = ring_grid
1409                        [ring_slot(side, exponent_index, index as usize)]
1410                    .sub(point)
1411                    .length_squared();
1412                    if distance_squared < candidate.distance_squared {
1413                        candidate.u = u;
1414                        candidate.v = v;
1415                        candidate.distance_squared = distance_squared;
1416                    }
1417                }
1418            };
1419            for exponent in 1..=22 {
1420                let offset = 1.0 / 2f64.powi(exponent);
1421                let e = exponent as usize - 1;
1422                if (best.v - v0).abs() <= (v1 - v0) * 0.02 {
1423                    scan(0, e, true, v0 + (v1 - v0) * offset, &mut ring);
1424                }
1425                if (best.v - v1).abs() <= (v1 - v0) * 0.02 {
1426                    scan(1, e, true, v1 - (v1 - v0) * offset, &mut ring);
1427                }
1428                if (best.u - u0).abs() <= (u1 - u0) * 0.02 {
1429                    scan(2, e, false, u0 + (u1 - u0) * offset, &mut ring);
1430                }
1431                if (best.u - u1).abs() <= (u1 - u0) * 0.02 {
1432                    scan(3, e, false, u1 - (u1 - u0) * offset, &mut ring);
1433                }
1434            }
1435            if ring.distance_squared < best.distance_squared {
1436                best = ring;
1437            }
1438            let polished = surface_newton(
1439                surface,
1440                point,
1441                ring.u,
1442                ring.v,
1443                [u0, u1, v0, v1],
1444                closed_u,
1445                closed_v,
1446            )?;
1447            if polished.distance_squared < best.distance_squared {
1448                best = polished;
1449            }
1450        }
1451    }
1452    Ok(best)
1453}
1454
1455/// Escape hatch for A/B measurement: `BREP_PROJECTION_GLOBAL=0` returns the
1456/// local answer alone ([`nearest_seed_answer`], the pre-2026-09-14 projector),
1457/// so a population run can be repeated with and without the global stage from
1458/// one binary. Read once.
1459fn global_stage_enabled() -> bool {
1460    switch!("BREP_PROJECTION_GLOBAL", true)
1461}
1462
1463/// `BREP_PROJECTION_GLOBAL_SITES=<a,b,…>`: the global stage's answer is kept
1464/// only for call sites whose `file:line` contains one of the comma-separated
1465/// substrings, and the local answer is returned everywhere else — so a result
1466/// that moves can be attributed to the call site that moved it.
1467/// `BREP_PROJECTION_GLOBAL_EXCEPT=<a,b,…>` is the complement: every site but
1468/// those. Unset: every site. Read once.
1469/// Whether a `BREP_PROJECTION_GLOBAL_SITES`/`_EXCEPT` filter is set, i.e.
1470/// whether [`project_point_to_surface`]'s answer can depend on its call site.
1471pub fn global_site_filter_active() -> bool {
1472    // Read once per process, like the site lists `global_answer_admitted`
1473    // reads: the common reader asks this for every probe (two `getenv` calls,
1474    // ~3.7% of the elephant's B12 prefix on the production sampler,
1475    // 2026-11-02), and nothing sets these variables after start-up.
1476    static ACTIVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1477    *ACTIVE.get_or_init(|| {
1478        std::env::var_os("BREP_PROJECTION_GLOBAL_SITES").is_some() || std::env::var_os("BREP_PROJECTION_GLOBAL_EXCEPT").is_some()
1479    })
1480}
1481
1482fn global_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
1483    fn list(name: &str) -> Option<Vec<String>> {
1484        std::env::var(name)
1485            .ok()
1486            .map(|value| value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect())
1487    }
1488    static SITES: std::sync::OnceLock<(Option<Vec<String>>, Option<Vec<String>>)> =
1489        std::sync::OnceLock::new();
1490    let (only, except) = SITES.get_or_init(|| {
1491        (list("BREP_PROJECTION_GLOBAL_SITES"), list("BREP_PROJECTION_GLOBAL_EXCEPT"))
1492    });
1493    if only.is_none() && except.is_none() {
1494        return true;
1495    }
1496    let location = format!("{}:{}", caller.file(), caller.line());
1497    let named = |sites: &Vec<String>| sites.iter().any(|site| location.contains(site.as_str()));
1498    only.as_ref().is_none_or(named) && !except.as_ref().is_some_and(named)
1499}
1500
1501/// `BREP_PROJECTION_AUDIT=<dir>`: every query on which the global stage
1502/// replaces the local answer appends one tab-separated line to
1503/// `<dir>/projection-audit-<pid>.tsv` — the call site, the local and the
1504/// global distance, both feet's `(u, v)` and the surface's shape. Per process,
1505/// because the case gate forks a child per case and loses its stderr.
1506fn audit_record(caller: &std::panic::Location<'_>, surface: &NurbsSurface, local: &NewtonResult, global: &NewtonResult) {
1507    use std::io::Write;
1508    static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1509        std::sync::OnceLock::new();
1510    let sink = SINK.get_or_init(|| {
1511        let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1512        let path = std::path::Path::new(&directory)
1513            .join(format!("projection-audit-{}.tsv", std::process::id()));
1514        std::fs::OpenOptions::new()
1515            .create(true)
1516            .append(true)
1517            .open(path)
1518            .ok()
1519            .map(std::sync::Mutex::new)
1520    });
1521    if let Some(file) = sink {
1522        if let Ok(mut file) = file.lock() {
1523            let _ = writeln!(
1524                file,
1525                "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{}x{} cp {}x{}",
1526                caller.file(),
1527                caller.line(),
1528                local.distance_squared.sqrt(),
1529                global.distance_squared.sqrt(),
1530                local.u,
1531                local.v,
1532                global.u,
1533                global.v,
1534                surface.degree_u,
1535                surface.degree_v,
1536                surface.control_points.len(),
1537                surface.control_points.first().map(Vec::len).unwrap_or(0),
1538            );
1539        }
1540    }
1541}
1542
1543/// The point of a general surface nearest `point`: the least local minimum of
1544/// the distance over the surface's whole domain.
1545///
1546/// **What it does.** First the local answer ([`nearest_seed_answer`]: Newton
1547/// from the nearest seed-grid sample, with its degenerate fallbacks — the whole
1548/// projector before 2026-09-14). Then the global stage ([`global_minimum`]):
1549/// the domain is cut into the cells of the projection lattice (every knot span
1550/// sampled `max(3, degree + 1)` times in an open direction and
1551/// `max(8, 4 × degree)` times in a closed one — the seed grid's own density),
1552/// and each cell is enclosed in a box built from the control points of the
1553/// surface REFINED to that cell. A NURBS patch with positive weights lies in
1554/// the convex hull of the control points that support it, so the distance from
1555/// the query to a cell's box is a rigorous LOWER bound on the distance to every
1556/// surface point of the cell. Every cell whose bound is below the best answer
1557/// so far is a candidate basin, and is refined by a descent confined to the
1558/// cell ([`confined_descent`]: Newton where the Hessian is positive definite,
1559/// the metric-scaled gradient where it is not, halved until the distance does
1560/// not rise, so it can end at a minimum but not at a saddle or a maximum),
1561/// seeded at the cell's nearest lattice node and continued over the domain
1562/// when the cell's least point is on its edge. The least answer wins. A closed
1563/// direction's seam is not special: the lattice spans the whole period, the
1564/// cells on either side of the seam are ordinary cells, and the continuation
1565/// wraps.
1566///
1567/// **What is guaranteed.**
1568/// * The answer is a point ON the surface, so its distance never under-reads.
1569/// * Every cell that could hold a point nearer than the answer by more than the
1570///   resolution has been descended in, unless it already held a verified
1571///   minimum: a cell left out was excluded by its hull bound, which cannot
1572///   over-read. [`GlobalStats::hull_lower_bound`] is that certificate: the
1573///   true distance lies in `[hull_lower_bound, answer]`, always.
1574/// * **The one step not certified in general: one basin in the cell that holds
1575///   the least minimum.** A descent finds the basin of its seed. A second basin
1576///   in any OTHER cell costs nothing — that cell's better basin is still no
1577///   nearer than the least minimum — but a second local minimum in the cell
1578///   holding the least minimum can catch the descent seeded at that cell's
1579///   nearest lattice node, and the least minimum is missed by at most
1580///   `answer − hull_lower_bound`. That takes a query past the focal distance of
1581///   part of the cell (farther than its radius of normal curvature on the
1582///   query's side, where the distance's Hessian `G − d·II` stops being positive
1583///   definite) or a cell whose image turns back toward the query. A descent that
1584///   runs out of iterations without a verified minimum fails the same way, with
1585///   the same bound. Seeding every corner of every candidate cell was measured
1586///   and changed no answer on the bench.
1587/// * **Certified on the analytic carriers** — the sphere, torus, cylinder and
1588///   cone, each a revolution of a circle or a line, and the plane. A lattice cell
1589///   there is an (azimuth × generatrix) rectangle under half a turn wide. In the
1590///   cell holding the least minimum the azimuthal derivative of the squared
1591///   distance, `2 ρ(v) ρ_P sin(λ − λ_P)`, vanishes only on the query's own
1592///   meridian, and moving toward that meridian lowers the distance from every
1593///   other point of the cell, so each local minimum over the cell is a local
1594///   minimum of the planar distance from the query's meridian image to the
1595///   generatrix over the cell's `v` range — exactly one on a circle arc under
1596///   half a turn or on a segment. At the focal sets (the axis, the sphere's
1597///   centre, the tube's centre circle) the minimum is a continuum of equal
1598///   distances and every foot is right. A general profile of revolution and a
1599///   general patch are not certified.
1600/// * Where the local answer is already the least minimum, it is returned
1601///   unchanged, bit for bit: the global stage replaces it only with a point
1602///   nearer by more than the resolution.
1603///
1604/// **The two numbers it reads.** The *on-surface floor* is `LINEAR_TOLERANCE`,
1605/// INHERITED unchanged: it is the local Newton's own stopping residual, and a
1606/// local answer within it of the query is on the surface and nothing is
1607/// searched. The *resolution* is the one new number, and it is the surface's
1608/// own: `(degree_u + 1)(degree_v + 1) · ε · scale`, `scale` the largest
1609/// control-point coordinate magnitude — the rounding of one evaluation, which
1610/// sums that many terms of that size. Every box is grown by it, and no
1611/// improvement finer than it is taken.
1612///
1613/// **What it costs.** A query settled by the floor costs what the local answer
1614/// always cost. Any other query builds the cell enclosure once per surface (one
1615/// knot refinement of the net to the lattice, cached on the surface beside the
1616/// seed grid), walks a bounding-sphere tree over the cells, and runs one
1617/// descent per candidate cell the hull bound does not exclude.
1618#[track_caller]
1619pub fn project_point_to_surface_general(
1620    surface: &NurbsSurface,
1621    point: Vec3,
1622) -> Result<SurfaceProjection, String> {
1623    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_GENERAL, surface);
1624    let [u0, u1] = surface.domain_u()?;
1625    let [v0, v1] = surface.domain_v()?;
1626    let (closed_u, closed_v) = surface.closed_directions()?;
1627    let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1628    let mut best = local;
1629    if global_stage_enabled() {
1630        global_minimum(
1631            surface,
1632            point,
1633            [u0, u1, v0, v1],
1634            (closed_u, closed_v),
1635            &mut best,
1636            &mut GlobalStats::default(),
1637        )?;
1638        if best.u != local.u || best.v != local.v {
1639            let caller = std::panic::Location::caller();
1640            if global_answer_admitted(caller) {
1641                audit_record(caller, surface, &local, &best);
1642            } else {
1643                best = local;
1644            }
1645        }
1646    }
1647    let projected = surface.evaluate(best.u, best.v)?;
1648    Ok(SurfaceProjection {
1649        u: best.u,
1650        v: best.v,
1651        point: projected,
1652        distance: projected.sub(point).length(),
1653    })
1654}
1655
1656/// The single-seed inversion by itself: the closed form on an analytic
1657/// carrier, otherwise [`nearest_seed_answer`] — Newton from the seed grid's
1658/// nearest sample, WITHOUT the global stage. Its distance is an upper bound and
1659/// its foot a local minimum. It is not a nearest-point query: it exists for a
1660/// caller that asks a question ABOUT that inversion, and there is one —
1661/// `joint_branch_pcurves` (`io/step_import/builder/rims.rs`) offers a loop the
1662/// joint branch only when this inversion alternates between branches along it,
1663/// which it does on a carrier that comes back within one seed-grid spacing of
1664/// itself (`abc_00000026`'s nearly closed thread flanks).
1665pub fn project_point_to_surface_from_nearest_seed(
1666    surface: &NurbsSurface,
1667    point: Vec3,
1668) -> Result<SurfaceProjection, String> {
1669    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_NEAREST_SEED, surface);
1670    if let Some(analytic) = surface.analytic() {
1671        if let Some(projection) = analytic.project(surface, point) {
1672            return Ok(projection);
1673        }
1674    }
1675    if let Some(ellipsoid) = surface.affine_sphere() {
1676        if let Some(projection) = ellipsoid.project(surface, point) {
1677            return Ok(projection);
1678        }
1679    }
1680    let [u0, u1] = surface.domain_u()?;
1681    let [v0, v1] = surface.domain_v()?;
1682    let (closed_u, closed_v) = surface.closed_directions()?;
1683    let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1684    let projected = surface.evaluate(local.u, local.v)?;
1685    Ok(SurfaceProjection {
1686        u: local.u,
1687        v: local.v,
1688        point: projected,
1689        distance: projected.sub(point).length(),
1690    })
1691}
1692
1693/// Both answers for one query, and what the global stage did — the bench's
1694/// seam (`examples/projector_bench.rs`). Not for kernel callers.
1695#[doc(hidden)]
1696pub fn project_point_to_surface_general_lanes(
1697    surface: &NurbsSurface,
1698    point: Vec3,
1699    run_global: bool,
1700) -> Result<(SurfaceProjection, GlobalStats), String> {
1701    let [u0, u1] = surface.domain_u()?;
1702    let [v0, v1] = surface.domain_v()?;
1703    let (closed_u, closed_v) = surface.closed_directions()?;
1704    let mut best = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1705    let mut stats = GlobalStats::default();
1706    if run_global {
1707        global_minimum(surface, point, [u0, u1, v0, v1], (closed_u, closed_v), &mut best, &mut stats)?;
1708    }
1709    let projected = surface.evaluate(best.u, best.v)?;
1710    Ok((
1711        SurfaceProjection {
1712            u: best.u,
1713            v: best.v,
1714            point: projected,
1715            distance: projected.sub(point).length(),
1716        },
1717        stats,
1718    ))
1719}
1720
1721/// How many basins the cells of one query hold — the bench's measure of the
1722/// global stage's one uncertified step (see [`project_point_to_surface_general`]).
1723#[doc(hidden)]
1724#[derive(Clone, Debug, Default)]
1725pub struct BasinCensus {
1726    /// Cells whose hull bound is below the answer's distance: every cell the
1727    /// global stage could have descended in.
1728    pub cells: usize,
1729    /// Descents run: one from each corner of those cells and one from the middle.
1730    pub descents: usize,
1731    /// Descents that stopped without a verified minimum.
1732    pub unconverged: usize,
1733    /// Cells where two verified minima differ in distance by more than `bar`.
1734    /// Distances within the on-surface floor count as equal: the descent stops
1735    /// there, so two feet under it are one foot polished to different depths.
1736    pub cells_with_two_basins: usize,
1737    /// Of those, cells whose rectangle holds the least foot any descent found:
1738    /// the only cells where a second basin can cost the answer anything.
1739    pub foot_cells_with_two_basins: usize,
1740    /// The least distance any descent reached, and where.
1741    pub least: f64,
1742    pub least_uv: (f64, f64),
1743    /// Every descent in a two-basin cell that holds the least foot: the cell,
1744    /// its rectangle, the seed, where it stopped, its distance, and whether that
1745    /// is a verified minimum.
1746    pub foot_cell_descents: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)>,
1747}
1748
1749/// Descend in every cell whose hull bound is below `answer_distance` from each
1750/// of its corners and its middle, and count the cells whose verified minima
1751/// disagree by more than `bar`. For the bench only: it costs five descents per
1752/// cell, which the projector itself was measured not to need.
1753#[doc(hidden)]
1754pub fn project_point_to_surface_basin_census(
1755    surface: &NurbsSurface,
1756    point: Vec3,
1757    answer_distance: f64,
1758    bar: f64,
1759) -> Result<BasinCensus, String> {
1760    let mut census = BasinCensus {
1761        least: f64::INFINITY,
1762        ..BasinCensus::default()
1763    };
1764    let Some(cells) = projection_cells(surface)? else {
1765        return Ok(census);
1766    };
1767    let columns = cells.vs.len() - 1;
1768    let mut spreads: Vec<(usize, f64)> = Vec::new();
1769    let mut runs: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)> = Vec::new();
1770    for (cell, cell_box) in cells.boxes.iter().enumerate() {
1771        if cell_box.lower_bound(point) >= answer_distance {
1772            continue;
1773        }
1774        census.cells += 1;
1775        let (row, column) = (cell / columns, cell % columns);
1776        let rectangle = [cells.us[row], cells.us[row + 1], cells.vs[column], cells.vs[column + 1]];
1777        let middle = ((rectangle[0] + rectangle[1]) * 0.5, (rectangle[2] + rectangle[3]) * 0.5);
1778        let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
1779        for seed in [
1780            (rectangle[0], rectangle[2]),
1781            (rectangle[1], rectangle[2]),
1782            (rectangle[0], rectangle[3]),
1783            (rectangle[1], rectangle[3]),
1784            middle,
1785        ] {
1786            census.descents += 1;
1787            let (found, _) = confined_descent(surface, point, seed, rectangle, (false, false))?;
1788            let distance = found.distance_squared.sqrt();
1789            runs.push((cell, rectangle, seed, (found.u, found.v), distance, found.converged));
1790            if distance < census.least {
1791                census.least = distance;
1792                census.least_uv = (found.u, found.v);
1793            }
1794            if !found.converged {
1795                census.unconverged += 1;
1796                continue;
1797            }
1798            low = low.min(distance.max(LINEAR_TOLERANCE));
1799            high = high.max(distance.max(LINEAR_TOLERANCE));
1800        }
1801        if high - low > bar {
1802            spreads.push((cell, high - low));
1803        }
1804    }
1805    census.cells_with_two_basins = spreads.len();
1806    let (u, v) = census.least_uv;
1807    let foot_cells: Vec<usize> = spreads
1808        .iter()
1809        .map(|&(cell, _)| cell)
1810        .filter(|&cell| {
1811            let (row, column) = (cell / columns, cell % columns);
1812            cells.us[row] <= u && u <= cells.us[row + 1] && cells.vs[column] <= v && v <= cells.vs[column + 1]
1813        })
1814        .collect();
1815    census.foot_cells_with_two_basins = foot_cells.len();
1816    census.foot_cell_descents = runs.into_iter().filter(|run| foot_cells.contains(&run.0)).collect();
1817    Ok(census)
1818}
1819
1820/// What the global stage did on one query.
1821#[doc(hidden)]
1822#[derive(Clone, Copy, Debug, Default)]
1823pub struct GlobalStats {
1824    /// The local answer was within the on-surface floor; nothing searched.
1825    pub settled_by_floor: bool,
1826    /// Cells whose hull bound admitted them.
1827    pub candidates: usize,
1828    /// Confined Newtons run (candidates not already holding a converged foot).
1829    pub refinements: usize,
1830    /// Continuations across the domain from a cell edge.
1831    pub continuations: usize,
1832    /// The global stage replaced the local answer.
1833    pub replaced: bool,
1834    /// The least hull bound over every cell — the true distance is never
1835    /// below it (0 when the floor settled the query).
1836    pub hull_lower_bound: f64,
1837}
1838
1839/// One lattice cell's enclosure: an oriented box around the control points
1840/// that support the cell, in an orthonormal frame fitted to the cell.
1841#[derive(Clone, Debug)]
1842struct CellBox {
1843    axes: [Vec3; 3],
1844    low: [f64; 3],
1845    high: [f64; 3],
1846}
1847
1848impl CellBox {
1849    /// Distance from `point` to the box: a lower bound on the distance to
1850    /// every surface point of the cell.
1851    fn lower_bound(&self, point: Vec3) -> f64 {
1852        let mut squared = 0.0;
1853        for axis in 0..3 {
1854            let coordinate = point.dot(self.axes[axis]);
1855            let excess = (self.low[axis] - coordinate).max(coordinate - self.high[axis]).max(0.0);
1856            squared += excess * excess;
1857        }
1858        squared.sqrt()
1859    }
1860}
1861
1862/// A node of the bounding-sphere tree over the cells. A leaf names its cell;
1863/// an internal node its two children.
1864#[derive(Clone, Copy, Debug)]
1865struct CellTreeNode {
1866    centre: Vec3,
1867    radius: f64,
1868    children: Option<(u32, u32)>,
1869    cell: u32,
1870}
1871
1872/// The cached enclosure of every projection lattice cell (see
1873/// [`project_point_to_surface_general`]).
1874#[derive(Clone, Debug)]
1875pub struct ProjectionCells {
1876    us: Vec<f64>,
1877    vs: Vec<f64>,
1878    /// `us.len() × vs.len()` lattice points, row-major in u.
1879    nodes: Vec<Vec3>,
1880    /// `(us.len() - 1) × (vs.len() - 1)` cells, row-major in u.
1881    boxes: Vec<CellBox>,
1882    /// The tree's root is the LAST node.
1883    tree: Vec<CellTreeNode>,
1884    /// One box per tree node: a leaf's is its cell's box, an internal node's
1885    /// holds both children's boxes grown by `node_margin` on every side (see
1886    /// [`hull_candidates`]). Empty when the surface has no usable scale.
1887    node_boxes: Vec<CellBox>,
1888    /// The growth of each internal node's box over its children's.
1889    node_margin: f64,
1890    /// The largest control-point coordinate magnitude.
1891    scale: f64,
1892    resolution: f64,
1893}
1894
1895/// The projection lattice's parameters along one direction: every knot span
1896/// cut into `samples` equal pieces, the seed grid's density, shared span ends
1897/// listed once.
1898fn lattice_parameters(knots: &[f64], degree: usize, closed: bool) -> Vec<f64> {
1899    let [start, end] = crate::curve::knot_domain(knots, degree);
1900    let samples = if closed {
1901        8usize.max(degree * 4)
1902    } else {
1903        3usize.max(degree + 1)
1904    };
1905    let mut breaks = vec![start];
1906    breaks.extend(interior_knots(knots, degree));
1907    breaks.push(end);
1908    let mut parameters = Vec::with_capacity((breaks.len() - 1) * samples + 1);
1909    for pair in breaks.windows(2) {
1910        for index in 0..samples {
1911            parameters.push(pair[0] + (pair[1] - pair[0]) * index as f64 / samples as f64);
1912        }
1913    }
1914    parameters.push(end);
1915    parameters
1916}
1917
1918/// Raise every lattice parameter to full multiplicity in the knot vector, so
1919/// each lattice cell is one Bézier piece of the refined net.
1920///
1921/// `net[i]` is the i-th control point along the refined direction, held as a
1922/// row across the other direction, and every row takes the same combination.
1923/// Knot refinement in one pass (Piegl & Tiller, *The NURBS Book*, A5.4), in
1924/// homogeneous coordinates, so a rational net refines exactly and the cost is
1925/// linear in the refined net's size.
1926fn refine_to_lattice(net: &mut Vec<Vec<Vec4>>, knots: &mut Vec<f64>, degree: usize, parameters: &[f64]) {
1927    let p = degree;
1928    let n = net.len() - 1;
1929    let mut inserted = Vec::new();
1930    for &parameter in parameters {
1931        let multiplicity = knots.iter().filter(|&&knot| knot == parameter).count();
1932        for _ in multiplicity..p {
1933            inserted.push(parameter);
1934        }
1935    }
1936    if inserted.is_empty() || p == 0 {
1937        return;
1938    }
1939    inserted.sort_by(f64::total_cmp);
1940    let find_span = |parameter: f64| -> usize {
1941        if parameter >= knots[n + 1] {
1942            return n;
1943        }
1944        (knots.partition_point(|&knot| knot <= parameter) - 1).clamp(p, n)
1945    };
1946    let r = inserted.len() - 1;
1947    let m = n + p + 1;
1948    let a = find_span(inserted[0]);
1949    let b = find_span(inserted[r]) + 1;
1950    let columns = net[0].len();
1951    let blank = vec![
1952        Vec4 {
1953            x: 0.0,
1954            y: 0.0,
1955            z: 0.0,
1956            w: 0.0,
1957        };
1958        columns
1959    ];
1960    let mut refined = vec![blank; n + r + 2];
1961    let mut refined_knots = vec![0.0; m + r + 2];
1962    for j in 0..=a - p {
1963        refined[j] = net[j].clone();
1964    }
1965    for j in b - 1..=n {
1966        refined[j + r + 1] = net[j].clone();
1967    }
1968    refined_knots[..=a].copy_from_slice(&knots[..=a]);
1969    for j in b + p..=m {
1970        refined_knots[j + r + 1] = knots[j];
1971    }
1972    let mut i = b + p - 1;
1973    let mut k = b + p + r;
1974    for j in (0..=r).rev() {
1975        while inserted[j] <= knots[i] && i > a {
1976            refined[k - p - 1] = net[i - p - 1].clone();
1977            refined_knots[k] = knots[i];
1978            k -= 1;
1979            i -= 1;
1980        }
1981        refined[k - p - 1] = refined[k - p].clone();
1982        for l in 1..=p {
1983            let index = k - p + l;
1984            let numerator = refined_knots[k + l] - inserted[j];
1985            if numerator == 0.0 {
1986                refined[index - 1] = refined[index].clone();
1987            } else {
1988                let alpha = numerator / (refined_knots[k + l] - knots[i - p + l]);
1989                let (head, tail) = refined.split_at_mut(index);
1990                for (before, &here) in head[index - 1].iter_mut().zip(&tail[0]) {
1991                    *before = before.scale(alpha).add(here.scale(1.0 - alpha));
1992                }
1993            }
1994        }
1995        refined_knots[k] = inserted[j];
1996        k = k.saturating_sub(1);
1997    }
1998    *net = refined;
1999    *knots = refined_knots;
2000}
2001
2002/// The control-point index range supporting the parameter interval
2003/// `[low, high]`: every basis function non-zero anywhere on it.
2004fn supporting_range(knots: &[f64], degree: usize, count: usize, low: f64, high: f64) -> (usize, usize) {
2005    let first_span = knots.partition_point(|&knot| knot <= low).saturating_sub(1);
2006    let last_span = knots.partition_point(|&knot| knot < high).saturating_sub(1);
2007    (
2008        first_span.saturating_sub(degree).min(count - 1),
2009        last_span.max(first_span).min(count - 1),
2010    )
2011}
2012
2013fn unit_or(vector: Vec3, fallback: Vec3) -> Vec3 {
2014    let length = vector.length();
2015    if length > 0.0 && length.is_finite() {
2016        vector.scale(1.0 / length)
2017    } else {
2018        fallback
2019    }
2020}
2021
2022fn enclosing_sphere(a: (Vec3, f64), b: (Vec3, f64)) -> (Vec3, f64) {
2023    let offset = b.0.sub(a.0);
2024    let separation = offset.length();
2025    if separation + b.1 <= a.1 {
2026        return a;
2027    }
2028    if separation + a.1 <= b.1 {
2029        return b;
2030    }
2031    let radius = (separation + a.1 + b.1) * 0.5;
2032    let centre = a.0.add(offset.scale((radius - a.1) / separation));
2033    (centre, radius)
2034}
2035
2036/// What [`build_cell_tree`] reads besides the spheres: the cells' boxes and
2037/// the lattice points (row-major, `lattice_columns` per row) that frame each
2038/// internal node's box, and the margin each internal box grows by.
2039struct NodeBoxInputs<'a> {
2040    boxes: &'a [CellBox],
2041    nodes: &'a [Vec3],
2042    lattice_columns: usize,
2043    margin: f64,
2044}
2045
2046/// The box of an internal node: framed like a cell's (along u, then the
2047/// normal of the region's lattice corners), spanning every corner of both
2048/// children's boxes, grown by `margin` on every side. Unbounded when a frame or
2049/// an extent is not finite, so it never prunes.
2050fn enclosing_node_box(corners: [Vec3; 4], children: [&CellBox; 2], margin: f64) -> CellBox {
2051    let unbounded = || CellBox {
2052        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)],
2053        low: [f64::NEG_INFINITY; 3],
2054        high: [f64::INFINITY; 3],
2055    };
2056    let [c00, c10, c01, c11] = corners;
2057    let along_u = c10.sub(c00).add(c11.sub(c01));
2058    let along_v = c01.sub(c00).add(c11.sub(c10));
2059    let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2060    let Ok(fallback) = e1.perpendicular() else {
2061        return unbounded();
2062    };
2063    let normal = unit_or(e1.cross(along_v), fallback);
2064    let e2 = unit_or(normal.cross(e1), fallback);
2065    let e3 = e1.cross(e2);
2066    let axes = [e1, e2, e3];
2067    let mut low = [f64::INFINITY; 3];
2068    let mut high = [f64::NEG_INFINITY; 3];
2069    for child in children {
2070        for corner in 0..8 {
2071            let mut point = Vec3::default();
2072            for axis in 0..3 {
2073                let value = if corner >> axis & 1 == 0 { child.low[axis] } else { child.high[axis] };
2074                point = point.add(child.axes[axis].scale(value));
2075            }
2076            for axis in 0..3 {
2077                let coordinate = point.dot(axes[axis]);
2078                low[axis] = low[axis].min(coordinate);
2079                high[axis] = high[axis].max(coordinate);
2080            }
2081        }
2082    }
2083    for axis in 0..3 {
2084        low[axis] -= margin;
2085        high[axis] += margin;
2086    }
2087    if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2088        return unbounded();
2089    }
2090    CellBox { axes, low, high }
2091}
2092
2093fn build_cell_tree(
2094    tree: &mut Vec<CellTreeNode>,
2095    node_boxes: &mut Vec<CellBox>,
2096    inputs: &NodeBoxInputs<'_>,
2097    spheres: &[(Vec3, f64)],
2098    columns: usize,
2099    [row_low, row_high, column_low, column_high]: [usize; 4],
2100) -> u32 {
2101    if row_high - row_low == 1 && column_high - column_low == 1 {
2102        let cell = row_low * columns + column_low;
2103        node_boxes.push(inputs.boxes[cell].clone());
2104        tree.push(CellTreeNode {
2105            centre: spheres[cell].0,
2106            radius: spheres[cell].1,
2107            children: None,
2108            cell: cell as u32,
2109        });
2110        return (tree.len() - 1) as u32;
2111    }
2112    let (first, second) = if row_high - row_low >= column_high - column_low {
2113        let middle = (row_low + row_high) / 2;
2114        (
2115            [row_low, middle, column_low, column_high],
2116            [middle, row_high, column_low, column_high],
2117        )
2118    } else {
2119        let middle = (column_low + column_high) / 2;
2120        (
2121            [row_low, row_high, column_low, middle],
2122            [row_low, row_high, middle, column_high],
2123        )
2124    };
2125    let first = build_cell_tree(tree, node_boxes, inputs, spheres, columns, first);
2126    let second = build_cell_tree(tree, node_boxes, inputs, spheres, columns, second);
2127    let a = tree[first as usize];
2128    let b = tree[second as usize];
2129    let lattice = |row: usize, column: usize| inputs.nodes[row * inputs.lattice_columns + column];
2130    node_boxes.push(enclosing_node_box(
2131        [
2132            lattice(row_low, column_low),
2133            lattice(row_high, column_low),
2134            lattice(row_low, column_high),
2135            lattice(row_high, column_high),
2136        ],
2137        [&node_boxes[first as usize], &node_boxes[second as usize]],
2138        inputs.margin,
2139    ));
2140    // The resolution-inflated leaf spheres already absorb rounding; the merge
2141    // adds one more rounding of the same order, absorbed by growing the radius
2142    // by the larger child's own ulp.
2143    let (centre, radius) = enclosing_sphere((a.centre, a.radius), (b.centre, b.radius));
2144    tree.push(CellTreeNode {
2145        centre,
2146        radius: radius * (1.0 + 4.0 * f64::EPSILON),
2147        children: Some((first, second)),
2148        cell: u32::MAX,
2149    });
2150    (tree.len() - 1) as u32
2151}
2152
2153fn projection_cells(surface: &NurbsSurface) -> Result<Option<&ProjectionCells>, String> {
2154    if let Some(cells) = surface.projection_cells.get() {
2155        return Ok(cells.as_ref());
2156    }
2157    let cells = build_projection_cells(surface)?;
2158    Ok(surface.projection_cells.get_or_init(|| cells).as_ref())
2159}
2160
2161fn build_projection_cells(surface: &NurbsSurface) -> Result<Option<ProjectionCells>, String> {
2162    let (closed_u, closed_v) = surface.closed_directions()?;
2163    let us = lattice_parameters(&surface.knots_u, surface.degree_u, closed_u);
2164    let vs = lattice_parameters(&surface.knots_v, surface.degree_v, closed_v);
2165    if us.len() < 2 || vs.len() < 2 {
2166        return Ok(None);
2167    }
2168    let mut scale = 0.0f64;
2169    for control in surface.control_points.iter().flatten() {
2170        let point = control.point()?;
2171        scale = scale.max(point.x.abs()).max(point.y.abs()).max(point.z.abs());
2172    }
2173    let resolution =
2174        ((surface.degree_u + 1) * (surface.degree_v + 1)) as f64 * f64::EPSILON * scale;
2175
2176    // Refine u (the net's rows), then v (its columns, as rows of the transpose).
2177    let mut net = surface.control_points.clone();
2178    let mut knots_u = surface.knots_u.clone();
2179    refine_to_lattice(&mut net, &mut knots_u, surface.degree_u, &us);
2180    let columns = net.first().map(Vec::len).unwrap_or(0);
2181    let mut transposed: Vec<Vec<Vec4>> =
2182        (0..columns).map(|column| net.iter().map(|row| row[column]).collect()).collect();
2183    let mut knots_v = surface.knots_v.clone();
2184    refine_to_lattice(&mut transposed, &mut knots_v, surface.degree_v, &vs);
2185    let rows = transposed.first().map(Vec::len).unwrap_or(0);
2186    let columns = transposed.len();
2187    if rows == 0 || columns == 0 {
2188        return Ok(None);
2189    }
2190    let mut points = vec![Vec3::default(); rows * columns];
2191    for (column, fibre) in transposed.iter().enumerate() {
2192        for (row, control) in fibre.iter().enumerate() {
2193            points[row * columns + column] = control.point()?;
2194        }
2195    }
2196
2197    let mut nodes = Vec::with_capacity(us.len() * vs.len());
2198    for &u in &us {
2199        for &v in &vs {
2200            nodes.push(surface.evaluate(u, v)?);
2201        }
2202    }
2203
2204    let cell_rows = us.len() - 1;
2205    let cell_columns = vs.len() - 1;
2206    let mut boxes = Vec::with_capacity(cell_rows * cell_columns);
2207    let mut spheres = Vec::with_capacity(cell_rows * cell_columns);
2208    for i in 0..cell_rows {
2209        let (row_low, row_high) =
2210            supporting_range(&knots_u, surface.degree_u, rows, us[i], us[i + 1]);
2211        for j in 0..cell_columns {
2212            let (column_low, column_high) =
2213                supporting_range(&knots_v, surface.degree_v, columns, vs[j], vs[j + 1]);
2214            let at = |row: usize, column: usize| points[row * columns + column];
2215            let c00 = at(row_low, column_low);
2216            let c10 = at(row_high, column_low);
2217            let c01 = at(row_low, column_high);
2218            let c11 = at(row_high, column_high);
2219            let along_u = c10.sub(c00).add(c11.sub(c01));
2220            let along_v = c01.sub(c00).add(c11.sub(c10));
2221            let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2222            let normal = unit_or(e1.cross(along_v), e1.perpendicular()?);
2223            let e2 = unit_or(normal.cross(e1), e1.perpendicular()?);
2224            let e3 = e1.cross(e2);
2225            let axes = [e1, e2, e3];
2226            let mut low = [f64::INFINITY; 3];
2227            let mut high = [f64::NEG_INFINITY; 3];
2228            for row in row_low..=row_high {
2229                for column in column_low..=column_high {
2230                    let point = at(row, column);
2231                    for axis in 0..3 {
2232                        let coordinate = point.dot(axes[axis]);
2233                        low[axis] = low[axis].min(coordinate);
2234                        high[axis] = high[axis].max(coordinate);
2235                    }
2236                }
2237            }
2238            for axis in 0..3 {
2239                low[axis] -= resolution;
2240                high[axis] += resolution;
2241            }
2242            let mut centre = Vec3::default();
2243            let mut half_diagonal_squared = 0.0;
2244            for axis in 0..3 {
2245                centre = centre.add(axes[axis].scale((low[axis] + high[axis]) * 0.5));
2246                let half = (high[axis] - low[axis]) * 0.5;
2247                half_diagonal_squared += half * half;
2248            }
2249            if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2250                return Ok(None);
2251            }
2252            spheres.push((centre, half_diagonal_squared.sqrt() + resolution));
2253            boxes.push(CellBox { axes, low, high });
2254        }
2255    }
2256    let mut tree = Vec::with_capacity(2 * boxes.len());
2257    let mut node_boxes = Vec::with_capacity(2 * boxes.len());
2258    // Each internal box grows by a billionth of the surface's scale over its
2259    // children: far above the rounding of the corners it spans and of the
2260    // bound read from it, so a box that excludes a point excludes every cell
2261    // under it (see `hull_candidates`).
2262    let node_margin = NODE_BOX_MARGIN * scale;
2263    let inputs = NodeBoxInputs { boxes: &boxes, nodes: &nodes, lattice_columns: vs.len(), margin: node_margin };
2264    build_cell_tree(&mut tree, &mut node_boxes, &inputs, &spheres, cell_columns, [0, cell_rows, 0, cell_columns]);
2265    if !(node_margin > 0.0 && node_margin.is_finite()) {
2266        node_boxes = Vec::new();
2267    }
2268    Ok(Some(ProjectionCells {
2269        us,
2270        vs,
2271        nodes,
2272        boxes,
2273        tree,
2274        node_boxes,
2275        node_margin,
2276        scale,
2277        resolution,
2278    }))
2279}
2280
2281/// First- and second-order optimality of `(u, v)` for the distance over the
2282/// rectangle: stationary on the coordinates the rectangle leaves free (the
2283/// descent's own cosine test), with a positive definite Hessian there. A
2284/// `periodic` direction has no edge to be pinned against: its seam is interior.
2285fn optimality(
2286    derivatives: &[[Vec3; 3]; 3],
2287    point: Vec3,
2288    (u, v): (f64, f64),
2289    [ua, ub, va, vb]: [f64; 4],
2290    periodic: (bool, bool),
2291) -> Optimality {
2292    let residual = derivatives[0][0].sub(point);
2293    let residual_length = residual.length();
2294    let su = derivatives[1][0];
2295    let sv = derivatives[0][1];
2296    let f = su.dot(residual);
2297    let g = sv.dot(residual);
2298    let metric_u = su.length_squared();
2299    let metric_v = sv.length_squared();
2300    let stationary_u = metric_u.sqrt() * residual_length <= EPSILON
2301        || f.abs() <= 1e-10 * metric_u.sqrt() * residual_length;
2302    let stationary_v = metric_v.sqrt() * residual_length <= EPSILON
2303        || g.abs() <= 1e-10 * metric_v.sqrt() * residual_length;
2304    let pinned_u = !periodic.0 && ((u <= ua && f > 0.0) || (u >= ub && f < 0.0));
2305    let pinned_v = !periodic.1 && ((v <= va && g > 0.0) || (v >= vb && g < 0.0));
2306    let j00 = derivatives[2][0].dot(residual) + metric_u;
2307    let j01 = derivatives[1][1].dot(residual) + su.dot(sv);
2308    let j11 = derivatives[0][2].dot(residual) + metric_v;
2309    let determinant = j00 * j11 - j01 * j01;
2310    let convex = match (!pinned_u, !pinned_v) {
2311        (true, true) => j00 > 0.0 && determinant > 0.0,
2312        (true, false) => j00 > 0.0,
2313        (false, true) => j11 > 0.0,
2314        (false, false) => true,
2315    };
2316    Optimality {
2317        residual_length,
2318        gradient: (f, g),
2319        metric: (metric_u, metric_v),
2320        hessian: (j00, j01, j11),
2321        determinant,
2322        pinned: (pinned_u, pinned_v),
2323        convex,
2324        minimum: residual_length <= LINEAR_TOLERANCE
2325            || ((stationary_u || pinned_u) && (stationary_v || pinned_v) && convex),
2326    }
2327}
2328
2329struct Optimality {
2330    residual_length: f64,
2331    gradient: (f64, f64),
2332    metric: (f64, f64),
2333    hessian: (f64, f64, f64),
2334    determinant: f64,
2335    pinned: (bool, bool),
2336    convex: bool,
2337    minimum: bool,
2338}
2339
2340fn is_verified_minimum(
2341    surface: &NurbsSurface,
2342    point: Vec3,
2343    at: (f64, f64),
2344    rectangle: [f64; 4],
2345    periodic: (bool, bool),
2346) -> Result<bool, String> {
2347    let derivatives = surface.derivatives_small(at.0, at.1, 2)?;
2348    Ok(optimality(&derivatives, point, at, rectangle, periodic).minimum)
2349}
2350
2351/// A descent to a local minimum of the distance over the rectangle
2352/// `[ua, ub] × [va, vb]`, from a seed inside it.
2353///
2354/// Newton on the gradient converges to ANY critical point — a saddle or a
2355/// maximum as readily as a minimum — and reads convergence there, so every
2356/// step here must lower the distance: the Newton step where the Hessian is
2357/// positive definite on the free coordinates, the metric-scaled gradient step
2358/// where it is not, halved until the distance does not rise. A coordinate
2359/// pinned at the rectangle's edge by a gradient pointing out of it is held
2360/// there and the other takes the one-dimensional step, so a minimum ON the edge
2361/// converges as one (the Karush-Kuhn-Tucker point) instead of stalling.
2362///
2363/// Returns the best iterate, whether it is a verified minimum (stationary on
2364/// the free coordinates with a positive definite Hessian there, or within the
2365/// on-surface floor), and whether it lies on the rectangle's edge.
2366fn confined_descent(
2367    surface: &NurbsSurface,
2368    point: Vec3,
2369    seed: (f64, f64),
2370    rectangle: [f64; 4],
2371    periodic: (bool, bool),
2372) -> Result<(NewtonResult, bool), String> {
2373    let [ua, ub, va, vb] = rectangle;
2374    let mut u = fit_parameter(seed.0, ua, ub, periodic.0);
2375    let mut v = fit_parameter(seed.1, va, vb, periodic.1);
2376    let mut converged = false;
2377    let mut current = surface.evaluate(u, v)?.sub(point).length_squared();
2378    for _ in 0..MAX_NEWTON_ITERATIONS {
2379        let derivatives = surface.derivatives_small(u, v, 2)?;
2380        let state = optimality(&derivatives, point, (u, v), rectangle, periodic);
2381        current = state.residual_length * state.residual_length;
2382        if state.minimum {
2383            converged = true;
2384            break;
2385        }
2386        let (f, g) = state.gradient;
2387        let (metric_u, metric_v) = state.metric;
2388        let (j00, j01, j11) = state.hessian;
2389        let determinant = state.determinant;
2390        let (free_u, free_v) = (!state.pinned.0, !state.pinned.1);
2391        let (mut du, mut dv) = match (free_u, free_v) {
2392            (true, true) if state.convex => (
2393                (-f * j11 + g * j01) / determinant,
2394                (-g * j00 + f * j01) / determinant,
2395            ),
2396            (true, false) if state.convex => (-f / j00, 0.0),
2397            (false, true) if state.convex => (0.0, -g / j11),
2398            _ => (
2399                if free_u && metric_u > 0.0 { -f / metric_u } else { 0.0 },
2400                if free_v && metric_v > 0.0 { -g / metric_v } else { 0.0 },
2401            ),
2402        };
2403        if !(du.is_finite() && dv.is_finite()) || (du == 0.0 && dv == 0.0) {
2404            break;
2405        }
2406        let mut moved = false;
2407        // The step actually taken, a whole period removed across a seam.
2408        let taken = |next: f64, here: f64, low: f64, high: f64, wraps: bool| {
2409            let raw = next - here;
2410            if wraps {
2411                raw - (high - low) * (raw / (high - low)).round()
2412            } else {
2413                raw
2414            }
2415        };
2416        for _ in 0..40 {
2417            let next_u = fit_parameter(u + du, ua, ub, periodic.0);
2418            let next_v = fit_parameter(v + dv, va, vb, periodic.1);
2419            if next_u == u && next_v == v {
2420                break;
2421            }
2422            let trial = surface.evaluate(next_u, next_v)?.sub(point).length_squared();
2423            if trial <= current {
2424                moved = taken(next_u, u, ua, ub, periodic.0).abs() > 1e-15 * (ub - ua)
2425                    || taken(next_v, v, va, vb, periodic.1).abs() > 1e-15 * (vb - va);
2426                u = next_u;
2427                v = next_v;
2428                current = trial;
2429                break;
2430            }
2431            du *= 0.5;
2432            dv *= 0.5;
2433        }
2434        if !moved {
2435            break;
2436        }
2437    }
2438    let result = NewtonResult {
2439        u,
2440        v,
2441        distance_squared: current,
2442        converged,
2443    };
2444    let on_edge =
2445        (!periodic.0 && (u <= ua || u >= ub)) || (!periodic.1 && (v <= va || v >= vb));
2446    Ok((result, on_edge))
2447}
2448
2449/// The growth of an internal node's box over its children's, per unit of
2450/// the surface's scale.
2451const NODE_BOX_MARGIN: f64 = 1e-9;
2452
2453/// `BREP_PROJECTION_NODE_BOXES` (default on): the cell-tree walk also reads
2454/// each internal node's box, not only its sphere. `=0` walks on spheres alone,
2455/// as before. Read once.
2456fn node_boxes_enabled() -> bool {
2457    switch!("BREP_PROJECTION_NODE_BOXES", true)
2458}
2459
2460/// The walk of the global stage: every cell whose box comes nearer `point`
2461/// than `bound`, with its box bound, in the walk's order, and the least bound
2462/// over everything the walk excluded.
2463///
2464/// A node is excluded when its sphere is no nearer than `bound`, and, with
2465/// `node_boxes`, when its box is not either. Cell spheres are loose on long,
2466/// thin cells (a 16 × 5632 lattice: about 3000 nodes visited and 200 cells
2467/// read per query to admit one), and an internal box is not. The box test
2468/// only removes subtrees whose every cell the cell test would reject, in the
2469/// same order, so the candidates are the same list to the bit with and
2470/// without it. Each internal box holds its children's boxes grown by
2471/// `node_margin` (`m`), and both bounds are read within `e` of their exact
2472/// value, `e` (below) set by the point's and the surface's magnitudes. A
2473/// box read at `b ≥ bound` with `b > 2e` is truly at least `b − e > 0` away,
2474/// so each cell box under it is truly at least `b − e + m` away and reads at
2475/// least `b − 2e + m ≥ bound` whenever `m ≥ 2e`; the test is skipped for a
2476/// point so far out that `4e > m` (beyond about 3·10⁴ scales), keeping half
2477/// of `m` for the rounding of the box corners themselves. Only the excluded
2478/// bound (the certificate in `GlobalStats::hull_lower_bound`) can differ: it
2479/// is still a lower bound, read from a tighter box.
2480fn hull_candidates(cells: &ProjectionCells, point: Vec3, bound: f64, node_boxes: bool) -> (Vec<(f64, usize)>, f64) {
2481    let read_error = 32.0 * f64::EPSILON * (point.x.abs() + point.y.abs() + point.z.abs() + 4.0 * cells.scale);
2482    let boxes = node_boxes && !cells.node_boxes.is_empty() && 4.0 * read_error <= cells.node_margin;
2483    let mut candidates: Vec<(f64, usize)> = Vec::new();
2484    let mut excluded = f64::INFINITY;
2485    let mut stack: Vec<u32> = Vec::with_capacity(64);
2486    stack.push((cells.tree.len() - 1) as u32);
2487    while let Some(index) = stack.pop() {
2488        let node = cells.tree[index as usize];
2489        let sphere_bound = (point.sub(node.centre).length() - node.radius).max(0.0);
2490        if sphere_bound >= bound {
2491            excluded = excluded.min(sphere_bound);
2492            continue;
2493        }
2494        match node.children {
2495            Some((first, second)) => {
2496                if boxes {
2497                    let box_bound = cells.node_boxes[index as usize].lower_bound(point);
2498                    if box_bound >= bound && box_bound > 2.0 * read_error {
2499                        excluded = excluded.min(box_bound);
2500                        continue;
2501                    }
2502                }
2503                stack.push(first);
2504                stack.push(second);
2505            }
2506            None => {
2507                let cell = node.cell as usize;
2508                let box_bound = cells.boxes[cell].lower_bound(point);
2509                if box_bound < bound {
2510                    candidates.push((box_bound, cell));
2511                } else {
2512                    excluded = excluded.min(box_bound);
2513                }
2514            }
2515        }
2516    }
2517    (candidates, excluded)
2518}
2519
2520/// The global stage of [`project_point_to_surface_general`]: replace `best`
2521/// with the least local minimum over every cell the hull bound admits.
2522#[allow(clippy::too_many_arguments)]
2523fn global_minimum(
2524    surface: &NurbsSurface,
2525    point: Vec3,
2526    domains: [f64; 4],
2527    periodic: (bool, bool),
2528    best: &mut NewtonResult,
2529    stats: &mut GlobalStats,
2530) -> Result<(), String> {
2531    if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2532        stats.settled_by_floor = true;
2533        return Ok(());
2534    }
2535    let Some(cells) = projection_cells(surface)? else {
2536        return Ok(());
2537    };
2538    let resolution = cells.resolution;
2539    let columns = cells.vs.len() - 1;
2540    let columns_u = cells.us.len() - 1;
2541    let mut bound = best.distance_squared.sqrt() - resolution;
2542
2543    // Every cell whose box comes nearer than the answer; the least bound over
2544    // what the walk excluded is the certificate.
2545    let (mut candidates, excluded) = hull_candidates(cells, point, bound, node_boxes_enabled());
2546    stats.candidates = candidates.len();
2547    candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
2548    stats.hull_lower_bound = candidates
2549        .first()
2550        .map_or(excluded, |&(least, _)| least.min(excluded));
2551
2552    // Cells already holding a verified minimum need no second descent. A foot
2553    // names ONE cell even when it sits on a lattice line shared by up to four:
2554    // a neighbour can hold a better basin of its own in its interior, and it
2555    // was admitted precisely because its bound beat this answer. The local
2556    // answer is one when it passes the same test the descent applies.
2557    let cell_of = |u: f64, v: f64| {
2558        let row = (cells.us.partition_point(|&value| value <= u).max(1) - 1).min(columns_u - 1);
2559        let column = (cells.vs.partition_point(|&value| value <= v).max(1) - 1).min(columns - 1);
2560        row * columns + column
2561    };
2562    let mut settled: Vec<usize> = Vec::new();
2563    if is_verified_minimum(surface, point, (best.u, best.v), domains, periodic)? {
2564        settled.push(cell_of(best.u, best.v));
2565    }
2566    for (cell_bound, cell) in candidates {
2567        if cell_bound >= bound {
2568            break;
2569        }
2570        let row = cell / columns;
2571        let column = cell % columns;
2572        let rectangle = [
2573            cells.us[row],
2574            cells.us[row + 1],
2575            cells.vs[column],
2576            cells.vs[column + 1],
2577        ];
2578        if settled.contains(&cell) {
2579            continue;
2580        }
2581        let mut seed = (rectangle[0], rectangle[2]);
2582        let mut seed_distance = f64::INFINITY;
2583        for (node_row, node_column) in
2584            [(row, column), (row + 1, column), (row, column + 1), (row + 1, column + 1)]
2585        {
2586            let distance = cells.nodes[node_row * cells.vs.len() + node_column]
2587                .sub(point)
2588                .length_squared();
2589            if distance < seed_distance {
2590                seed_distance = distance;
2591                seed = (cells.us[node_row], cells.vs[node_column]);
2592            }
2593        }
2594        stats.refinements += 1;
2595        let (confined, on_edge) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2596        let mut found = confined;
2597        if on_edge && confined.distance_squared.sqrt() < bound {
2598            // The cell's least point is on its edge and beats the answer:
2599            // the basin continues past the cell.
2600            stats.continuations += 1;
2601            let (continued, _) =
2602                confined_descent(surface, point, (confined.u, confined.v), domains, periodic)?;
2603            if continued.distance_squared < found.distance_squared {
2604                found = continued;
2605            }
2606            if continued.converged {
2607                settled.push(cell_of(continued.u, continued.v));
2608            }
2609        }
2610        if found.distance_squared.sqrt() < bound {
2611            *best = found;
2612            bound = best.distance_squared.sqrt() - resolution;
2613            stats.replaced = true;
2614            if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2615                return Ok(());
2616            }
2617        }
2618    }
2619    Ok(())
2620}
2621
2622
2623
2624/// Domain handling for a local foot-point Newton walk.
2625#[derive(Clone, Copy)]
2626pub enum FootDomain {
2627    Clamp,
2628    Wrap,
2629    Extended,
2630}
2631
2632#[derive(Clone, Copy)]
2633pub struct CurveFootPolicy {
2634    pub domain: FootDomain,
2635    pub iterations: usize,
2636    pub slope_guard: f64,
2637    pub step_limit: f64,
2638    pub parameter_tolerance: f64,
2639    pub mode: FootMode,
2640}
2641
2642/// Acceptance and convergence differ between a distance minimum and a stationary root.
2643#[derive(Clone, Copy)]
2644pub enum FootMode {
2645    Monotone,
2646    Witness,
2647    Stationary { positive_slope: bool, relative_step: bool },
2648    Backtracked,
2649    Planar,
2650}
2651
2652/// Local Newton foot. Seeding and enumeration of local minima belong to the caller.
2653/// Returns the last parameter, best witnessed parameter, and squared distance.
2654fn curve_foot_newton_state(
2655    curve: &NurbsCurve,
2656    point: Vec3,
2657    seed: f64,
2658    bracket: [f64; 2],
2659    policy: CurveFootPolicy,
2660) -> Result<(f64, f64, f64), String> {
2661    let fit = |u| match policy.domain {
2662        FootDomain::Clamp => fit_parameter(u, bracket[0], bracket[1], false),
2663        FootDomain::Wrap => fit_parameter(u, bracket[0], bracket[1], true),
2664        FootDomain::Extended => u,
2665    };
2666    let extended = matches!(policy.domain, FootDomain::Extended) || matches!(policy.mode, FootMode::Backtracked);
2667    let planar = matches!(policy.mode, FootMode::Planar);
2668    let project = |p: Vec3| if planar { Vec3::new(p.x, p.y, 0.0) } else { p };
2669    let point = project(point);
2670    let distance = |u| -> Result<f64, String> {
2671        let p = if extended { curve.derivatives_extended(u, 0)?[0] } else { curve.evaluate(u)? };
2672        Ok(project(p).sub(point).length())
2673    };
2674    let monotone = matches!(policy.mode, FootMode::Monotone | FootMode::Backtracked);
2675    let witness = matches!(policy.mode, FootMode::Witness);
2676    let mut u = if witness { seed } else { fit(seed) };
2677    let mut nearest_u = seed;
2678    let mut nearest_squared = f64::INFINITY;
2679    let mut best = if monotone { distance(u)? } else { f64::INFINITY };
2680    for _ in 0..policy.iterations {
2681        let derivatives = if extended {
2682            let values = curve.derivatives_extended(u, 2)?;
2683            [values[0], values[1], values[2]]
2684        } else if matches!(policy.mode, FootMode::Stationary { .. })
2685            || (planar && !crate::curve::small_curve_derivatives_enabled()) {
2686            let values = curve.derivatives(u, 2)?;
2687            [values[0], values[1], values[2]]
2688        } else {
2689            curve.derivatives_small(u, 2)?
2690        }.map(project);
2691        let offset = derivatives[0].sub(point);
2692        let numerator = offset.dot(derivatives[1]);
2693        let denominator = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
2694        if witness {
2695            let squared = offset.length_squared();
2696            if squared < nearest_squared {
2697                nearest_u = u;
2698                nearest_squared = squared;
2699            }
2700            let residual_length = squared.sqrt();
2701            if residual_length <= LINEAR_TOLERANCE
2702                || numerator.abs() <= EPSILON + 1e-10 * derivatives[1].length() * residual_length {
2703                break;
2704            }
2705        }
2706        let singular = if planar { denominator.abs() < policy.slope_guard }
2707            else { denominator.abs() <= policy.slope_guard };
2708        if singular || (matches!(policy.mode, FootMode::Stationary { positive_slope: true, .. }) && !(denominator > 0.0)) { break; }
2709        let mut step = if matches!(policy.mode, FootMode::Backtracked) && !(denominator > 0.0) {
2710            policy.step_limit.copysign(numerator)
2711        } else {
2712            (numerator / denominator).clamp(-policy.step_limit, policy.step_limit)
2713        };
2714        let mut next = fit(u - step);
2715        let mut next_distance = if monotone { distance(next)? } else { f64::INFINITY };
2716        if matches!(policy.mode, FootMode::Backtracked) {
2717            for _ in 0..30 {
2718                if next_distance < best { break; }
2719                step *= 0.5;
2720                next = fit(u - step);
2721                next_distance = distance(next)?;
2722            }
2723            if !(next_distance < best) { break; }
2724        } else if monotone && next_distance >= best { break; }
2725        let moved = if planar || matches!(policy.domain, FootDomain::Extended) { step }
2726            else if matches!(policy.domain, FootDomain::Wrap) {
2727                let period = bracket[1] - bracket[0];
2728                let raw = next - u;
2729                raw - period * (raw / period).round()
2730            } else { next - u };
2731        let tolerance = if matches!(policy.mode, FootMode::Stationary { relative_step: true, .. }) {
2732            policy.parameter_tolerance * (1.0 + u.abs())
2733        } else { policy.parameter_tolerance };
2734        let small = if planar || matches!(policy.mode, FootMode::Backtracked) { moved.abs() < tolerance }
2735            else { moved.abs() <= tolerance };
2736        if small && matches!(policy.mode, FootMode::Monotone) { break; }
2737        u = next;
2738        best = next_distance;
2739        if small { break; }
2740    }
2741    if witness { return Ok((u, nearest_u, nearest_squared)); }
2742    if !monotone { best = distance(u)?; }
2743    Ok((u, u, best * best))
2744}
2745
2746pub fn curve_foot_newton(
2747    curve: &NurbsCurve, point: Vec3, seed: f64, bracket: [f64; 2], policy: CurveFootPolicy,
2748) -> Result<(f64, f64), String> {
2749    let (_, nearest, squared) = curve_foot_newton_state(curve, point, seed, bracket, policy)?;
2750    Ok((nearest, squared))
2751}
2752
2753
2754