Skip to main content

brep_geometry/intersect/
surface_surface_intersection.rs

1use crate::curve::interior_knot_count;
2use crate::fit::solve_small;
3use crate::projection::project_point_to_surface_from_seed;
4use crate::{project_point_to_surface, KnotVector, NurbsSurface, Vec3, Vec4};
5use std::collections::HashMap;
6use serde::{Deserialize, Serialize};
7
8const EPSILON: f64 = crate::tolerance::FP_FLOOR;
9const LINEAR_TOLERANCE: f64 = crate::tolerance::DEFAULT_MODEL;
10
11/// Minimum `|n_a × n_b|` at a start point for a trace to begin there — the
12/// gate `intersect_surfaces` applies to explicit seeds and grid starts alike,
13/// and `intersect_surfaces_supplemental` to its own seeds.
14///
15/// Below it the carriers are tangent there to working precision, so the point
16/// sits in a tangency BAND — the set of points within the coincidence
17/// tolerance of both surfaces, about `√(2·R·tol)` wide across a contact of
18/// curvature radius `R` — rather than on a transverse curve.  A trace started
19/// inside the band walks the band's noise: it neither closes nor reaches a
20/// boundary and exhausts its step budget (a corner blend's sphere kissing a
21/// mirrored copy's face plane at one point; the same sphere inscribed in its
22/// own fillet cylinder, kissing it along a circle).  Shared topology at a
23/// tangential contact comes from imprint's boundary-curve exchange, never
24/// from marching ("similar faces we do not intersect" — Golovanov §6.2).
25const TRANSVERSE_START_CROSS: f64 = 1e-2;
26
27/// [`TRANSVERSE_START_CROSS`] under its crate-wide name: the bound at which a
28/// contact stops being a graze and becomes a crossing. `csg::imprint`'s
29/// tangential-only gate asks the same question of a marched point, and must ask
30/// it with the same number the seeds were accepted by.
31pub const TRANSVERSE_SEED_CROSS: f64 = TRANSVERSE_START_CROSS;
32
33/// How much CURVE a trace must be able to reach, as a multiple of the
34/// carriers' shared extent, whatever step ceiling the caller asked for.
35///
36/// `maximum_steps` bounds corrector CALLS; multiplied by the ceiling in force
37/// it bounds the ARC a trace can reach, and that product is the only thing
38/// that decides whether an ordinary section is reachable at all.  At the
39/// marcher's own ceiling (`diagonal / 15`) the default budget reaches 266
40/// extents — no bound in practice.  A caller that asks for a FINER ceiling is
41/// asking for RESOLUTION, and its request silently shortened the reach in the
42/// same proportion: `offset_shell`'s `0.0005 · scale` leaves 2.0 extents, less
43/// than one turn of an ordinary closed section on a part that size, so a
44/// perfectly marched circle died at 4000 steps (2026-09-13: the apex-cone
45/// carrier against its base plane — 42.714 of curve against a 28.844 reach,
46/// every step at the cap, the §4.12 curvature budget permitting 113× more).
47///
48/// That is the 2026-08-06 rule one level up: what a marcher can reach must be
49/// a fixed fraction of the MODEL, never a function of the step the caller
50/// asked for.  So the ceiling is honoured as resolution and the step COUNT is
51/// derived from it — the trace takes however many steps this much curve needs.
52/// Nothing that completes today changes by a single step: the derived count
53/// only ever exceeds the caller's own, and only on the fine-ceiling lane.
54///
55/// It is a FLOOR on the reach, not a bound on how long a section may be — the
56/// default lane keeps its 266 extents.  Sized for the fine-ceiling lane alone,
57/// where the longest section measured over the kernel's 37 631 traces is 1.76
58/// extents (the 2026-09-13 census; 4.43 is the most any capped ceiling reached
59/// before this and 0.13 the least).
60const MARCH_REACH_EXTENTS: f64 = 4.0;
61
62/// Corrector calls a trace may spend: the caller's own budget, or however many
63/// [`MARCH_REACH_EXTENTS`] of curve need at `maximum_step`, whichever is more.
64fn step_budget(maximum_steps: usize, maximum_step: f64, diagonal: f64) -> usize {
65    if !(maximum_step > 0.0) || !diagonal.is_finite() {
66        return maximum_steps;
67    }
68    let needed = (MARCH_REACH_EXTENTS * diagonal / maximum_step).ceil();
69    if !needed.is_finite() || needed <= maximum_steps as f64 {
70        return maximum_steps;
71    }
72    needed as usize
73}
74
75use crate::spatial::Aabb as Bounds;
76
77
78#[derive(Clone, Copy)]
79struct SurfaceInfo<'a> {
80    surface: &'a NurbsSurface,
81    u0: f64,
82    u1: f64,
83    v0: f64,
84    v1: f64,
85    closed_u: bool,
86    closed_v: bool,
87}
88
89fn surface_info(surface: &NurbsSurface) -> Result<SurfaceInfo<'_>, String> {
90    let ku = KnotVector::new(surface.knots_u.clone(), surface.degree_u)?;
91    let kv = KnotVector::new(surface.knots_v.clone(), surface.degree_v)?;
92    let [u0, u1] = ku.domain();
93    let [v0, v1] = kv.domain();
94    let mut closed_u = true;
95    let mut closed_v = true;
96    for fraction in [0.17, 0.5, 0.83] {
97        let v = v0 + (v1 - v0) * fraction;
98        if surface
99            .evaluate(u0, v)?
100            .sub(surface.evaluate(u1, v)?)
101            .length()
102            > LINEAR_TOLERANCE * 10.0
103        {
104            closed_u = false;
105        }
106        let u = u0 + (u1 - u0) * fraction;
107        if surface
108            .evaluate(u, v0)?
109            .sub(surface.evaluate(u, v1)?)
110            .length()
111            > LINEAR_TOLERANCE * 10.0
112        {
113            closed_v = false;
114        }
115    }
116    Ok(SurfaceInfo {
117        surface,
118        u0,
119        u1,
120        v0,
121        v1,
122        closed_u,
123        closed_v,
124    })
125}
126
127fn fit(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
128    crate::projection::fit_parameter(value, minimum, maximum, closed)
129}
130
131
132#[derive(Clone, Copy)]
133struct IntersectionPoint {
134    ua: f64,
135    va: f64,
136    ub: f64,
137    vb: f64,
138    point: Vec3,
139}
140
141fn refine_point(
142    first: SurfaceInfo<'_>,
143    second: SurfaceInfo<'_>,
144    mut ua: f64,
145    mut va: f64,
146    mut ub: f64,
147    mut vb: f64,
148    tolerance: f64,
149) -> Result<Option<IntersectionPoint>, String> {
150    for _ in 0..40 {
151        let da = first.surface.derivatives(ua, va, 1)?;
152        let db = second.surface.derivatives(ub, vb, 1)?;
153        let residual = da[0][0].sub(db[0][0]);
154        if residual.length() <= tolerance * 0.01 + EPSILON {
155            return Ok(Some(IntersectionPoint {
156                ua,
157                va,
158                ub,
159                vb,
160                point: da[0][0].add(db[0][0]).scale(0.5),
161            }));
162        }
163        let columns = [
164            da[1][0],
165            da[0][1],
166            db[1][0].scale(-1.0),
167            db[0][1].scale(-1.0),
168        ];
169        let mut matrix = [[0.0f64; 3]; 3];
170        for column in columns {
171            let values = [column.x, column.y, column.z];
172            for row in 0..3 {
173                for col in 0..3 {
174                    matrix[row][col] += values[row] * values[col];
175                }
176            }
177        }
178        let lambda = match solve_small(matrix, [-residual.x, -residual.y, -residual.z], 3) {
179            Ok(value) => value,
180            Err(_) => return Ok(None),
181        };
182        let multiplier = Vec3::new(lambda[0], lambda[1], lambda[2]);
183        let mut changes = columns.map(|column| column.dot(multiplier));
184        let domains = [
185            first.u1 - first.u0,
186            first.v1 - first.v0,
187            second.u1 - second.u0,
188            second.v1 - second.v0,
189        ];
190        for index in 0..4 {
191            changes[index] = changes[index].clamp(-domains[index] / 4.0, domains[index] / 4.0);
192        }
193        ua = fit(ua + changes[0], first.u0, first.u1, first.closed_u);
194        va = fit(va + changes[1], first.v0, first.v1, first.closed_v);
195        ub = fit(ub + changes[2], second.u0, second.u1, second.closed_u);
196        vb = fit(vb + changes[3], second.v0, second.v1, second.closed_v);
197    }
198    let a = first.surface.evaluate(ua, va)?;
199    let b = second.surface.evaluate(ub, vb)?;
200    if a.sub(b).length() <= tolerance {
201        Ok(Some(IntersectionPoint {
202            ua,
203            va,
204            ub,
205            vb,
206            point: a.add(b).scale(0.5),
207        }))
208    } else {
209        Ok(None)
210    }
211}
212
213fn find_start_points(
214    first: SurfaceInfo<'_>,
215    second: SurfaceInfo<'_>,
216    tolerance: f64,
217    density: f64,
218) -> Result<Vec<IntersectionPoint>, String> {
219    let grid_count = |info: SurfaceInfo<'_>, direction_u: bool| {
220        let (knots, degree) = if direction_u {
221            (&info.surface.knots_u, info.surface.degree_u)
222        } else {
223            (&info.surface.knots_v, info.surface.degree_v)
224        };
225        (8.0_f64)
226            .max(((interior_knot_count(knots, degree) + 1) * (degree + 1)) as f64 * density)
227            .ceil()
228            .min(24.0) as usize
229    };
230    let nu = grid_count(first, true);
231    let nv = grid_count(first, false);
232    let first_box = Bounds::from_surface_controls(first.surface)?;
233    let second_box = Bounds::from_surface_controls(second.surface)?;
234    let gate = first_box.diagonal().min(second_box.diagonal()) * 0.15 + tolerance;
235    let expanded_second = second_box.expanded((tolerance * 100.0).max(gate));
236    let mut starts = Vec::new();
237    for i in 0..=nu {
238        for j in 0..=nv {
239            let ua = first.u0 + (first.u1 - first.u0) * i as f64 / nu as f64;
240            let va = first.v0 + (first.v1 - first.v0) * j as f64 / nv as f64;
241            let point = first.surface.evaluate(ua, va)?;
242            if !expanded_second.contains(point) {
243                continue;
244            }
245            let projection = project_point_to_surface(second.surface, point)?;
246            if projection.distance > gate {
247                continue;
248            }
249            if let Some(refined) =
250                refine_point(first, second, ua, va, projection.u, projection.v, tolerance)?
251            {
252                starts.push(refined);
253            }
254        }
255    }
256    Ok(starts)
257}
258
259/// One knot-span leaf of a carrier: the control box of the span (the patch
260/// lies in it, weights being positive) and the span's parametric centre.
261struct SpanLeaf {
262    bounds: Bounds,
263    centre: [f64; 2],
264}
265
266/// The knot-span leaves of a carrier (A4): one per non-empty span pair, each
267/// boxed by the `(p+1)×(q+1)` control points that influence it. A net whose
268/// span structure cannot be read is one leaf, the whole box.
269/// `BREP_SSI_SEPARATION_PREFILTER` (default on, `0` off): the boolean imprint
270/// culls a face pair whose carriers [`hull_sets_proved_apart`] before its
271/// classification and seeding.
272pub fn separation_prefilter_enabled() -> bool {
273    crate::switch!(live "BREP_SSI_SEPARATION_PREFILTER", true)
274}
275
276/// One knot span of a carrier: its control sub-net's points (the span lies in
277/// their convex hull when every weight is positive), their box, and the
278/// sub-net's corner normal (`None` where the corners do not span a plane).
279struct SpanHull {
280    bounds: Bounds,
281    points: Vec<Vec3>,
282    normal: Option<Vec3>,
283    /// The span's parameter box, `[u0, u1, v0, v1]`.
284    range: [f64; 4],
285    /// The span's homogeneous control net, `(p + 1) x (q + 1)` row-major:
286    /// its own Bezier patch once the carrier is in Bezier form.
287    net: Vec<Vec4>,
288    degrees: (usize, usize),
289}
290
291/// The hull of one Bezier patch's homogeneous net (`(p + 1) x (q + 1)`,
292/// row-major) over the parameter box `range`.
293fn hull_of_net(net: Vec<Vec4>, (p, q): (usize, usize), range: [f64; 4]) -> Option<SpanHull> {
294    let mut points = Vec::with_capacity(net.len());
295    let mut minimum = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
296    let mut maximum = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
297    for control in &net {
298        if !(control.w > 0.0) || !control.w.is_finite() {
299            return None;
300        }
301        let point = control.point().ok()?;
302        // A non-finite point bounds nothing: the hull is unreadable, so the
303        // pair is never proved apart on it.
304        if !(point.x.is_finite() && point.y.is_finite() && point.z.is_finite()) {
305            return None;
306        }
307        minimum = Vec3::new(minimum.x.min(point.x), minimum.y.min(point.y), minimum.z.min(point.z));
308        maximum = Vec3::new(maximum.x.max(point.x), maximum.y.max(point.y), maximum.z.max(point.z));
309        points.push(point);
310    }
311    let at = |r: usize, c: usize| points[r * (q + 1) + c];
312    let du = at(p, 0).add(at(p, q)).sub(at(0, 0)).sub(at(0, q));
313    let dv = at(0, q).add(at(p, q)).sub(at(0, 0)).sub(at(p, 0));
314    let normal = du.cross(dv).normalized().ok();
315    Some(SpanHull { bounds: Bounds { minimum, maximum }, points, normal, range, net, degrees: (p, q) })
316}
317
318/// A Bezier span's four quarters, split at its parameter middle both ways by
319/// de Casteljau on the homogeneous net (exact for a rational patch): the same
320/// patches a full-multiplicity middle knot inserted into the whole carrier
321/// gives, read from this span alone.
322fn quartered(hull: &SpanHull) -> Option<[SpanHull; 4]> {
323    let (p, q) = hull.degrees;
324    // Split a row of `n + 1` homogeneous points at t = 1/2.
325    let split = |row: &[Vec4]| -> (Vec<Vec4>, Vec<Vec4>) {
326        let mut work = row.to_vec();
327        let n = work.len() - 1;
328        let mut left = Vec::with_capacity(n + 1);
329        let mut right = vec![work[n]; n + 1];
330        left.push(work[0]);
331        right[n] = work[n];
332        for level in 1..=n {
333            for k in 0..=n - level {
334                // Halved before the sum: no overflow at extreme weights.
335                work[k] = work[k].scale(0.5).add(work[k + 1].scale(0.5));
336            }
337            left.push(work[0]);
338            right[n - level] = work[n - level];
339        }
340        (left, right)
341    };
342    // In u: split every column (u runs down the rows).
343    let mut low_u = vec![Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 }; (p + 1) * (q + 1)];
344    let mut high_u = low_u.clone();
345    for c in 0..=q {
346        let column: Vec<Vec4> = (0..=p).map(|r| hull.net[r * (q + 1) + c]).collect();
347        let (left, right) = split(&column);
348        for r in 0..=p {
349            low_u[r * (q + 1) + c] = left[r];
350            high_u[r * (q + 1) + c] = right[r];
351        }
352    }
353    // In v: split every row of each half.
354    let halves_v = |net: &[Vec4]| -> (Vec<Vec4>, Vec<Vec4>) {
355        let (mut low, mut high) = (Vec::with_capacity(net.len()), Vec::with_capacity(net.len()));
356        for r in 0..=p {
357            let (left, right) = split(&net[r * (q + 1)..(r + 1) * (q + 1)]);
358            low.extend(left);
359            high.extend(right);
360        }
361        (low, high)
362    };
363    let [u0, u1, v0, v1] = hull.range;
364    let (um, vm) = (0.5 * (u0 + u1), 0.5 * (v0 + v1));
365    let (a, b) = halves_v(&low_u);
366    let (c, d) = halves_v(&high_u);
367    Some([
368        hull_of_net(a, (p, q), [u0, um, v0, vm])?,
369        hull_of_net(b, (p, q), [u0, um, vm, v1])?,
370        hull_of_net(c, (p, q), [um, u1, v0, vm])?,
371        hull_of_net(d, (p, q), [um, u1, vm, v1])?,
372    ])
373}
374
375/// `BREP_SSI_SEPARATION_LOCAL_REFINE` (default on, `0` off): the prefilter's
376/// refinement quarters only the spans of its unproved pairs (de Casteljau on
377/// each span's own Bezier net) instead of halving every span of both whole
378/// carriers at each level. Off, a pair of 22 x 11-span lofted faces that touch
379/// along an edge (never provable) paid ~140 ms building ~15 000 span hulls per
380/// carrier by the third level.
381pub fn separation_local_refine_enabled() -> bool {
382    crate::switch!(live "BREP_SSI_SEPARATION_LOCAL_REFINE", true)
383}
384
385/// Every knot span's hull of `surface`, or `None` when a weight is not
386/// positive (the convex-hull property needs positive weights).
387fn span_hulls(surface: &NurbsSurface) -> Option<Vec<SpanHull>> {
388    let (p, q) = (surface.degree_u, surface.degree_v);
389    let rows = surface.control_points.len();
390    let columns = surface.control_points.first().map_or(0, Vec::len);
391    // A rectangular net whose knot vectors fit it, or nothing is read.
392    if rows == 0
393        || columns == 0
394        || surface.control_points.iter().any(|row| row.len() != columns)
395        || surface.knots_u.len() != rows + p + 1
396        || surface.knots_v.len() != columns + q + 1
397    {
398        return None;
399    }
400    if surface.control_points.iter().flatten().any(|control| !(control.w > 0.0) || !control.w.is_finite()) {
401        return None;
402    }
403    let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
404        (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
405    };
406    let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
407    let mut hulls = Vec::with_capacity(spans_u.len() * spans_v.len());
408    for &i in &spans_u {
409        for &j in &spans_v {
410            let net: Vec<Vec4> = surface.control_points[i - p..=i].iter().flat_map(|row| row[j - q..=j].iter().copied()).collect();
411            let range = [surface.knots_u[i], surface.knots_u[i + 1], surface.knots_v[j], surface.knots_v[j + 1]];
412            hulls.push(hull_of_net(net, (p, q), range)?);
413        }
414    }
415    (!hulls.is_empty()).then_some(hulls)
416}
417
418/// Whether `surface`'s net can be read span by span: rectangular, knot vectors
419/// that fit it, finite and non-decreasing, with at least one span each way.
420fn readable_net(surface: &NurbsSurface) -> bool {
421    let (p, q) = (surface.degree_u, surface.degree_v);
422    let rows = surface.control_points.len();
423    let columns = surface.control_points.first().map_or(0, Vec::len);
424    let knots_fit = |knots: &[f64], degree: usize, count: usize| {
425        knots.len() == count + degree + 1
426            && knots.iter().all(|knot| knot.is_finite())
427            && knots.windows(2).all(|pair| pair[0] <= pair[1])
428            && knots[0] < knots[knots.len() - 1]
429    };
430    rows > 0
431        && columns > 0
432        && surface.control_points.iter().all(|row| row.len() == columns)
433        && knots_fit(&surface.knots_u, p, rows)
434        && knots_fit(&surface.knots_v, q, columns)
435}
436
437/// `surface` in Bezier form: every interior knot raised to multiplicity
438/// `degree` (exact), so each span's control sub-net is that span's own
439/// Bezier net and its hull hugs the span (a B-spline span's sub-net reaches
440/// about `degree` spans either side).
441fn bezier_form(surface: &NurbsSurface) -> Option<NurbsSurface> {
442    if !readable_net(surface) {
443        return None;
444    }
445    let raise = |knots: &[f64], degree: usize| -> Vec<f64> {
446        let (first, last) = (knots[0], knots[knots.len() - 1]);
447        let mut inserted = Vec::new();
448        let mut index = 0;
449        while index < knots.len() {
450            let knot = knots[index];
451            let count = knots[index..].iter().take_while(|&&other| other == knot).count();
452            if knot > first && knot < last && count < degree {
453                inserted.extend(std::iter::repeat(knot).take(degree - count));
454            }
455            index += count;
456        }
457        inserted
458    };
459    let in_u = raise(&surface.knots_u, surface.degree_u);
460    let refined = if in_u.is_empty() { surface.clone() } else { surface.refine_knots(crate::KnotDirection::U, &in_u).ok()? };
461    let in_v = raise(&refined.knots_v, refined.degree_v);
462    if in_v.is_empty() { Some(refined) } else { refined.refine_knots(crate::KnotDirection::V, &in_v).ok() }
463}
464
465/// `surface` (in Bezier form) with a full-multiplicity knot at the middle of
466/// every span, both directions: the same surface on Bezier spans half as
467/// wide, whose hulls hug it four times closer.
468fn halved_spans(surface: &NurbsSurface) -> Option<NurbsSurface> {
469    let middles = |knots: &[f64], degree: usize| -> Vec<f64> {
470        knots
471            .windows(2)
472            .filter(|pair| pair[0] < pair[1])
473            .flat_map(|pair| std::iter::repeat(0.5 * (pair[0] + pair[1])).take(degree))
474            .collect()
475    };
476    let refined = surface.refine_knots(crate::KnotDirection::U, &middles(&surface.knots_u, surface.degree_u)).ok()?;
477    refined.refine_knots(crate::KnotDirection::V, &middles(&refined.knots_v, refined.degree_v)).ok()
478}
479
480/// Whether two carriers are PROVED apart by more than `margin`: every pair of
481/// knot spans, one of each, is separated by its control hulls' boxes or by a
482/// plane square to either span's corner normal or to the line between the
483/// hulls' centroids (a span lies in its control hull, so hulls apart by
484/// `margin` along any direction are surfaces apart). A span pair no direction
485/// separates is read again on both carriers with every span halved (exact
486/// knot insertion), its children only, up to three times while at most 64
487/// pairs remain. `false` when anything cannot be read, the span count is
488/// large, or a pair is still not proved apart: the march then runs as before.
489///
490/// Two neighbouring hob cutters (near-parallel lofted flanks a few tenths of
491/// a millimetre apart) seed and refine every overlapping leaf pair to
492/// nothing, because the boxes the seeder grows by a share of the carrier
493/// always overlap there; this test settles such a pair first.
494pub fn carriers_proved_apart(first: &NurbsSurface, second: &NurbsSurface, margin: f64) -> bool {
495    match (SpanHullSet::of(first), SpanHullSet::of(second)) {
496        (Some(a), Some(b)) => hull_sets_proved_apart(&a, &b, margin),
497        _ => false,
498    }
499}
500
501/// A carrier in Bezier form with its span hulls, built once per face so a
502/// face tested against many others ([`hull_sets_proved_apart`]) converts once.
503pub struct SpanHullSet {
504    surface: NurbsSurface,
505    hulls: Vec<SpanHull>,
506}
507
508impl SpanHullSet {
509    /// `None` when the carrier cannot be read (a weight not positive, a ragged
510    /// net): such a face is never proved apart.
511    pub fn of(surface: &NurbsSurface) -> Option<Self> {
512        let surface = bezier_form(surface)?;
513        let hulls = span_hulls(&surface)?;
514        Some(Self { surface, hulls })
515    }
516}
517
518/// [`carriers_proved_apart`] on two prepared hull sets.
519pub fn hull_sets_proved_apart(first: &SpanHullSet, second: &SpanHullSet, margin: f64) -> bool {
520    const PAIR_CAP: usize = 250_000;
521    // A pair that crosses leaves many span pairs unseparated at once: past
522    // this many the pair is given up at the first level, so a crossing pair
523    // pays a partial scan, not refinements.
524    const REFINE_CAP: usize = 64;
525    const LEVELS: usize = 3;
526    if first.hulls.len().saturating_mul(second.hulls.len()) > PAIR_CAP {
527        return false;
528    }
529    let (a, b) = (&first.hulls, &second.hulls);
530    let interval = |points: &[Vec3], normal: Vec3| {
531        points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
532            let value = point.dot(normal);
533            (low.min(value), high.max(value))
534        })
535    };
536    let centroid = |points: &[Vec3]| points.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, p| sum.add(*p)).scale(1.0 / points.len() as f64);
537    let apart = |hull_a: &SpanHull, hull_b: &SpanHull| {
538        if !hull_a.bounds.intersects(hull_b.bounds, margin) {
539            return true;
540        }
541        // The spans' own normals, then the line between the hulls' centroids.
542        let between = centroid(&hull_b.points).sub(centroid(&hull_a.points)).normalized().ok();
543        [hull_a.normal, hull_b.normal, between].into_iter().flatten().any(|normal| {
544            let (low_a, high_a) = interval(&hull_a.points, normal);
545            let (low_b, high_b) = interval(&hull_b.points, normal);
546            low_a > high_b + margin || low_b > high_a + margin
547        })
548    };
549    let mut unproved: Vec<(usize, usize)> = Vec::new();
550    for (ia, hull_a) in a.iter().enumerate() {
551        for (ib, hull_b) in b.iter().enumerate() {
552            if !apart(hull_a, hull_b) {
553                unproved.push((ia, ib));
554                if unproved.len() > REFINE_CAP {
555                    return false;
556                }
557            }
558        }
559    }
560    if separation_local_refine_enabled() {
561        // Each level's hulls are the quarters of the previous level's unproved
562        // spans only; a pair's children are its spans' quarters.
563        let mut level_a: Vec<SpanHull> = Vec::new();
564        let mut level_b: Vec<SpanHull> = Vec::new();
565        let mut first_level = true;
566        for _ in 0..LEVELS {
567            if unproved.is_empty() {
568                break;
569            }
570            let (parents_a, parents_b): (&[SpanHull], &[SpanHull]) =
571                if first_level { (a, b) } else { (&level_a, &level_b) };
572            let mut quarters_a: HashMap<usize, usize> = HashMap::new();
573            let mut quarters_b: HashMap<usize, usize> = HashMap::new();
574            let (mut next_a, mut next_b): (Vec<SpanHull>, Vec<SpanHull>) = (Vec::new(), Vec::new());
575            let mut next: Vec<(usize, usize)> = Vec::new();
576            for &(ia, ib) in &unproved {
577                let start_a = match quarters_a.get(&ia) {
578                    Some(&start) => start,
579                    None => {
580                        let Some(children) = quartered(&parents_a[ia]) else { return false };
581                        let start = next_a.len();
582                        next_a.extend(children);
583                        quarters_a.insert(ia, start);
584                        start
585                    }
586                };
587                let start_b = match quarters_b.get(&ib) {
588                    Some(&start) => start,
589                    None => {
590                        let Some(children) = quartered(&parents_b[ib]) else { return false };
591                        let start = next_b.len();
592                        next_b.extend(children);
593                        quarters_b.insert(ib, start);
594                        start
595                    }
596                };
597                for ka in start_a..start_a + 4 {
598                    for kb in start_b..start_b + 4 {
599                        if !apart(&next_a[ka], &next_b[kb]) {
600                            next.push((ka, kb));
601                            if next.len() > REFINE_CAP {
602                                return false;
603                            }
604                        }
605                    }
606                }
607            }
608            next.sort_unstable();
609            next.dedup();
610            unproved = next;
611            level_a = next_a;
612            level_b = next_b;
613            first_level = false;
614        }
615        if std::env::var_os("BREP_DEBUG_SEPARATION").is_some() {
616            eprintln!("separation (local): unproved after refinement {}", unproved.len());
617        }
618        return unproved.is_empty();
619    }
620    // Each refinement level owns its carriers and hulls; level 0 is the
621    // prepared sets.
622    let within = |child: &[f64; 4], parent: &[f64; 4]| child[0] >= parent[0] && child[1] <= parent[1] && child[2] >= parent[2] && child[3] <= parent[3];
623    let mut levels: Vec<(NurbsSurface, NurbsSurface, Vec<SpanHull>, Vec<SpanHull>)> = Vec::new();
624    for _ in 0..LEVELS {
625        if unproved.is_empty() {
626            break;
627        }
628        let (surface_a, surface_b, parents_a, parents_b) = match levels.last() {
629            Some((sa, sb, ha, hb)) => (sa, sb, ha.as_slice(), hb.as_slice()),
630            None => (&first.surface, &second.surface, a.as_slice(), b.as_slice()),
631        };
632        let (Some(next_a), Some(next_b)) = (halved_spans(surface_a), halved_spans(surface_b)) else { return false };
633        let (Some(hulls_a), Some(hulls_b)) = (span_hulls(&next_a), span_hulls(&next_b)) else { return false };
634        let mut next: Vec<(usize, usize)> = Vec::new();
635        for &(ia, ib) in &unproved {
636            let children_a: Vec<usize> = (0..hulls_a.len()).filter(|&k| within(&hulls_a[k].range, &parents_a[ia].range)).collect();
637            let children_b: Vec<usize> = (0..hulls_b.len()).filter(|&k| within(&hulls_b[k].range, &parents_b[ib].range)).collect();
638            for &ka in &children_a {
639                for &kb in &children_b {
640                    if !apart(&hulls_a[ka], &hulls_b[kb]) {
641                        next.push((ka, kb));
642                        if next.len() > REFINE_CAP {
643                            return false;
644                        }
645                    }
646                }
647            }
648        }
649        next.sort_unstable();
650        next.dedup();
651        unproved = next;
652        levels.push((next_a, next_b, hulls_a, hulls_b));
653    }
654    if std::env::var_os("BREP_DEBUG_SEPARATION").is_some() {
655        let (a, b) = match levels.last() {
656            Some((_, _, ha, hb)) => (ha.as_slice(), hb.as_slice()),
657            None => (a.as_slice(), b.as_slice()),
658        };
659        eprintln!("separation: spans {}x{} unproved after refinement {}", a.len(), b.len(), unproved.len());
660    }
661    unproved.is_empty()
662}
663
664fn span_leaves(info: SurfaceInfo<'_>) -> Result<Vec<SpanLeaf>, String> {
665    let surface = info.surface;
666    let (p, q) = (surface.degree_u, surface.degree_v);
667    let rows = surface.control_points.len();
668    let columns = surface.control_points.first().map_or(0, Vec::len);
669    let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
670        (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
671    };
672    let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
673    if spans_u.is_empty() || spans_v.is_empty() {
674        return Ok(vec![SpanLeaf {
675            bounds: Bounds::from_surface_controls(surface)?,
676            centre: [0.5 * (info.u0 + info.u1), 0.5 * (info.v0 + info.v1)],
677        }]);
678    }
679    let mut leaves = Vec::with_capacity(spans_u.len() * spans_v.len());
680    for &i in &spans_u {
681        for &j in &spans_v {
682            let mut minimum = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
683            let mut maximum = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
684            for row in &surface.control_points[i - p..=i] {
685                for control in &row[j - q..=j] {
686                    let point = control.point()?;
687                    minimum.x = minimum.x.min(point.x);
688                    minimum.y = minimum.y.min(point.y);
689                    minimum.z = minimum.z.min(point.z);
690                    maximum.x = maximum.x.max(point.x);
691                    maximum.y = maximum.y.max(point.y);
692                    maximum.z = maximum.z.max(point.z);
693                }
694            }
695            leaves.push(SpanLeaf {
696                bounds: Bounds { minimum, maximum },
697                centre: [
698                    0.5 * (surface.knots_u[i] + surface.knots_u[i + 1]),
699                    0.5 * (surface.knots_v[j] + surface.knots_v[j + 1]),
700                ],
701            });
702        }
703    }
704    Ok(leaves)
705}
706
707/// Above this many overlapping leaf pairs the tree seeding hands back to the
708/// grid: two dense nets that overlap everywhere would otherwise refine tens
709/// of thousands of candidates where the grid's few hundred find the same
710/// curves.
711const TREE_SEED_PAIR_CAP: usize = 4096;
712
713/// A4: interior start candidates from the two carriers' knot-span leaves.
714/// For every pair of leaves whose boxes overlap (each grown by the same gate
715/// the grid uses) two candidates are refined onto both carriers: the first
716/// leaf's parametric centre projected onto the second carrier from the second
717/// leaf's centre, and the converse. `None` when the pair count is over
718/// [`TREE_SEED_PAIR_CAP`], which the caller answers with the grid.
719fn tree_start_points(
720    first: SurfaceInfo<'_>,
721    second: SurfaceInfo<'_>,
722    tolerance: f64,
723) -> Result<Option<(Vec<IntersectionPoint>, usize)>, String> {
724    let first_box = Bounds::from_surface_controls(first.surface)?;
725    let second_box = Bounds::from_surface_controls(second.surface)?;
726    let gate = first_box.diagonal().min(second_box.diagonal()) * 0.15 + tolerance;
727    let grow = (tolerance * 100.0).max(gate);
728    let leaves_a = span_leaves(first)?;
729    let leaves_b = span_leaves(second)?;
730    let mut pairs = Vec::new();
731    for (ia, leaf_a) in leaves_a.iter().enumerate() {
732        for (ib, leaf_b) in leaves_b.iter().enumerate() {
733            if leaf_a.bounds.intersects(leaf_b.bounds, grow) {
734                pairs.push((ia, ib));
735                if pairs.len() > TREE_SEED_PAIR_CAP {
736                    return Ok(None);
737                }
738            }
739        }
740    }
741    let mut starts = Vec::new();
742    for (ia, ib) in &pairs {
743        let (leaf_a, leaf_b) = (&leaves_a[*ia], &leaves_b[*ib]);
744        // A leaf's centre is at most a leaf diagonal from anything in its
745        // box, so a candidate that far from the other carrier is still the
746        // pair's own and is refined; the grid's gate (a fraction of the
747        // whole carrier) would drop every candidate of a leaf pair smaller
748        // than it — a sphere of radius `0.005 L` on an `L` sheet.
749        let reach = gate.max(leaf_a.bounds.diagonal().max(leaf_b.bounds.diagonal()));
750        // The first leaf's centre onto the second carrier, seeded from the
751        // second leaf's centre; then the converse.
752        for (from, onto, from_info, onto_info, from_first) in [
753            (leaf_a, leaf_b, first, second, true),
754            (leaf_b, leaf_a, second, first, false),
755        ] {
756            let point = from_info.surface.evaluate(from.centre[0], from.centre[1])?;
757            let projection = project_point_to_surface_from_seed(onto_info.surface, point, onto.centre)?;
758            if projection.distance > reach {
759                continue;
760            }
761            let refined = if from_first {
762                refine_point(first, second, from.centre[0], from.centre[1], projection.u, projection.v, tolerance)?
763            } else {
764                refine_point(first, second, projection.u, projection.v, from.centre[0], from.centre[1], tolerance)?
765            };
766            if let Some(refined) = refined {
767                starts.push(refined);
768            }
769        }
770    }
771    Ok(Some((starts, pairs.len())))
772}
773
774/// Whether the two carriers CROSS at `point` (`|n_a × n_b|` at or above
775/// [`TRANSVERSE_START_CROSS`]) rather than touch tangentially; a surface
776/// with no normal there counts as not crossing.
777fn transverse_at(
778    first: SurfaceInfo<'_>,
779    second: SurfaceInfo<'_>,
780    point: IntersectionPoint,
781) -> bool {
782    crossing_at(first, second, point) >= TRANSVERSE_START_CROSS
783}
784
785/// `|n_a × n_b|` at `point`; zero where either carrier has no normal there.
786fn crossing_at(
787    first: SurfaceInfo<'_>,
788    second: SurfaceInfo<'_>,
789    point: IntersectionPoint,
790) -> f64 {
791    match (
792        first.surface.normal(point.ua, point.va),
793        second.surface.normal(point.ub, point.vb),
794    ) {
795        (Ok(a), Ok(b)) => a.cross(b).length(),
796        _ => 0.0,
797    }
798}
799
800fn tangent_at(
801    first: SurfaceInfo<'_>,
802    second: SurfaceInfo<'_>,
803    point: IntersectionPoint,
804) -> Result<Option<Vec3>, String> {
805    let first_normal = first.surface.normal(point.ua, point.va).ok();
806    let second_normal = second.surface.normal(point.ub, point.vb).ok();
807    match (first_normal, second_normal) {
808        (Some(a), Some(b)) => {
809            let tangent = a.cross(b);
810            if tangent.length() <= 1e-9 {
811                Ok(None)
812            } else {
813                Ok(Some(tangent.normalized()?))
814            }
815        }
816        _ => Ok(None),
817    }
818}
819
820fn polish_boundary(
821    first: SurfaceInfo<'_>,
822    second: SurfaceInfo<'_>,
823    mut point: IntersectionPoint,
824    tolerance: f64,
825) -> Result<Option<IntersectionPoint>, String> {
826    let free = [
827        first.closed_u || (point.ua > first.u0 && point.ua < first.u1),
828        first.closed_v || (point.va > first.v0 && point.va < first.v1),
829        second.closed_u || (point.ub > second.u0 && point.ub < second.u1),
830        second.closed_v || (point.vb > second.v0 && point.vb < second.v1),
831    ];
832    for _ in 0..40 {
833        let da = first.surface.derivatives(point.ua, point.va, 1)?;
834        let db = second.surface.derivatives(point.ub, point.vb, 1)?;
835        let residual = da[0][0].sub(db[0][0]);
836        if residual.length() <= tolerance {
837            point.point = da[0][0].add(db[0][0]).scale(0.5);
838            return Ok(Some(point));
839        }
840        let all_columns = [
841            da[1][0],
842            da[0][1],
843            db[1][0].scale(-1.0),
844            db[0][1].scale(-1.0),
845        ];
846        let indices: Vec<usize> = (0..4).filter(|index| free[*index]).collect();
847        if indices.is_empty() {
848            return Ok(None);
849        }
850        let mut matrix = [[0.0f64; 4]; 4];
851        let mut rhs = [0.0f64; 4];
852        for (row, &r) in indices.iter().enumerate() {
853            rhs[row] = -all_columns[r].dot(residual);
854            for (column, &c) in indices.iter().enumerate() {
855                matrix[row][column] = all_columns[r].dot(all_columns[c]);
856            }
857        }
858        let changes = match solve_small(matrix, rhs, indices.len()) {
859            Ok(value) => value,
860            Err(_) => return Ok(None),
861        };
862        let mut update = [0.0; 4];
863        for (index, &parameter_index) in indices.iter().enumerate() {
864            update[parameter_index] = changes[index];
865        }
866        point.ua = fit(point.ua + update[0], first.u0, first.u1, first.closed_u);
867        point.va = fit(point.va + update[1], first.v0, first.v1, first.closed_v);
868        point.ub = fit(point.ub + update[2], second.u0, second.u1, second.closed_u);
869        point.vb = fit(point.vb + update[3], second.v0, second.v1, second.closed_v);
870    }
871    Ok(None)
872}
873
874fn correct(
875    first: SurfaceInfo<'_>,
876    second: SurfaceInfo<'_>,
877    from: IntersectionPoint,
878    predicted: Vec3,
879    tangent: Vec3,
880    tolerance: f64,
881) -> Result<Option<(IntersectionPoint, bool)>, String> {
882    let mut point = from;
883    let mut boundary = false;
884    for _ in 0..30 {
885        let da = first.surface.derivatives(point.ua, point.va, 1)?;
886        let db = second.surface.derivatives(point.ub, point.vb, 1)?;
887        let residual = da[0][0].sub(db[0][0]);
888        let plane_residual = da[0][0].sub(predicted).dot(tangent);
889        if residual.length() <= tolerance * 0.01 + EPSILON
890            && plane_residual.abs() <= tolerance * 0.01 + EPSILON
891        {
892            point.point = da[0][0].add(db[0][0]).scale(0.5);
893            return Ok(Some((point, boundary)));
894        }
895        let matrix = [
896            [da[1][0].x, da[0][1].x, -db[1][0].x, -db[0][1].x],
897            [da[1][0].y, da[0][1].y, -db[1][0].y, -db[0][1].y],
898            [da[1][0].z, da[0][1].z, -db[1][0].z, -db[0][1].z],
899            [da[1][0].dot(tangent), da[0][1].dot(tangent), 0.0, 0.0],
900        ];
901        let changes = match solve_small(
902            matrix,
903            [-residual.x, -residual.y, -residual.z, -plane_residual],
904            4,
905        ) {
906            Ok(value) => value,
907            Err(_) => return Ok(None),
908        };
909        let scale = [
910            changes[0].abs() / ((first.u1 - first.u0) / 4.0),
911            changes[1].abs() / ((first.v1 - first.v0) / 4.0),
912            changes[2].abs() / ((second.u1 - second.u0) / 4.0),
913            changes[3].abs() / ((second.v1 - second.v0) / 4.0),
914            1.0,
915        ]
916        .into_iter()
917        .fold(1.0_f64, f64::max);
918        let raw = [
919            point.ua + changes[0] / scale,
920            point.va + changes[1] / scale,
921            point.ub + changes[2] / scale,
922            point.vb + changes[3] / scale,
923        ];
924        let domains = [
925            (first.u0, first.u1, first.closed_u),
926            (first.v0, first.v1, first.closed_v),
927            (second.u0, second.u1, second.closed_u),
928            (second.v0, second.v1, second.closed_v),
929        ];
930        boundary = false;
931        let mut next = [0.0; 4];
932        for index in 0..4 {
933            next[index] = fit(
934                raw[index],
935                domains[index].0,
936                domains[index].1,
937                domains[index].2,
938            );
939            if !domains[index].2
940                && (next[index] == domains[index].0 || next[index] == domains[index].1)
941                && raw[index] != next[index]
942            {
943                boundary = true;
944            }
945        }
946        let old = [point.ua, point.va, point.ub, point.vb];
947        let spans = [
948            first.u1 - first.u0,
949            first.v1 - first.v0,
950            second.u1 - second.u0,
951            second.v1 - second.v0,
952        ];
953        let stalled = (0..4).all(|index| (next[index] - old[index]).abs() <= 1e-14 * spans[index]);
954        point.ua = next[0];
955        point.va = next[1];
956        point.ub = next[2];
957        point.vb = next[3];
958        if stalled {
959            if boundary {
960                if let Some(polished) = polish_boundary(first, second, point, tolerance)? {
961                    return Ok(Some((polished, true)));
962                }
963            }
964            return Ok(None);
965        }
966    }
967    Ok(None)
968}
969
970struct Trace {
971    points: Vec<IntersectionPoint>,
972    /// One unit tangent per point, along the trace direction.
973    tangents: Vec<Vec3>,
974    closed: bool,
975    /// The largest span deviation measured, `0.0` when none was asked for.
976    deviation: f64,
977}
978
979/// A branch assembled from its traces: stations, one tangent per station
980/// along the branch, and the largest span deviation either trace measured.
981struct Spliced {
982    points: Vec<IntersectionPoint>,
983    tangents: Vec<Vec3>,
984    deviation: f64,
985}
986
987impl From<Trace> for Spliced {
988    fn from(trace: Trace) -> Self {
989        Self {
990            points: trace.points,
991            tangents: trace.tangents,
992            deviation: trace.deviation,
993        }
994    }
995}
996
997/// `reverse(backward[1..]) ++ forward`: the backward trace walked the other
998/// way, so its tangents are negated to run along the branch.
999fn splice(backward: Trace, forward: Trace) -> Spliced {
1000    let mut points: Vec<_> = backward.points.into_iter().skip(1).rev().collect();
1001    let mut tangents: Vec<_> = backward
1002        .tangents
1003        .into_iter()
1004        .skip(1)
1005        .rev()
1006        .map(|tangent| tangent.scale(-1.0))
1007        .collect();
1008    points.extend(forward.points);
1009    tangents.extend(forward.tangents);
1010    Spliced {
1011        points,
1012        tangents,
1013        deviation: backward.deviation.max(forward.deviation),
1014    }
1015}
1016
1017/// Preserve complete tangents for UV reuse without asking the marcher to
1018/// measure or change its spans. Deviation remains absent unless measured.
1019fn curve_from(all: Spliced, closed: bool, measured: bool) -> SurfaceIntersectionCurve {
1020    let complete = all.tangents.len() == all.points.len();
1021    SurfaceIntersectionCurve {
1022        points: all.points.iter().map(|point| point.point).collect(),
1023        params_a: all.points.iter().map(|point| [point.ua, point.va]).collect(),
1024        params_b: all.points.iter().map(|point| [point.ub, point.vb]).collect(),
1025        closed,
1026        tangents: (complete && (measured || (crate::carried_uv::carried_uv_enabled() && all.points.len() >= crate::carried_uv::carried_uv_min_stations()))).then_some(all.tangents),
1027        span_deviation: (complete && measured).then_some(all.deviation),
1028        tangent: false,
1029    }
1030}
1031
1032/// The cubic Hermite through `p0` and `p1` with end derivatives `d0`, `d1`,
1033/// at `s` in `[0, 1]`.
1034fn hermite_at(p0: Vec3, d0: Vec3, p1: Vec3, d1: Vec3, s: f64) -> Vec3 {
1035    let s2 = s * s;
1036    let s3 = s2 * s;
1037    p0.scale(2.0 * s3 - 3.0 * s2 + 1.0)
1038        .add(d0.scale(s3 - 2.0 * s2 + s))
1039        .add(p1.scale(-2.0 * s3 + 3.0 * s2))
1040        .add(d1.scale(s3 - s2))
1041}
1042
1043/// A cubic Hermite in one carrier's parameter plane between two stations:
1044/// end parameters, and end derivatives that are the least-squares images of
1045/// the chord-scaled 3D tangents through `[S_u S_v]`. Closed directions are
1046/// unwrapped so the Hermite runs the short way round; [`fit`] wraps the
1047/// samples back.
1048struct ParameterHermite {
1049    p0: [f64; 2],
1050    d0: [f64; 2],
1051    p1: [f64; 2],
1052    d1: [f64; 2],
1053}
1054
1055impl ParameterHermite {
1056    fn new(
1057        info: SurfaceInfo<'_>,
1058        p0: [f64; 2],
1059        t0: Vec3,
1060        p1: [f64; 2],
1061        t1: Vec3,
1062        chord: f64,
1063    ) -> Result<Self, String> {
1064        let image = |uv: [f64; 2], tangent: Vec3| -> Result<[f64; 2], String> {
1065            let d = info.surface.derivatives(uv[0], uv[1], 1)?;
1066            let (su, sv) = (d[1][0], d[0][1]);
1067            let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv));
1068            let (bu, bv) = (su.dot(tangent), sv.dot(tangent));
1069            let det = e * g - f * f;
1070            if det.abs() <= EPSILON * (1.0 + e * g) {
1071                return Ok([0.0, 0.0]);
1072            }
1073            Ok([
1074                (g * bu - f * bv) / det * chord,
1075                (e * bv - f * bu) / det * chord,
1076            ])
1077        };
1078        let mut p1 = p1;
1079        let unwrap = |value: f64, near: f64, closed: bool, minimum: f64, maximum: f64| {
1080            let period = maximum - minimum;
1081            if closed && period > 0.0 && (value - near).abs() > 0.5 * period {
1082                value - period * ((value - near) / period).round()
1083            } else {
1084                value
1085            }
1086        };
1087        p1[0] = unwrap(p1[0], p0[0], info.closed_u, info.u0, info.u1);
1088        p1[1] = unwrap(p1[1], p0[1], info.closed_v, info.v0, info.v1);
1089        Ok(Self {
1090            p0,
1091            d0: image(p0, t0)?,
1092            p1,
1093            d1: image([fit(p1[0], info.u0, info.u1, info.closed_u), fit(p1[1], info.v0, info.v1, info.closed_v)], t1)?,
1094        })
1095    }
1096
1097    fn at(&self, s: f64) -> [f64; 2] {
1098        let s2 = s * s;
1099        let s3 = s2 * s;
1100        let (h00, h10, h01, h11) = (
1101            2.0 * s3 - 3.0 * s2 + 1.0,
1102            s3 - 2.0 * s2 + s,
1103            -2.0 * s3 + 3.0 * s2,
1104            s3 - s2,
1105        );
1106        [
1107            h00 * self.p0[0] + h10 * self.d0[0] + h01 * self.p1[0] + h11 * self.d1[0],
1108            h00 * self.p0[1] + h10 * self.d0[1] + h01 * self.p1[1] + h11 * self.d1[1],
1109        ]
1110    }
1111}
1112
1113/// It is what the emitted span would miss by if the stations were
1114/// interpolated with these tangents, measured against the carriers
1115/// themselves, which no test on the stations alone can see.
1116fn span_deviation(
1117    first: SurfaceInfo<'_>,
1118    second: SurfaceInfo<'_>,
1119    from: IntersectionPoint,
1120    from_tangent: Vec3,
1121    to: IntersectionPoint,
1122    to_tangent: Vec3,
1123) -> Result<f64, String> {
1124    let chord = to.point.sub(from.point).length();
1125    if chord <= EPSILON {
1126        return Ok(0.0);
1127    }
1128    let on_a = ParameterHermite::new(first, [from.ua, from.va], from_tangent, [to.ua, to.va], to_tangent, chord)?;
1129    let on_b = ParameterHermite::new(second, [from.ub, from.vb], from_tangent, [to.ub, to.vb], to_tangent, chord)?;
1130    let (d0, d1) = (from_tangent.scale(chord), to_tangent.scale(chord));
1131    let mut worst: f64 = 0.0;
1132    for s in [0.17, 0.33, 0.5, 0.67, 0.83] {
1133        let c = hermite_at(from.point, d0, to.point, d1, s);
1134        let [ua, va] = on_a.at(s);
1135        let a = first.surface.evaluate(fit(ua, first.u0, first.u1, first.closed_u), fit(va, first.v0, first.v1, first.closed_v))?;
1136        let [ub, vb] = on_b.at(s);
1137        let b = second.surface.evaluate(fit(ub, second.u0, second.u1, second.closed_u), fit(vb, second.v0, second.v1, second.closed_v))?;
1138        worst = worst
1139            .max(a.sub(b).length())
1140            .max(a.sub(c).length())
1141            .max(b.sub(c).length());
1142    }
1143    Ok(worst)
1144}
1145
1146fn vector_angle(a: Vec3, b: Vec3) -> f64 {
1147    (a.dot(b) / (a.length() * b.length()))
1148        .clamp(-1.0, 1.0)
1149        .acos()
1150}
1151
1152/// Predictive step size from the surface-normal turn budget (Golovanov
1153/// §4.12): for each parameter of each surface the permissible parametric
1154/// step is Δα·√g/b (g, b = first/second fundamental form coefficients);
1155/// its 3D advance is Δα·g/b, and the usable step is the smallest advance
1156/// PROJECTED onto the march direction (the displacement sphere of §4.8),
1157/// ignoring parameters that barely move along the curve.  Returns None
1158/// when curvature data is unavailable (degenerate normals) — the caller
1159/// keeps its reactive step then.
1160fn normal_turn_step(
1161    first: SurfaceInfo<'_>,
1162    second: SurfaceInfo<'_>,
1163    point: IntersectionPoint,
1164    tangent: Vec3,
1165    budget: f64,
1166) -> Option<f64> {
1167    let mut best: Option<f64> = None;
1168    for (surface, u, v) in [
1169        (first.surface, point.ua, point.va),
1170        (second.surface, point.ub, point.vb),
1171    ] {
1172        let derivatives = surface.derivatives(u, v, 2).ok()?;
1173        let normal = derivatives[1][0].cross(derivatives[0][1]);
1174        let normal_length = normal.length();
1175        if normal_length <= 1e-12 {
1176            continue;
1177        }
1178        let unit_normal = normal.scale(1.0 / normal_length);
1179        for (first_derivative, second_derivative) in [
1180            (derivatives[1][0], derivatives[2][0]),
1181            (derivatives[0][1], derivatives[0][2]),
1182        ] {
1183            let metric = first_derivative.dot(first_derivative);
1184            if metric <= 1e-16 {
1185                continue;
1186            }
1187            let curvature = second_derivative.dot(unit_normal).abs();
1188            if curvature <= 1e-12 {
1189                continue; // flat along this parameter: no budget limit
1190            }
1191            let advance = budget * metric / curvature;
1192            let alignment = first_derivative
1193                .scale(1.0 / metric.sqrt())
1194                .dot(tangent)
1195                .abs();
1196            if alignment <= 0.1 {
1197                continue; // barely moves along the curve (§4.8)
1198            }
1199            let along = advance * alignment;
1200            if best.map(|value| along < value).unwrap_or(true) {
1201                best = Some(along);
1202            }
1203        }
1204    }
1205    best
1206}
1207
1208/// The switches a trace reads, taken from the environment once per
1209/// intersection call rather than once per trace.
1210#[derive(Clone, Copy)]
1211struct TraceSwitches {
1212    /// `BREP_SSI_FIRST_STEP_BUDGET=0` lets the first step skip the §4.12
1213    /// ceiling, as every trace did before 2026-09-15.
1214    first_step_ceiling: bool,
1215    /// `BREP_DEBUG_SSI_TRACE=1`: every start and every accepted station.
1216    debug: bool,
1217}
1218
1219impl TraceSwitches {
1220    fn from_env() -> Self {
1221        Self {
1222            first_step_ceiling: std::env::var("BREP_SSI_FIRST_STEP_BUDGET").as_deref() != Ok("0"),
1223            debug: std::env::var_os("BREP_DEBUG_SSI_TRACE").is_some(),
1224        }
1225    }
1226}
1227
1228#[allow(clippy::too_many_arguments)]
1229fn trace(
1230    first: SurfaceInfo<'_>,
1231    second: SurfaceInfo<'_>,
1232    start: IntersectionPoint,
1233    direction: f64,
1234    tolerance: f64,
1235    initial_step: f64,
1236    minimum_step: f64,
1237    maximum_step: f64,
1238    maximum_steps: usize,
1239    switches: TraceSwitches,
1240    span_budget: Option<f64>,
1241) -> Result<Trace, String> {
1242    let mut points = vec![start];
1243    let mut current = start;
1244    let Some(mut tangent) = tangent_at(first, second, start)? else {
1245        return Ok(Trace {
1246            points,
1247            tangents: Vec::new(),
1248            closed: false,
1249            deviation: 0.0,
1250        });
1251    };
1252    tangent = tangent.scale(direction);
1253    let mut tangents = vec![tangent];
1254    let mut deviation: f64 = 0.0;
1255    // The FIRST step is held to the same §4.12 normal-turn ceiling as every
1256    // later one. The ceiling used to be applied only after a step was accepted,
1257    // so step zero was `diagonal / 100` whatever the curvature — and a step
1258    // that lands on a trim-window boundary ends the branch before the turn
1259    // check below ever reads it. On the rescue pair
1260    // (`boolean_fuzz_corpus/23_section_pcurve_fold_t222`, cone × a 90° pin-wall
1261    // window) that one step was the whole 0.69 and 0.77 of section, turning the
1262    // tangent 0.97 rad where the ceiling allows 1.0e-2 of advance: two
1263    // stations, a four-point fit, and trims 3.0e-2 and 3.8e-2 apart. Escape
1264    // hatch: BREP_SSI_FIRST_STEP_BUDGET=0.
1265    let mut step_size = initial_step.min(maximum_step);
1266    if switches.first_step_ceiling {
1267        if let Some(budget) = normal_turn_step(first, second, start, tangent, 0.1) {
1268            step_size = step_size.min(budget).clamp(minimum_step, maximum_step);
1269        }
1270    }
1271    let mut terminated = false;
1272    for _ in 0..maximum_steps {
1273        let mut accepted = None;
1274        while step_size >= minimum_step {
1275            let predicted = current.point.add(tangent.scale(step_size));
1276            if let Some((corrected, boundary)) =
1277                correct(first, second, current, predicted, tangent, tolerance)?
1278            {
1279                if corrected.point.sub(current.point).length() <= 2.5 * step_size {
1280                    accepted = Some((corrected, boundary));
1281                    break;
1282                }
1283            }
1284            step_size /= 2.0;
1285        }
1286        let Some((candidate, boundary)) = accepted else {
1287            terminated = true;
1288            break;
1289        };
1290        points.push(candidate);
1291        if switches.debug {
1292            // One line per accepted station: the tangent's turn across the
1293            // step, the normal-turn ceiling where it started, the step asked
1294            // for and the distance actually covered.
1295            let turn = tangent_at(first, second, candidate)
1296                .ok()
1297                .flatten()
1298                .map(|next| vector_angle(tangent, if next.dot(tangent) < 0.0 { next.scale(-1.0) } else { next }))
1299                .unwrap_or(f64::NAN);
1300            let budget = normal_turn_step(first, second, current, tangent, 0.1).unwrap_or(f64::NAN);
1301            let at = candidate.point;
1302            eprintln!(
1303                "SSI-TRACE dir {direction} step {step_size:.4e} jump {:.4e} turn {turn:.4} ceiling {budget:.4e} boundary {boundary} p ({:.6},{:.6},{:.6})",
1304                at.sub(current.point).length(),
1305                at.x,
1306                at.y,
1307                at.z
1308            );
1309        }
1310        // A station that ends the trace still gets a tangent (its own where
1311        // one exists, else the previous one carried forward), so the tangent
1312        // list stays parallel to the stations.
1313        let next = tangent_at(first, second, candidate)?.map(|next| {
1314            if next.dot(tangent) < 0.0 { next.scale(-1.0) } else { next }
1315        });
1316        if boundary {
1317            tangents.push(next.unwrap_or(tangent));
1318            terminated = true;
1319            break;
1320        }
1321        let Some(next_tangent) = next else {
1322            tangents.push(tangent);
1323            terminated = true;
1324            break;
1325        };
1326        let angle = vector_angle(tangent, next_tangent);
1327        if angle > 0.35 {
1328            points.pop();
1329            step_size = minimum_step.max(step_size / 2.0);
1330            if step_size <= minimum_step * 1.01 {
1331                points.push(candidate);
1332            } else {
1333                continue;
1334            }
1335        }
1336        // The span test (A1): the span between `current` and `candidate`
1337        // is measured against both carriers; over budget, it is re-stepped
1338        // at half the step, like a turn over 0.35, and accepted at the
1339        // minimum step regardless.
1340        let mut span_fine = true;
1341        if let Some(budget) = span_budget {
1342            let measured = span_deviation(first, second, current, tangent, candidate, next_tangent)?;
1343            if measured > budget && step_size > minimum_step * 1.01 {
1344                points.pop();
1345                step_size = minimum_step.max(step_size / 2.0);
1346                continue;
1347            }
1348            deviation = deviation.max(measured);
1349            span_fine = measured < budget / 8.0;
1350        }
1351        tangents.push(next_tangent);
1352        // §4.12 normal-turn budget on BOTH surfaces as a hard CEILING on
1353        // the reactive controller: growth stays reactive (accelerating
1354        // into under-sampled flats regressed downstream curve fits), but
1355        // the budget stops the step from outrunning surface curvature.
1356        let reactive = if angle < 0.03 && span_fine {
1357            step_size * 1.5
1358        } else if angle > 0.15 {
1359            step_size * 0.6
1360        } else {
1361            step_size
1362        };
1363        step_size = match normal_turn_step(first, second, candidate, next_tangent, 0.1) {
1364            Some(budget) => reactive.min(budget),
1365            None => reactive,
1366        }
1367        .clamp(minimum_step, maximum_step);
1368        if points.len() > 4 && candidate.point.sub(start.point).length() <= step_size * 1.2 {
1369            let to_start = start.point.sub(candidate.point);
1370            if to_start.length() <= EPSILON || to_start.dot(next_tangent) >= 0.0 {
1371                points.push(start);
1372                tangents.push(tangents[0]);
1373                return Ok(Trace {
1374                    points,
1375                    tangents,
1376                    closed: true,
1377                    deviation,
1378                });
1379            }
1380        }
1381        current = candidate;
1382        tangent = next_tangent;
1383    }
1384    if !terminated {
1385        // The step budget ran out with the curve still going: a silently
1386        // truncated branch flows into topology as if complete, which is far
1387        // worse than a loud failure here.
1388        return Err(format!(
1389            "surface intersection trace exhausted {maximum_steps} steps \
1390             ({} points, step {step_size:.3e}) without reaching a boundary or closure",
1391            points.len()
1392        ));
1393    }
1394    Ok(Trace {
1395        points,
1396        tangents,
1397        closed: false,
1398        deviation,
1399    })
1400}
1401
1402fn point_segment_distance(point: Vec3, start: Vec3, end: Vec3) -> f64 {
1403    point.distance_to_segment(start, end, EPSILON)
1404}
1405
1406#[derive(Clone, Debug, Serialize)]
1407pub struct SurfaceIntersectionCurve {
1408    pub points: Vec<Vec3>,
1409    pub params_a: Vec<[f64; 2]>,
1410    pub params_b: Vec<[f64; 2]>,
1411    pub closed: bool,
1412    /// The section's unit tangent at each station, along the curve's
1413    /// direction; retained for trace-UV reuse or when the march ran with a
1414    /// [`SurfaceIntersectionOptions::span_budget`].
1415    #[serde(skip_serializing_if = "Option::is_none")]
1416    pub tangents: Option<Vec<Vec3>>,
1417    /// The largest span deviation the march measured on this curve;
1418    /// present only when it ran with a `span_budget`.
1419    #[serde(skip_serializing_if = "Option::is_none")]
1420    pub span_deviation: Option<f64>,
1421    /// The curve is a TANGENT section: the carriers touch along it with
1422    /// parallel normals rather than crossing it, so it separates nothing on
1423    /// either face. Only `intersect::tangent_curve` produces one; every
1424    /// marched or supplemental curve reads `false`.
1425    #[serde(skip_serializing_if = "std::ops::Not::not")]
1426    pub tangent: bool,
1427}
1428
1429#[derive(Clone, Debug, Deserialize)]
1430pub struct SurfaceIntersectionOptions {
1431    #[serde(default = "default_tolerance")]
1432    pub tolerance: f64,
1433    #[serde(default = "default_density")]
1434    pub seed_density: f64,
1435    #[serde(default = "default_maximum_steps")]
1436    pub maximum_steps: usize,
1437    pub maximum_step: Option<f64>,
1438    #[serde(default)]
1439    pub seed_points: Vec<Vec3>,
1440    #[serde(default)]
1441    pub seed_only: bool,
1442    pub seed_gate: Option<f64>,
1443    /// When set, every accepted span is re-sampled as the cubic Hermite
1444    /// through its two stations — chord-scaled tangents, in 3D and in each
1445    /// carrier's parameter plane — at five interior parameters, and the
1446    /// span's deviation is the largest distance among the 3D Hermite and
1447    /// the two carriers' images of their parameter Hermites. A span over
1448    /// the budget is rejected and re-stepped at half the step (accepted at
1449    /// the minimum step regardless), and the step grows only while the
1450    /// deviation stays under an eighth of the budget. The curve then
1451    /// reports its station tangents and its largest span deviation.
1452    ///
1453    /// `None`, the default, measures nothing and marches exactly as before.
1454    /// The budget a lane carries is what its FIT can absorb (the imprint's
1455    /// `intersection_fit`), never the corrector's `tolerance`: a cubic
1456    /// Hermite over a circle of radius `r` with step `h` misses by about
1457    /// `r (h/r)^4 / 384`, so a budget of `1e-7` would hold the step near
1458    /// `r/15` and multiply stations on every curved section.
1459    #[serde(default)]
1460    pub span_budget: Option<f64>,
1461    /// Off, the default, keeps the grid-then-seeds order byte for byte.
1462    #[serde(default)]
1463    pub ordered_starts: bool,
1464    /// A3's second half: a start an earlier trace ran through is consumed
1465    /// with a station snapped to it (the start is a refined intersection
1466    /// point, the chord it lies by is not), instead of merely dropped. Off,
1467    /// the default, keeps the first-claimant rule. Measured apart from the
1468    /// ordering because it inserts stations into traced curves.
1469    #[serde(default)]
1470    pub consume_starts: bool,
1471    /// The transverse gate stays. Off, the default, grids as before.
1472    #[serde(default)]
1473    pub tree_seeds: bool,
1474    /// SUB-GATE STARTS (2026-10-17, the revolve-into-bore report): the
1475    /// `|n_a × n_b|` an EXPLICIT seed is admitted at, in place of
1476    /// `TRANSVERSE_START_CROSS`. Grid and tree starts keep the gate: the
1477    /// tangency-band runaway it exists for is theirs (a refined start inside
1478    /// a band is a point no transverse curve passes through). An explicit
1479    /// seed the caller has PROVEN to lie on a crossing — a trim edge of one
1480    /// face that leaves one side of the other carrier for the other at the
1481    /// seed — is a point of a transverse section whatever the angle, and the
1482    /// march from it is sound down to where the corrector can still tell the
1483    /// section from the tangency band: the lateral uncertainty `tol / α` of
1484    /// a crossing at angle `α` against the band's half-width `√(2 R tol)`
1485    /// across a contact of curvature radius `R`, so `α ≥ √(tol / 2R)`; the
1486    /// caller derives the bound from its own tolerance and scale. A seed
1487    /// below it is dropped exactly as before. `None`, the default, keeps the
1488    /// gate byte for byte.
1489    #[serde(default)]
1490    pub seed_start_cross: Option<f64>,
1491}
1492
1493fn default_tolerance() -> f64 {
1494    LINEAR_TOLERANCE
1495}
1496fn default_density() -> f64 {
1497    1.0
1498}
1499fn default_maximum_steps() -> usize {
1500    4000
1501}
1502
1503impl Default for SurfaceIntersectionOptions {
1504    fn default() -> Self {
1505        Self {
1506            tolerance: default_tolerance(),
1507            seed_density: default_density(),
1508            maximum_steps: default_maximum_steps(),
1509            maximum_step: None,
1510            seed_points: Vec::new(),
1511            seed_only: false,
1512            seed_gate: None,
1513            span_budget: None,
1514            ordered_starts: false,
1515            consume_starts: false,
1516            tree_seeds: false,
1517            seed_start_cross: None,
1518        }
1519    }
1520}
1521
1522/// A station used only to construct an emitted section. Refinement preserves
1523/// every supplied station; it never replaces the topology-bearing trace.
1524#[derive(Clone, Copy, Debug)]
1525pub struct EmissionSample {
1526    pub point: Vec3,
1527    pub uv_a: [f64; 2],
1528    pub uv_b: [f64; 2],
1529    pub tangent: Vec3,
1530}
1531
1532/// Subdivide smooth spans locally until their joint 3D/UV Hermites pass the
1533/// existing span check. Failure is a conservative request for the fit route.
1534/// No seed search, branch tracing, clipping, station motion or topology edit.
1535pub fn refine_emission_samples(
1536    first_surface: &NurbsSurface,
1537    second_surface: &NurbsSurface,
1538    samples: &[EmissionSample],
1539    budget: f64,
1540) -> Result<Option<Vec<EmissionSample>>, String> {
1541    if samples.len() < 2 || !(budget > 0.0 && budget.is_finite()) { return Ok(None); }
1542    let first = surface_info(first_surface)?;
1543    let second = surface_info(second_surface)?;
1544    let point = |s: EmissionSample| IntersectionPoint {
1545        point: s.point, ua: s.uv_a[0], va: s.uv_a[1], ub: s.uv_b[0], vb: s.uv_b[1],
1546    };
1547    // Fixed endpoints must themselves meet the emission floor. Refining an
1548    // interior cannot repair an inaccurate endpoint without moving topology.
1549    for s in samples {
1550        if !(first_surface.evaluate(s.uv_a[0], s.uv_a[1])?.sub(s.point).length() <= budget)
1551            || !(second_surface.evaluate(s.uv_b[0], s.uv_b[1])?.sub(s.point).length() <= budget)
1552        { return Ok(None); }
1553    }
1554    let mut pending: Vec<_> = samples.windows(2).rev().map(|p| (p[0], p[1], 0usize)).collect();
1555    let mut out = vec![samples[0]];
1556    let mut inserted = 0;
1557    while let Some((a, b, depth)) = pending.pop() {
1558        let pa = point(a);
1559        let pb = point(b);
1560        if span_deviation(first, second, pa, a.tangent, pb, b.tangent)? <= budget {
1561            out.push(b);
1562            continue;
1563        }
1564        let chord_vector = b.point.sub(a.point);
1565        let chord = chord_vector.length();
1566        if depth >= 8 || inserted >= 4096 || chord <= 4.0 * crate::KNOT_IDENTITY_TOL
1567            || crossing_at(first, second, pa) < 0.05 || crossing_at(first, second, pb) < 0.05
1568            || a.tangent.dot(b.tangent) < 0.5
1569            || a.tangent.dot(chord_vector) <= 0.5 * chord || b.tangent.dot(chord_vector) <= 0.5 * chord
1570        { return Ok(None); }
1571        let ha = ParameterHermite::new(first, a.uv_a, a.tangent, b.uv_a, b.tangent, chord)?;
1572        let hb = ParameterHermite::new(second, a.uv_b, a.tangent, b.uv_b, b.tangent, chord)?;
1573        let ua = ha.at(0.5);
1574        let ub = hb.at(0.5);
1575        let predicted = hermite_at(a.point, a.tangent.scale(chord), b.point, b.tangent.scale(chord), 0.5);
1576        let direction = a.tangent.add(b.tangent).normalized()?;
1577        let seed = IntersectionPoint {
1578            point: predicted,
1579            ua: fit(ua[0], first.u0, first.u1, first.closed_u),
1580            va: fit(ua[1], first.v0, first.v1, first.closed_v),
1581            ub: fit(ub[0], second.u0, second.u1, second.closed_u),
1582            vb: fit(ub[1], second.v0, second.v1, second.closed_v),
1583        };
1584        let Some((mid, boundary)) = correct(first, second, seed, predicted, direction, budget * 0.1)? else { return Ok(None); };
1585        let along = mid.point.sub(a.point).dot(chord_vector) / (chord * chord);
1586        if boundary || mid.point.sub(predicted).length() > 0.25 * chord
1587            || !(0.2..=0.8).contains(&along) || crossing_at(first, second, mid) < 0.05
1588        { return Ok(None); }
1589        let Some(mut tangent) = tangent_at(first, second, mid)? else { return Ok(None); };
1590        if tangent.dot(direction) < 0.0 { tangent = tangent.scale(-1.0); }
1591        if tangent.dot(a.tangent) < 0.5 || tangent.dot(b.tangent) < 0.5 { return Ok(None); }
1592        let m = EmissionSample { point: mid.point, uv_a: [mid.ua, mid.va], uv_b: [mid.ub, mid.vb], tangent };
1593        inserted += 1;
1594        pending.push((m, b, depth + 1));
1595        pending.push((a, m, depth + 1));
1596    }
1597    Ok(Some(out))
1598}
1599
1600/// The march's plane-constrained corrector from given parameters on both
1601/// carriers: the intersection point in the plane through `predicted` square to
1602/// `direction`, with its parameters, at the march residual (`tolerance * 0.01`).
1603/// `None` when the Newton does not converge. For a section lane that bisects a
1604/// span between two stations it already holds (`csg/imprint/hermite.rs`).
1605pub fn correct_in_plane(
1606    first_surface: &NurbsSurface,
1607    second_surface: &NurbsSurface,
1608    uv_a: [f64; 2],
1609    uv_b: [f64; 2],
1610    predicted: Vec3,
1611    direction: Vec3,
1612    tolerance: f64,
1613) -> Result<Option<(Vec3, [f64; 2], [f64; 2])>, String> {
1614    let first = surface_info(first_surface)?;
1615    let second = surface_info(second_surface)?;
1616    let seed = IntersectionPoint {
1617        point: predicted,
1618        ua: fit(uv_a[0], first.u0, first.u1, first.closed_u),
1619        va: fit(uv_a[1], first.v0, first.v1, first.closed_v),
1620        ub: fit(uv_b[0], second.u0, second.u1, second.closed_u),
1621        vb: fit(uv_b[1], second.v0, second.v1, second.closed_v),
1622    };
1623    Ok(correct(first, second, seed, predicted, direction, tolerance)?
1624        .map(|(point, _)| (point.point, [point.ua, point.va], [point.ub, point.vb])))
1625}
1626
1627/// Refine `seed` onto the intersection of `first_surface` and `second_surface`:
1628/// the closest point on each carrier seeds the same Newton the march uses
1629/// ([`refine_point`]), so the answer is an INTERSECTION point at the march's own
1630/// residual (`tolerance * 0.01`), not a projection onto one surface — a point
1631/// merely projected onto one carrier would carry the very bias a section
1632/// refiner exists to remove (2026-09-26, the sphere/bore rim of `BadBoolean`).
1633/// `None` when the Newton does not converge or lands further than `reach` from
1634/// the seed: a refiner must not pull a station onto another branch.
1635pub fn refine_to_intersection(
1636    first_surface: &NurbsSurface,
1637    second_surface: &NurbsSurface,
1638    seed: Vec3,
1639    tolerance: f64,
1640    reach: f64,
1641) -> Result<Option<Vec3>, String> {
1642    let first = surface_info(first_surface)?;
1643    let second = surface_info(second_surface)?;
1644    let on_first = project_point_to_surface(first_surface, seed)?;
1645    let on_second = project_point_to_surface(second_surface, seed)?;
1646    let Some(refined) = refine_point(
1647        first,
1648        second,
1649        on_first.u,
1650        on_first.v,
1651        on_second.u,
1652        on_second.v,
1653        tolerance,
1654    )?
1655    else {
1656        return Ok(None);
1657    };
1658    if refined.point.sub(seed).length() > reach {
1659        return Ok(None);
1660    }
1661    Ok(Some(refined.point))
1662}
1663
1664pub fn intersect_surfaces(
1665    first_surface: &NurbsSurface,
1666    second_surface: &NurbsSurface,
1667    options: &SurfaceIntersectionOptions,
1668) -> Result<Vec<SurfaceIntersectionCurve>, String> {
1669    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::MARCH);
1670    let _lap = crate::projection_profile::Lap::enter_pair(first_surface, second_surface);
1671    let first_box = Bounds::from_surface_controls(first_surface)?;
1672    let second_box = Bounds::from_surface_controls(second_surface)?;
1673    if !first_box.intersects(second_box, options.tolerance * 10.0) {
1674        return Ok(Vec::new());
1675    }
1676    let first = surface_info(first_surface)?;
1677    let second = surface_info(second_surface)?;
1678    let diagonal = first_box.diagonal().min(second_box.diagonal());
1679    let initial_step = diagonal / 100.0;
1680    let minimum_step = (options.tolerance * 100.0).max(diagonal * 1e-6);
1681    let maximum_step = (diagonal / 15.0).min(options.maximum_step.unwrap_or(f64::INFINITY));
1682    let maximum_steps = step_budget(options.maximum_steps, maximum_step, diagonal);
1683    let mut starts = if options.seed_only {
1684        Vec::new()
1685    } else if options.tree_seeds {
1686        // A4: leaf-pair candidates; the grid only when the pair count is
1687        // over the cap.
1688        match tree_start_points(first, second, options.tolerance)? {
1689            Some((starts, _pairs)) => starts,
1690            None => find_start_points(first, second, options.tolerance, options.seed_density)?,
1691        }
1692    } else {
1693        find_start_points(first, second, options.tolerance, options.seed_density)?
1694    };
1695    // A grid start is refined onto both carriers exactly like an explicit
1696    // seed and is held to the same transversality gate: inside a tangency
1697    // band the refinement converges (the band IS within tolerance of both
1698    // surfaces) to a point no transverse curve passes through.
1699    starts.retain(|start| transverse_at(first, second, *start));
1700    let seed_gate = options.seed_gate.unwrap_or(options.tolerance * 100.0);
1701    // A3: explicit seeds are kept apart so they can be traced first.
1702    let grid_count = starts.len();
1703    for seed in &options.seed_points {
1704        let projection_a = project_point_to_surface(first_surface, *seed)?;
1705        if projection_a.distance > seed_gate {
1706            continue;
1707        }
1708        let projection_b = project_point_to_surface(second_surface, *seed)?;
1709        if projection_b.distance > seed_gate {
1710            continue;
1711        }
1712        let Some(refined) = refine_point(
1713            first,
1714            second,
1715            projection_a.u,
1716            projection_a.v,
1717            projection_b.u,
1718            projection_b.v,
1719            options.tolerance,
1720        )?
1721        else {
1722            continue;
1723        };
1724        // The seed's own gate: the caller's sub-gate bound where it vouches
1725        // for the seed, the transversality gate otherwise.
1726        let admitted = match options.seed_start_cross {
1727            Some(bound) => crossing_at(first, second, refined) >= bound.min(TRANSVERSE_START_CROSS),
1728            None => transverse_at(first, second, refined),
1729        };
1730        if !admitted {
1731            continue;
1732        }
1733        starts.push(refined);
1734    }
1735    if options.ordered_starts {
1736        // A3: seeds (trim-boundary pierces) before the interior candidates,
1737        // and within each group the most transverse first; stable, so equal
1738        // crossings keep their discovery order.
1739        let crossing = |start: &IntersectionPoint| -> f64 {
1740            match (
1741                first.surface.normal(start.ua, start.va),
1742                second.surface.normal(start.ub, start.vb),
1743            ) {
1744                (Ok(a), Ok(b)) => a.cross(b).length(),
1745                _ => 0.0,
1746            }
1747        };
1748        let mut seeds = starts.split_off(grid_count);
1749        seeds.sort_by(|a, b| crossing(b).total_cmp(&crossing(a)));
1750        starts.sort_by(|a, b| crossing(b).total_cmp(&crossing(a)));
1751        seeds.append(&mut starts);
1752        starts = seeds;
1753    }
1754
1755    let switches = TraceSwitches::from_env();
1756    let mut curves: Vec<SurfaceIntersectionCurve> = Vec::new();
1757    for start in starts {
1758        let mut claimed = false;
1759        for curve in &mut curves {
1760            let Some((index, distance)) = curve
1761                .points
1762                .windows(2)
1763                .enumerate()
1764                .map(|(index, segment)| (index, point_segment_distance(start.point, segment[0], segment[1])))
1765                .filter(|(_, distance)| *distance <= initial_step * 1.5)
1766                .min_by(|a, b| a.1.total_cmp(&b.1))
1767            else {
1768                continue;
1769            };
1770            claimed = true;
1771            // A3: a start an earlier trace ran through is consumed with a
1772            // station snapped to it — the start is a refined intersection
1773            // point, the segment it lies by is a chord — unless it sits on a
1774            // station already.
1775            if options.consume_starts
1776                && distance > 0.0
1777                && start.point.sub(curve.points[index]).length() > minimum_step
1778                && start.point.sub(curve.points[index + 1]).length() > minimum_step
1779            {
1780                curve.points.insert(index + 1, start.point);
1781                if let Some(tangents) = curve.tangents.as_mut() {
1782                    let along = curve.points[index + 2].sub(curve.points[index]);
1783                    let tangent = match tangent_at(first, second, start)? {
1784                        Some(tangent) if tangent.dot(along) < 0.0 => tangent.scale(-1.0),
1785                        Some(tangent) => tangent,
1786                        None => tangents[index],
1787                    };
1788                    tangents.insert(index + 1, tangent);
1789                }
1790                if curve.params_a.len() > index + 1 && curve.params_b.len() > index + 1 {
1791                    curve.params_a.insert(index + 1, [start.ua, start.va]);
1792                    curve.params_b.insert(index + 1, [start.ub, start.vb]);
1793                }
1794            }
1795            break;
1796        }
1797        if switches.debug {
1798            let at = start.point;
1799            eprintln!(
1800                "SSI-START claimed {claimed} p ({:.6},{:.6},{:.6}) initial {initial_step:.4e} minimum {minimum_step:.4e} maximum {maximum_step:.4e}",
1801                at.x, at.y, at.z
1802            );
1803        }
1804        if claimed {
1805            continue;
1806        }
1807        let forward = trace(
1808            first,
1809            second,
1810            start,
1811            1.0,
1812            options.tolerance,
1813            initial_step,
1814            minimum_step,
1815            maximum_step,
1816            maximum_steps,
1817            switches,
1818            options.span_budget,
1819        )?;
1820        let (all, closed) = if forward.closed {
1821            (Spliced::from(forward), true)
1822        } else {
1823            let backward = trace(
1824                first,
1825                second,
1826                start,
1827                -1.0,
1828                options.tolerance,
1829                initial_step,
1830                minimum_step,
1831                maximum_step,
1832                maximum_steps,
1833                switches,
1834                options.span_budget,
1835            )?;
1836            (splice(backward, forward), false)
1837        };
1838        if all.points.len() < 2 {
1839            continue;
1840        }
1841        curves.push(curve_from(all, closed, options.span_budget.is_some()));
1842    }
1843    Ok(curves)
1844}
1845
1846/// Minimum |n_a × n_b| for a seed/branch to count as a *transverse* crossing
1847/// rather than a tangential graze — the same threshold `intersect_surfaces`
1848/// applies to its start points.
1849const SUPPLEMENTAL_TRANSVERSE_CROSS: f64 = TRANSVERSE_START_CROSS;
1850
1851/// Gated supplemental SSI **detector** for a pair the coarse pair-classifier
1852/// culled as "tangential-only" (`NearTangent` + `tangential_only`).
1853///
1854/// The 5×5 classification grid can land only on an incidental tangential KISS
1855/// between two curved carriers (e.g. the inner walls / tube tops of two
1856/// overlapping tori) and never sample the transverse loop where their tubes
1857/// actually CROSS, so `tangential_only` is a false positive that would drop a
1858/// real intersection. This routine re-seeds a DENSER grid on BOTH carriers,
1859/// keeps only *transverse* seeds (near-parallel normals rejected up front, so
1860/// the tangency band is never walked), SWALLOWS per-branch trace-exhaustion (a
1861/// genuine tangency band never closes/exits and would otherwise error — here
1862/// it simply means "no transverse curve from this seed"), and returns only
1863/// branches that are genuinely transverse along their length.
1864///
1865/// A *genuinely* tangential pair yields an empty result (every seed rejected /
1866/// every trace fruitless), so the caller skips exactly as before — the common
1867/// intersection path is never touched.
1868///
1869/// NOTE — deferred capability: when this DOES return branches, the true
1870/// intersection is *singular* (the transverse loops meet at tangent nodes,
1871/// e.g. equal-radius torus-torus at `(1.5, ±3.708, ±1.5)`). Imprinting them
1872/// requires 4-valent tangent-vertex ("checkerboard") singular assembly, which
1873/// the kernel does not yet do; until then the caller REFUSES such a pair with
1874/// a clear error rather than silently dropping the geometry or emitting the
1875/// cryptic downstream pcurve/open-loop error. See imprint.rs (tangential-only
1876/// skip) and the project singular-assembly roadmap.
1877pub fn intersect_surfaces_supplemental(
1878    first_surface: &NurbsSurface,
1879    second_surface: &NurbsSurface,
1880    options: &SurfaceIntersectionOptions,
1881) -> Result<Vec<SurfaceIntersectionCurve>, String> {
1882    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::MARCH);
1883    let first_box = Bounds::from_surface_controls(first_surface)?;
1884    let second_box = Bounds::from_surface_controls(second_surface)?;
1885    if !first_box.intersects(second_box, options.tolerance * 10.0) {
1886        return Ok(Vec::new());
1887    }
1888    let first = surface_info(first_surface)?;
1889    let second = surface_info(second_surface)?;
1890    let diagonal = first_box.diagonal().min(second_box.diagonal());
1891    let initial_step = diagonal / 100.0;
1892    let minimum_step = (options.tolerance * 100.0).max(diagonal * 1e-6);
1893    let maximum_step = (diagonal / 15.0).min(options.maximum_step.unwrap_or(f64::INFINITY));
1894    let maximum_steps = step_budget(options.maximum_steps, maximum_step, diagonal);
1895
1896    // Denser self-seed (≥2× density pushes the ≤24 grid toward its cap so a
1897    // thin transverse overlap the classifier stepped over still gets a start),
1898    // gridding BOTH carriers so an interior loop touching neither trim boundary
1899    // is still hit from whichever surface samples it best.
1900    let density = options.seed_density.max(2.0);
1901    let mut starts: Vec<IntersectionPoint> = Vec::new();
1902    for gridded_second in [false, true] {
1903        let (a, b) = if gridded_second {
1904            (second, first)
1905        } else {
1906            (first, second)
1907        };
1908        for start in find_start_points(a, b, options.tolerance, density)? {
1909            // find_start_points expresses params as (grid surface, projected
1910            // surface); normalise every start to (first, second).
1911            let start = if gridded_second {
1912                IntersectionPoint {
1913                    ua: start.ub,
1914                    va: start.vb,
1915                    ub: start.ua,
1916                    vb: start.va,
1917                    point: start.point,
1918                }
1919            } else {
1920                start
1921            };
1922            starts.push(start);
1923        }
1924    }
1925    // Reject tangential seeds outright: a start whose two surface normals are
1926    // (near-)parallel is on a graze, not a crossing, and marching it walks the
1927    // tangency band.
1928    starts.retain(|start| {
1929        match (
1930            first.surface.normal(start.ua, start.va),
1931            second.surface.normal(start.ub, start.vb),
1932        ) {
1933            (Ok(na), Ok(nb)) => na.cross(nb).length() > SUPPLEMENTAL_TRANSVERSE_CROSS,
1934            _ => false,
1935        }
1936    });
1937
1938    let switches = TraceSwitches::from_env();
1939    let mut curves: Vec<SurfaceIntersectionCurve> = Vec::new();
1940    for start in starts {
1941        let claimed = curves.iter().any(|curve| {
1942            curve.points.windows(2).any(|segment| {
1943                point_segment_distance(start.point, segment[0], segment[1]) <= initial_step * 1.5
1944            })
1945        });
1946        if claimed {
1947            continue;
1948        }
1949        // Swallow trace-exhaustion here (unlike the common path, which errors
1950        // loudly): on this gated path a non-closing branch means the seed sat
1951        // on a tangency band, which we simply drop.
1952        let Ok(forward) = trace(
1953            first,
1954            second,
1955            start,
1956            1.0,
1957            options.tolerance,
1958            initial_step,
1959            minimum_step,
1960            maximum_step,
1961            maximum_steps,
1962            switches,
1963            options.span_budget,
1964        ) else {
1965            continue;
1966        };
1967        let (all, closed) = if forward.closed {
1968            (Spliced::from(forward), true)
1969        } else {
1970            let Ok(backward) = trace(
1971                first,
1972                second,
1973                start,
1974                -1.0,
1975                options.tolerance,
1976                initial_step,
1977                minimum_step,
1978                maximum_step,
1979                maximum_steps,
1980                switches,
1981                options.span_budget,
1982            ) else {
1983                continue;
1984            };
1985            (splice(backward, forward), false)
1986        };
1987        if all.points.len() < 2 {
1988            continue;
1989        }
1990        // Keep only a branch that is genuinely transverse somewhere along its
1991        // length — a final guard against a tangency-band polyline that happened
1992        // to close.
1993        let transverse = all.points.iter().step_by((all.points.len() / 5).max(1)).any(|point| {
1994            match (
1995                first.surface.normal(point.ua, point.va),
1996                second.surface.normal(point.ub, point.vb),
1997            ) {
1998                (Ok(na), Ok(nb)) => na.cross(nb).length() > SUPPLEMENTAL_TRANSVERSE_CROSS,
1999                _ => false,
2000            }
2001        });
2002        if !transverse {
2003            continue;
2004        }
2005        curves.push(curve_from(all, closed, options.span_budget.is_some()));
2006    }
2007    Ok(curves)
2008}
2009