Skip to main content

brep_kernel/geometry/
projection.rs

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