Skip to main content

brep_geometry/intersect/
curve_surface_intersection.rs

1use crate::curve::interior_knot_count;
2use crate::{project_point_to_surface, NurbsCurve, NurbsSurface, Vec3};
3use serde::Serialize;
4
5const EPSILON: f64 = crate::tolerance::FP_FLOOR;
6
7use crate::spatial::Aabb as Bounds;
8
9
10/// The box of the carrier's control points, in their order; the first control
11/// point that is not a point is the error. Read without collecting them: it
12/// is paid on every call, and a view ray through a fitted carrier of a gear
13/// asks it thousands of times.
14fn surface_bounds(surface: &NurbsSurface) -> Result<Bounds, String> {
15    let mut bounds = Bounds::from_points([]);
16    for point in surface.control_points.iter().flatten() {
17        let point = point.point()?;
18        bounds.minimum.x = bounds.minimum.x.min(point.x);
19        bounds.minimum.y = bounds.minimum.y.min(point.y);
20        bounds.minimum.z = bounds.minimum.z.min(point.z);
21        bounds.maximum.x = bounds.maximum.x.max(point.x);
22        bounds.maximum.y = bounds.maximum.y.max(point.y);
23        bounds.maximum.z = bounds.maximum.z.max(point.z);
24    }
25    Ok(bounds)
26}
27
28
29/// The box of each knot-span patch's control points: the surface over span
30/// `[u_i, u_i+1) x [v_j, v_j+1)` lies in the convex hull of the
31/// `(p + 1) x (q + 1)` control points that support it (positive weights), so
32/// a curve segment clear of every span box is clear of the surface.
33///
34/// The whole-net box cannot say that for a carrier that winds: an eight-turn
35/// helical tube's box is the whole coil, every sample segment of a ray through
36/// the coil passes it, and every one seeded a Newton that starts from a global
37/// projection onto a 1280-point net — 21 of the 26 s the 2026-09-26 coil
38/// fillet report's interference check took, for about one hit in forty seeds.
39fn span_bounds(surface: &NurbsSurface) -> Result<Vec<Bounds>, String> {
40    let (p, q) = (surface.degree_u, surface.degree_v);
41    let rows = surface.control_points.len();
42    let columns = surface.control_points.first().map_or(0, Vec::len);
43    let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
44        (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
45    };
46    let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
47    // A malformed net has no span structure to trust: the whole-net box stands.
48    if spans_u.is_empty() || spans_v.is_empty() {
49        return Ok(vec![surface_bounds(surface)?]);
50    }
51    let mut boxes = Vec::with_capacity(spans_u.len() * spans_v.len());
52    for &i in &spans_u {
53        for &j in &spans_v {
54            let mut bounds = Bounds::from_points([]);
55            for row in &surface.control_points[i - p..=i] {
56                for control in &row[j - q..=j] {
57                    let point = control.point()?;
58                    bounds.minimum.x = bounds.minimum.x.min(point.x);
59                    bounds.minimum.y = bounds.minimum.y.min(point.y);
60                    bounds.minimum.z = bounds.minimum.z.min(point.z);
61                    bounds.maximum.x = bounds.maximum.x.max(point.x);
62                    bounds.maximum.y = bounds.maximum.y.max(point.y);
63                    bounds.maximum.z = bounds.maximum.z.max(point.z);
64                }
65            }
66            boxes.push(bounds);
67        }
68    }
69    Ok(boxes)
70}
71
72fn fit_parameter(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
73    crate::projection::fit_parameter(value, minimum, maximum, closed)
74}
75
76fn solve_three(matrix: [[f64; 3]; 3], rhs: Vec3) -> Option<[f64; 3]> {
77    let a = matrix;
78    let determinant = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
79        - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
80        + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
81    let scale: f64 = a.iter().flatten().map(|value| value.abs()).sum();
82    if determinant.abs() <= 1e-14 * scale.max(1.0).powi(3) {
83        return None;
84    }
85    let x = (rhs.x * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
86        - a[0][1] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
87        + a[0][2] * (rhs.y * a[2][1] - a[1][1] * rhs.z))
88        / determinant;
89    let y = (a[0][0] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
90        - rhs.x * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
91        + a[0][2] * (a[1][0] * rhs.z - rhs.y * a[2][0]))
92        / determinant;
93    let z = (a[0][0] * (a[1][1] * rhs.z - rhs.y * a[2][1])
94        - a[0][1] * (a[1][0] * rhs.z - rhs.y * a[2][0])
95        + rhs.x * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
96        / determinant;
97    Some([x, y, z])
98}
99
100/// `BREP_CS_NEWTON_LOCAL_START` (default on; =0 opens from the global foot): on a classifier's ray
101/// ([`intersect_ray_surface`]), each seed's Newton opens from
102/// the local foot of its curve point ([`crate::projection::project_point_to_surface_local`]:
103/// Newton from the seed grid's nearest sample) instead of the nearest point of
104/// the whole surface. The opening foot is only a start: the Newton then solves
105/// curve = surface on its own, and the gap filter and duplicate guard read its
106/// answer as before. On a ray through a winding carrier the global stage was
107/// nine tenths of each Newton's cost.
108pub fn newton_local_start_enabled() -> bool {
109    switch!("BREP_CS_NEWTON_LOCAL_START", true)
110}
111
112/// `BREP_CS_NEWTON_LOCAL_START_CHECK=1` (with the start switch on): solve every
113/// call from both starts, return the local one's answer, and count (and print)
114/// each opening foot more than the model tolerance from the global one's and
115/// each call whose hits differ ([`newton_start_check_counts`]).
116fn newton_local_start_check() -> bool {
117    switch!("BREP_CS_NEWTON_LOCAL_START_CHECK", false)
118}
119
120static START_CHECK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
121static START_CHECK_FEET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
122static START_CHECK_FOOT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
123static START_CHECK_HIT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
124
125/// What the check mode has compared in this process: `(calls, opening feet,
126/// feet apart by more than the model tolerance, calls whose hits differ)`.
127pub fn newton_start_check_counts() -> (u64, u64, u64, u64) {
128    use std::sync::atomic::Ordering::Relaxed;
129    (
130        START_CHECK_CALLS.load(Relaxed),
131        START_CHECK_FEET.load(Relaxed),
132        START_CHECK_FOOT_DISAGREEMENTS.load(Relaxed),
133        START_CHECK_HIT_DISAGREEMENTS.load(Relaxed),
134    )
135}
136
137/// The Newton's opening foot of `point`: local or the whole surface's nearest.
138/// In check mode the local start also reads the global foot and counts the two
139/// apart by more than the model tolerance.
140fn opening_foot(surface: &NurbsSurface, point: Vec3, local: bool, check: bool) -> Result<[f64; 2], String> {
141    if !local {
142        let projection = project_point_to_surface(surface, point)?;
143        return Ok([projection.u, projection.v]);
144    }
145    let projection = crate::projection::project_point_to_surface_local(surface, point)?;
146    if check {
147        use std::sync::atomic::Ordering::Relaxed;
148        START_CHECK_FEET.fetch_add(1, Relaxed);
149        let nearest = project_point_to_surface(surface, point)?;
150        let apart = projection.point.sub(nearest.point).length();
151        if apart > crate::tolerance::DEFAULT_MODEL {
152            START_CHECK_FOOT_DISAGREEMENTS.fetch_add(1, Relaxed);
153            eprintln!(
154                "cs newton start check: foot apart {apart:.3e} (local {:.3e} at ({:.9},{:.9}), nearest {:.3e} at ({:.9},{:.9}))",
155                projection.distance, projection.u, projection.v, nearest.distance, nearest.u, nearest.v
156            );
157        }
158    }
159    Ok([projection.u, projection.v])
160}
161
162fn newton_curve_surface(
163    curve: &NurbsCurve,
164    surface: &NurbsSurface,
165    seed: f64,
166    local_start: bool,
167    check: bool,
168) -> Result<[f64; 3], String> {
169    let [t0, t1] = curve.domain()?;
170    let [u0, u1] = surface.domain_u()?;
171    let [v0, v1] = surface.domain_v()?;
172    let (closed_u, closed_v) = surface.closed_directions()?;
173    let mut t = seed;
174    let [mut u, mut v] = opening_foot(surface, curve.evaluate(t)?, local_start, check)?;
175    for _ in 0..60 {
176        let (curve_point, tangent) = curve.deriv1(t)?;
177        let (surface_point, du, dv) = surface.deriv1(u, v)?;
178        let residual = curve_point.sub(surface_point);
179        if residual.length() <= EPSILON {
180            return Ok([t, u, v]);
181        }
182        let Some([mut step_t, mut step_u, mut step_v]) = solve_three(
183            [
184                [tangent.x, -du.x, -dv.x],
185                [tangent.y, -du.y, -dv.y],
186                [tangent.z, -du.z, -dv.z],
187            ],
188            residual.scale(-1.0),
189        ) else {
190            if tangent.length_squared() <= EPSILON {
191                return Ok([t, u, v]);
192            }
193            let next_t = (t - residual.dot(tangent) / tangent.length_squared()).clamp(t0, t1);
194            if (next_t - t).abs() <= 1e-15 * (t1 - t0) {
195                return Ok([t, u, v]);
196            }
197            t = next_t;
198            // The next iterate's foot, continued from this one's: the Newton
199            // is on ONE sheet, and the nearest point of the whole surface to
200            // the stepped curve point can be on another.
201            let projection =
202                crate::projection::project_point_to_surface_from_seed(surface, curve.evaluate(t)?, [u, v])?;
203            u = projection.u;
204            v = projection.v;
205            continue;
206        };
207        step_t = step_t.clamp(-(t1 - t0) / 4.0, (t1 - t0) / 4.0);
208        step_u = step_u.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
209        step_v = step_v.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
210        let next_t = (t + step_t).clamp(t0, t1);
211        let next_u = fit_parameter(u + step_u, u0, u1, closed_u);
212        let next_v = fit_parameter(v + step_v, v0, v1, closed_v);
213        let stalled = (next_t - t).abs() <= 1e-15 * (t1 - t0)
214            && (next_u - u).abs() <= 1e-15 * (u1 - u0)
215            && (next_v - v).abs() <= 1e-15 * (v1 - v0);
216        t = next_t;
217        u = next_u;
218        v = next_v;
219        if stalled {
220            return Ok([t, u, v]);
221        }
222    }
223    Ok([t, u, v])
224}
225
226#[derive(Clone, Copy, Debug, Serialize)]
227pub struct CurveSurfaceIntersection {
228    pub t: f64,
229    pub u: f64,
230    pub v: f64,
231    pub point: Vec3,
232    pub gap: f64,
233    pub tangential: bool,
234}
235
236/// Whether the duplicate guard's parameter tolerance is capped by the curve's
237/// domain. `BREP_CS_DUPLICATE_CAP=0` restores the uncapped tolerance, which at
238/// a stationary parameter is 1e6 and swallows every other hit on the curve.
239fn duplicate_cap_enabled() -> bool {
240    switch!("BREP_CS_DUPLICATE_CAP", true)
241}
242
243pub fn intersect_curve_surface(
244    curve: &NurbsCurve,
245    surface: &NurbsSurface,
246    tolerance: f64,
247) -> Result<Vec<CurveSurfaceIntersection>, String> {
248    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
249    let seeds = sampled_seeds(curve, surface, tolerance)?;
250    intersect_curve_surface_from_seeds(curve, surface, tolerance, seeds)
251}
252
253/// The general search's Newton seeds: the midpoint of every sample segment
254/// of the curve whose box meets the surface's box and one of its span boxes.
255fn sampled_seeds(curve: &NurbsCurve, surface: &NurbsSurface, tolerance: f64) -> Result<Vec<f64>, String> {
256    let [t0, t1] = curve.domain()?;
257    let surface_box = surface_bounds(surface)?.expanded(tolerance * 10.0);
258    let sample_count =
259        32usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4);
260    let mut samples = Vec::with_capacity(sample_count + 1);
261    for index in 0..=sample_count {
262        let t = t0 + (t1 - t0) * index as f64 / sample_count as f64;
263        samples.push((t, curve.evaluate(t)?));
264    }
265    let span_boxes = span_bounds(surface)?;
266    let mut seeds = Vec::new();
267    for pair in samples.windows(2) {
268        let segment_box = Bounds::from_points([pair[0].1, pair[1].1]).expanded(tolerance * 10.0);
269        if segment_box.intersects_exact(surface_box)
270            && span_boxes.iter().any(|span_box| segment_box.intersects_exact(span_box.expanded(tolerance * 10.0)))
271        {
272            seeds.push((pair[0].0 + pair[1].0) * 0.5);
273        }
274    }
275    Ok(seeds)
276}
277
278/// [`intersect_curve_surface`] from the caller's own Newton seeds (curve
279/// parameters): the same Newton, gap filter, duplicate guard and tangency
280/// reading as the general search, only the seeds differ. The classifier's
281/// exact ray lane (`crate::exact_line_surface`) seeds it with the closed-form
282/// roots of a straight segment against an analytic carrier.
283pub fn intersect_curve_surface_from_seeds(
284    curve: &NurbsCurve,
285    surface: &NurbsSurface,
286    tolerance: f64,
287    seeds: Vec<f64>,
288) -> Result<Vec<CurveSurfaceIntersection>, String> {
289    solve_counted(curve, surface, tolerance, &seeds, false)
290}
291
292/// [`intersect_curve_surface`] for a point classifier's ray: the same search,
293/// with each Newton opened from the local foot when
294/// `BREP_CS_NEWTON_LOCAL_START` is on. Only a ray caller may take it: it reads
295/// the parity of transversal crossings and casts another direction on a
296/// grazing hit, so a cluster of roots where a curve runs along the surface (an
297/// edge on a face, where the two starts can keep different members of the
298/// cluster) never decides its answer.
299pub fn intersect_ray_surface(
300    curve: &NurbsCurve,
301    surface: &NurbsSurface,
302    tolerance: f64,
303) -> Result<Vec<CurveSurfaceIntersection>, String> {
304    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
305    let seeds = sampled_seeds(curve, surface, tolerance)?;
306    if !ray_hull_seeds_enabled() {
307        return solve_counted(curve, surface, tolerance, &seeds, true);
308    }
309    let Some(kept) = hull_seeds(curve, surface, tolerance, &seeds) else {
310        return solve_counted(curve, surface, tolerance, &seeds, true);
311    };
312    let hits = solve_counted(curve, surface, tolerance, &kept, true)?;
313    if ray_hull_seeds_check() {
314        let every = solve_counted(curve, surface, tolerance, &seeds, true)?;
315        assert!(
316            same_hits(&hits, &every, tolerance),
317            "BREP_RAY_HULL_SEEDS_CHECK: {} of {} seeds read t {:?}, every seed read t {:?}",
318            kept.len(),
319            seeds.len(),
320            hits.iter().map(|hit| hit.t).collect::<Vec<_>>(),
321            every.iter().map(|hit| hit.t).collect::<Vec<_>>()
322        );
323    }
324    Ok(hits)
325}
326
327/// `BREP_RAY_HULL_SEEDS` (default on; `=0` keeps every seed): a straight ray's Newton seeds are kept
328/// only where the ray meets the surface's Bezier hulls. Each knot-span patch is
329/// halved (de Casteljau) while the ray passes through its control box, down to
330/// boxes whose stretch of the ray is under one seed segment; a seed whose
331/// segment meets none of those stretches cannot reach a hit there, since the
332/// surface lies in the hull of each piece's controls (positive weights). A
333/// classifier's ray across a height-field slab took 32 seeds, each a Newton
334/// opened by a point projection, for about one hit.
335/// `BREP_RAY_HULL_SEEDS_CHECK=1` turns it on and also solves from every seed,
336/// stopping where the hits differ.
337fn ray_hull_seeds_enabled() -> bool {
338    ray_hull_seeds_check() || switch!("BREP_RAY_HULL_SEEDS", true)
339}
340
341fn ray_hull_seeds_check() -> bool {
342    switch!("BREP_RAY_HULL_SEEDS_CHECK", false)
343}
344
345/// The seeds of [`intersect_ray_surface`] whose segment meets the stretch of a
346/// straight `curve` inside a hull piece of `surface` ([`ray_hull_seeds_enabled`]);
347/// `None` when the curve is not a straight segment or the patches cannot be
348/// read, and every seed stays.
349fn hull_seeds(curve: &NurbsCurve, surface: &NurbsSurface, tolerance: f64, seeds: &[f64]) -> Option<Vec<f64>> {
350    if seeds.is_empty() || curve.degree != 1 || curve.control_points.len() != 2 {
351        return None;
352    }
353    let [t0, t1] = curve.domain().ok()?;
354    let (start, end) = (curve.control_points[0].point().ok()?, curve.control_points[1].point().ok()?);
355    let (spans_u, spans_v) = crate::curve_clear::patch_span_counts(surface)?;
356    // The seed segments of `sampled_seeds`, in the ray's own parameter s in [0, 1].
357    let sample_count = 32usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4);
358    let step = 1.0 / sample_count as f64;
359    let pad = tolerance * 10.0;
360    let direction = end.sub(start);
361    // The ray's stretch [s0, s1] inside a box padded by `pad` (slab clipping).
362    let stretch = |lo: [f64; 3], hi: [f64; 3]| -> Option<[f64; 2]> {
363        let (mut s0, mut s1) = (0.0f64, 1.0f64);
364        for (k, (origin, delta)) in [(start.x, direction.x), (start.y, direction.y), (start.z, direction.z)].into_iter().enumerate() {
365            let (low, high) = (lo[k] - pad, hi[k] + pad);
366            if delta.abs() <= f64::MIN_POSITIVE {
367                if origin < low || origin > high {
368                    return None;
369                }
370                continue;
371            }
372            let (a, b) = ((low - origin) / delta, (high - origin) / delta);
373            s0 = s0.max(a.min(b));
374            s1 = s1.min(a.max(b));
375            if s0 > s1 {
376                return None;
377            }
378        }
379        Some([s0, s1])
380    };
381    let mut stretches: Vec<[f64; 2]> = Vec::new();
382    let mut pending: Vec<(usize, usize, [f64; 2], [f64; 2], u32)> =
383        (0..spans_u).flat_map(|i| (0..spans_v).map(move |j| (i, j, [0.0, 1.0], [0.0, 1.0], 0))).collect();
384    // A ray running along the surface keeps meeting pieces: past this many the
385    // seeds all stay.
386    let mut visits = 0usize;
387    while let Some((i, j, range_u, range_v, depth)) = pending.pop() {
388        visits += 1;
389        if visits > 4096 {
390            return None;
391        }
392        let (lo, hi) = crate::curve_clear::patch_piece_box(surface, i, j, range_u, range_v)?;
393        let Some(along) = stretch(lo, hi) else {
394            continue;
395        };
396        if along[1] - along[0] <= step || depth >= 12 {
397            stretches.push(along);
398            continue;
399        }
400        let (mu, mv) = (0.5 * (range_u[0] + range_u[1]), 0.5 * (range_v[0] + range_v[1]));
401        for (u, v) in [([range_u[0], mu], [range_v[0], mv]), ([mu, range_u[1]], [range_v[0], mv]), ([range_u[0], mu], [mv, range_v[1]]), ([mu, range_u[1]], [mv, range_v[1]])] {
402            pending.push((i, j, u, v, depth + 1));
403        }
404    }
405    let span = t1 - t0;
406    Some(
407        seeds
408            .iter()
409            .copied()
410            .filter(|&seed| {
411                let s = (seed - t0) / span;
412                stretches.iter().any(|&[a, b]| s + step >= a && s - step <= b)
413            })
414            .collect(),
415    )
416}
417
418fn solve_counted(
419    curve: &NurbsCurve,
420    surface: &NurbsSurface,
421    tolerance: f64,
422    seeds: &[f64],
423    ray: bool,
424) -> Result<Vec<CurveSurfaceIntersection>, String> {
425    if !ray || !newton_local_start_enabled() {
426        return solve_from_seeds(curve, surface, tolerance, seeds, false, false);
427    }
428    if !newton_local_start_check() {
429        return solve_from_seeds(curve, surface, tolerance, seeds, true, false);
430    }
431    let local = solve_from_seeds(curve, surface, tolerance, seeds, true, true)?;
432    let global = solve_from_seeds(curve, surface, tolerance, seeds, false, false)?;
433    START_CHECK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
434    if !same_hits(&local, &global, tolerance) {
435        START_CHECK_HIT_DISAGREEMENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
436        let read = |hits: &[CurveSurfaceIntersection]| hits.iter().map(|hit| hit.t).collect::<Vec<_>>();
437        eprintln!(
438            "cs newton start check: hits differ: local t {:?} global t {:?}",
439            read(&local),
440            read(&global)
441        );
442    }
443    Ok(local)
444}
445
446/// The two starts read the same hits: as many, each at the same place within
447/// the duplicate guard's chord (`tolerance * 10`), with the same tangency.
448fn same_hits(first: &[CurveSurfaceIntersection], second: &[CurveSurfaceIntersection], tolerance: f64) -> bool {
449    first.len() == second.len()
450        && first.iter().zip(second).all(|(a, b)| {
451            a.point.sub(b.point).length() <= tolerance * 10.0 && a.tangential == b.tangential
452        })
453}
454
455fn solve_from_seeds(
456    curve: &NurbsCurve,
457    surface: &NurbsSurface,
458    tolerance: f64,
459    seeds: &[f64],
460    local_start: bool,
461    check: bool,
462) -> Result<Vec<CurveSurfaceIntersection>, String> {
463    let [t0, t1] = curve.domain()?;
464    let mut results: Vec<CurveSurfaceIntersection> = Vec::new();
465    for &seed in seeds {
466        let [t, u, v] = newton_curve_surface(curve, surface, seed, local_start, check)?;
467        let on_curve = curve.evaluate(t)?;
468        let on_surface = surface.evaluate(u, v)?;
469        let gap = on_curve.sub(on_surface).length();
470        if gap > tolerance {
471            continue;
472        }
473        let tangent = curve.deriv1(t)?.1;
474        // Two hits are the SAME hit when they are at the same PLACE, and the
475        // chord test below is what measures that. This parameter test only has
476        // to absorb two seeds landing on one root a few ulps apart — and it
477        // converts the caller's 3D tolerance into a parameter tolerance by
478        // dividing by the curve's speed, a quotient that is unbounded where the
479        // speed is not. At a stationary parameter the `EPSILON` floor makes it
480        // `1e-7 / 1e-12 * 10 = 1e6`, wider than any curve's domain, so every
481        // earlier hit on the curve reads as a duplicate and a legitimate
482        // intersection AT a cusp is discarded unless it happens to be first.
483        // An involute flank's speed is `r_base * t`, so a gear profile carries
484        // one such cusp per flank per tooth: this is the 2026-09-14 herringbone
485        // report's root cause one lane over, where it is silent rather than
486        // loud.
487        //
488        // The cap is the curve's OWN domain, which is the only scale this test
489        // has: 1e-6 of it keeps the ulp-absorbing job (nine orders above the
490        // `1e-15 * (t1 - t0)` stall the Newton above exits on, three above the
491        // 1e-9 floor this rule already had) and drops the unbounded one. Two
492        // seeds on the same cusp root can land further apart than that in
493        // parameter, but not in space, and the chord test catches them.
494        // Escape hatch for tamper-verification:
495        // BREP_CS_DUPLICATE_CAP=0 restores the uncapped tolerance.
496        let uncapped = ((tolerance / tangent.length().max(EPSILON)) * 10.0).max((t1 - t0) * 1e-9);
497        let capped = uncapped.min((t1 - t0) * 1e-6);
498        let parameter_tolerance = if duplicate_cap_enabled() { capped } else { uncapped };
499        if let Some(result) = results.iter().find(|result| {
500            (result.t - t).abs() <= parameter_tolerance
501                || result.point.sub(on_curve).length() <= tolerance * 10.0
502        }) {
503            // The only drops the cap changes: a PARAMETER-only match (the two
504            // hits are apart in space) that the capped tolerance would keep. A
505            // hit dropped here leaves no trace anywhere else, so name it when
506            // asked: `BREP_DEBUG_CS_DUPLICATE=1`. With the cap on this prints
507            // nothing by construction; under `BREP_CS_DUPLICATE_CAP=0` it counts
508            // what the cap recovers.
509            let chord = result.point.sub(on_curve).length();
510            let gap = (result.t - t).abs();
511            if chord > tolerance * 10.0
512                && gap > capped
513                && std::env::var("BREP_DEBUG_CS_DUPLICATE").is_ok()
514            {
515                eprintln!(
516                    "cs-duplicate: dropped t={t:.12} against t={:.12} gap={gap:.6e} ptol={parameter_tolerance:.6e} \
517                     chord={chord:.6e} |tangent|={:.6e} domain=[{t0:.6},{t1:.6}] tolerance={tolerance:.3e}",
518                    result.t,
519                    tangent.length(),
520                );
521            }
522            continue;
523        }
524        let normal = surface.normal(u, v).ok();
525        let tangential = normal
526            .and_then(|normal| {
527                tangent
528                    .normalized()
529                    .ok()
530                    .map(|unit| normal.dot(unit).abs() <= 1e-3)
531            })
532            .unwrap_or(false);
533        results.push(CurveSurfaceIntersection {
534            t,
535            u,
536            v,
537            point: on_curve.add(on_surface).scale(0.5),
538            gap,
539            tangential,
540        });
541    }
542    results.sort_by(|a, b| a.t.total_cmp(&b.t));
543    Ok(results)
544}
545