Skip to main content

brep_geometry/geometry/analytic_surface/
intersect.rs

1use super::*;
2pub use super::recognition::{generatrix_is_meridional_half_ray, surface_scale};
3use super::revolution::{intersect_coaxial_revolutions, intersect_cylinder_radius_invariant, rotate_curve_about_axis};
4
5/// Exact plane data extracted from an affine patch.
6struct PlaneData {
7    origin: Vec3,
8    normal: Vec3,
9}
10
11fn plane_data(analytic: &AnalyticSurface) -> Option<PlaneData> {
12    match analytic {
13        AnalyticSurface::Plane {
14            origin,
15            u_dir,
16            v_dir,
17            ..
18        } => Some(PlaneData {
19            origin: *origin,
20            normal: u_dir.cross(*v_dir).normalized().ok()?,
21        }),
22        _ => None,
23    }
24}
25
26/// Apply a homogeneous 4x4-style map to a rational curve's control points.
27/// `map` produces the image (x', y', z', w') of each homogeneous control
28/// point; weights must come back strictly one-signed or the section is not
29/// an ellipse/circle and we refuse it.
30fn map_rational_curve(
31    curve: &NurbsCurve,
32    map: impl Fn(crate::Vec4) -> crate::Vec4,
33) -> Option<NurbsCurve> {
34    let mut controls = Vec::with_capacity(curve.control_points.len());
35    let mut sign = 0.0f64;
36    for point in &curve.control_points {
37        let image = map(*point);
38        if image.w == 0.0 || !image.w.is_finite() {
39            return None;
40        }
41        if sign == 0.0 {
42            sign = image.w.signum();
43        } else if image.w.signum() != sign {
44            return None;
45        }
46        controls.push(image);
47    }
48    if sign < 0.0 {
49        for point in &mut controls {
50            point.x = -point.x;
51            point.y = -point.y;
52            point.z = -point.z;
53            point.w = -point.w;
54        }
55    }
56    NurbsCurve::new(curve.degree, curve.knots.clone(), controls).ok()
57}
58
59/// `BREP_CONE_PLANE_OPEN_SECTION` (default off, `1` on): a plane cutting a
60/// cone or frustum in a parabola or hyperbola is answered with the section's
61/// arcs inside the carrier's axial band ([`cone_plane_open_section`]) instead
62/// of being left to the marcher.
63fn cone_plane_open_section_enabled() -> bool {
64    crate::switch!(live "BREP_CONE_PLANE_OPEN_SECTION", false)
65}
66
67/// A plane's open (parabolic or hyperbolic) section of a cone or frustum,
68/// exactly, over the carrier's axial band. The section point over the base
69/// circle's angle θ is the circle point projected from the apex onto the
70/// plane: homogeneous-linear in (cos θ, sin θ, 1), with weight
71/// `w(θ) = A + B cos θ + C sin θ` and axial coordinate `z_apex + K / w(θ)`
72/// (every base point sits at one height). The band's ends and `w = 0` (the
73/// section's points at infinity) are each `R cos(θ − φ) = c` in closed form;
74/// between consecutive roots `w` keeps its sign, so a base-circle arc there
75/// maps to an exact rational quadratic. The arcs whose middle lies in the band
76/// are returned.
77#[allow(clippy::too_many_arguments)]
78fn cone_plane_open_section(
79    frame: &RevolutionFrame,
80    height: f64,
81    apex: Vec3,
82    reference_rho: f64,
83    reference_z: f64,
84    k: f64,
85    normal: Vec3,
86    tolerance: f64,
87    project: &dyn Fn(crate::Vec4) -> crate::Vec4,
88) -> Option<Vec<NurbsCurve>> {
89    let center = frame.origin.add(frame.axis.scale(reference_z));
90    let a = center.sub(apex).dot(normal);
91    let b = reference_rho * frame.x_axis.dot(normal);
92    let c = reference_rho * frame.y_axis.dot(normal);
93    let r = (b * b + c * c).sqrt();
94    let z_apex = apex.sub(frame.origin).dot(frame.axis);
95    // `K` in z(θ) = z_apex + K / w(θ): k times the base circle's height over the apex.
96    let big_k = k * (reference_z - z_apex);
97    let (band_low, band_high) = (0.0_f64.min(height), 0.0_f64.max(height));
98    let margin = tolerance.max(1e-12);
99    let axial = |theta: f64| -> Option<f64> {
100        let w = a + b * theta.cos() + c * theta.sin();
101        (w.abs() > 1e-300).then(|| z_apex + big_k / w)
102    };
103    let mut roots: Vec<f64> = Vec::new();
104    let mut solve = |target: f64| {
105        // b cos θ + c sin θ = target − a.
106        if r <= 0.0 {
107            return;
108        }
109        let ratio = (target - a) / r;
110        if ratio.abs() > 1.0 {
111            return;
112        }
113        let phi = c.atan2(b);
114        let spread = ratio.acos();
115        for theta in [phi + spread, phi - spread] {
116            roots.push(theta.rem_euclid(std::f64::consts::TAU));
117        }
118    };
119    solve(0.0);
120    for end in [band_low, band_high] {
121        let offset = end - z_apex;
122        if offset.abs() > 1e-300 {
123            solve(big_k / offset);
124        }
125    }
126    roots.sort_by(f64::total_cmp);
127    roots.dedup();
128    if roots.is_empty() {
129        roots.push(0.0);
130    }
131    let mut arcs = Vec::new();
132    for index in 0..roots.len() {
133        let start = roots[index];
134        let mut end = if index + 1 < roots.len() { roots[index + 1] } else { roots[0] + std::f64::consts::TAU };
135        if roots.len() == 1 {
136            end = start + std::f64::consts::TAU;
137        }
138        // Only an empty interval is skipped: a thin one in angle can be a
139        // long branch (a plane close to a large cone's axis); one too thin to
140        // build an arc on refuses below and leaves the pair to the marcher.
141        if !(end > start) {
142            continue;
143        }
144        let middle = 0.5 * (start + end);
145        let Some(z) = axial(middle) else { continue };
146        if z < band_low - margin || z > band_high + margin {
147            continue;
148        }
149        let arc = make_arc(center, frame.x_axis, frame.y_axis, reference_rho, start, end).ok()?;
150        // Within the interval the weight keeps its sign: the image is exact.
151        arcs.push(map_rational_curve(&arc, project)?);
152    }
153    Some(arcs)
154}
155
156/// The full u-circle of a revolution surface at radial distance `rho` and
157/// axial height `z`, built with the same arc construction as the surface.
158fn frame_circle(frame: &RevolutionFrame, rho: f64, z: f64) -> Option<NurbsCurve> {
159    make_arc(
160        frame.origin.add(frame.axis.scale(z)),
161        frame.x_axis,
162        frame.y_axis,
163        rho,
164        0.0,
165        std::f64::consts::TAU,
166    )
167    .ok()
168}
169
170/// Exact intersection curves for recognized analytic pairs, or `None` when
171/// the pair is not handled and the caller must fall back to SSI marching.
172/// `Some(vec![])` means "provably empty" and skips marching entirely.
173pub fn intersect_analytic_pair(
174    first: &NurbsSurface,
175    second: &NurbsSurface,
176    tolerance: f64,
177) -> Option<Vec<NurbsCurve>> {
178    intersect_analytic_pair_with(first, second, tolerance, ruled_gate())
179}
180
181/// Which predicate admits a general revolution's generatrix as the straight
182/// line of a cone, frustum or cylinder in [`intersect_analytic_pair`].
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum RuledGate {
185    /// The count proxy: degree 1, exactly two control points, unit weights.
186    Count,
187    /// What the section constructions consume: the generatrix's two ends, and
188    /// that the curve between them is the straight segment joining them
189    /// ([`NurbsCurve::straight_segment`]).
190    Geometry,
191}
192
193/// The gate the boolean runs: straightness, which is all the section
194/// constructions read. The count proxy declined a knot-refined, degree-elevated
195/// or re-weighted generatrix of the same cone and sent the pair to the marcher.
196/// Escape hatch for measurement: `BREP_RULED_GATE_GEOMETRY=0` runs the count
197/// gate.
198pub fn ruled_gate() -> RuledGate {
199    if std::env::var("BREP_RULED_GATE_GEOMETRY").as_deref() == Ok("0") {
200        RuledGate::Count
201    } else {
202        RuledGate::Geometry
203    }
204}
205
206/// [`intersect_analytic_pair`] under a named generatrix gate — what the fit
207/// census asks of the gate the boolean does NOT run.
208pub fn intersect_analytic_pair_with(
209    first: &NurbsSurface,
210    second: &NurbsSurface,
211    tolerance: f64,
212    gate: RuledGate,
213) -> Option<Vec<NurbsCurve>> {
214    // A ball and a cylinder tangent inside it: Viviani's curve, exact
215    // (`BREP_SPHERE_CYLINDER_TANGENT_SECTION`).
216    if let Some(curves) = super::sphere_cylinder_tangent::intersect_sphere_cylinder_tangent(first, second, tolerance) {
217        return Some(curves);
218    }
219    if let Some(curves) = intersect_recognized_pair(first, second, tolerance, gate) {
220        return Some(curves);
221    }
222    if crate::switch!("BREP_EXTRUSION_SECTIONS", true) {
223        for (plane, swept) in [(first,second),(second,first)] {
224            if matches!(swept.analytic(),Some(AnalyticSurface::Plane { .. })) { continue; }
225            if let (Some(plane),Some(extrusion)) = (plane.analytic().and_then(plane_data),swept.linear_extrusion()) {
226                if let Some(curves) = super::plane_extrusion_section(extrusion,plane.origin,plane.normal,tolerance) { return Some(curves); }
227            }
228        }
229        if !matches!(first.analytic(),Some(AnalyticSurface::Plane { .. })) && !matches!(second.analytic(),Some(AnalyticSurface::Plane { .. })) {
230        if let (Some(a),Some(b)) = (first.linear_extrusion(),second.linear_extrusion()) {
231            if let Some(curves) = super::parallel_extrusion_sections(a,b,tolerance) { return Some(curves); }
232        }
233        }
234    }
235    if let Some(curves) = intersect_plane_affine_sphere(first, second, tolerance) {
236        return Some(curves);
237    }
238    if let Some(curves) = intersect_coaxial_revolutions(first, second, tolerance) {
239        return Some(curves);
240    }
241    if coaxial_iso_section_enabled() {
242        if let Some(curves) = intersect_cylinder_radius_invariant(first, second, tolerance) {
243            return Some(curves);
244        }
245        if let Some(curves) = intersect_cylinder_radius_invariant(second, first, tolerance) {
246            return Some(curves);
247        }
248    }
249    // Only under the production gate: the count gate is the escape hatch that
250    // measures the old routing (`ruled_gate_admits_a_straight_generatrix_
251    // whatever_it_counts` reads it sending a re-weighted cone to the marcher).
252    if gate == RuledGate::Geometry && plane_revolution_section_enabled() {
253        if let Some(curves) = intersect_perpendicular_plane_revolution(first, second, tolerance) {
254            return Some(curves);
255        }
256        if let Some(curves) = intersect_perpendicular_plane_revolution(second, first, tolerance) {
257            return Some(curves);
258        }
259    }
260    if let Some(curves) = intersect_axial_plane_revolution(first, second, tolerance) {
261        return Some(curves);
262    }
263    intersect_axial_plane_revolution(second, first, tolerance)
264}
265
266/// `BREP_COAXIAL_ISO_SECTION` (default on; `=0` leaves the pair to the
267/// marcher): a cylinder against a surface
268/// whose radius about its axis is invariant along one parameter
269/// ([`intersect_cylinder_radius_invariant`]).
270fn coaxial_iso_section_enabled() -> bool {
271    crate::switch!("BREP_COAXIAL_ISO_SECTION", true)
272}
273
274/// PLANE x REVOLUTION SECTION (2026-11-06;
275/// `BREP_PLANE_REVOLUTION_SECTION`, default on, `=0` off). A plane square to the axis
276/// of a general surface of revolution (one no quadric arm reads: a revolved
277/// parabola, a revolved spline) meets it in one circle per height at which the
278/// generatrix crosses the plane, over the revolution's sweep. No arm read this
279/// pair, so it went to the marcher, which seeds on a grid and finds no loop
280/// much smaller than the faces: brep-bench
281/// `tangent/paraboloid-tip-a-ten-thousandth-high` (a size-8 paraboloid cut by
282/// z = 1e-4, a rim circle of radius 0.028) read "no boundary faces".
283///
284/// The lane answers only when every crossing is clean: each a sign change of
285/// the generatrix's height over the plane, transversal, and away from the
286/// generatrix's ends and from the axis, and the scan's crossings are as many
287/// as the generatrix's control points change sides of the plane (so none can
288/// hide between two stations). A touching height, a crossing at a
289/// rim the face already has as an edge, or no crossing at all keeps the pair
290/// on the paths it took before (`None`).
291fn plane_revolution_section_enabled() -> bool {
292    crate::switch!("BREP_PLANE_REVOLUTION_SECTION", true)
293}
294
295fn intersect_perpendicular_plane_revolution(
296    plane_surface: &NurbsSurface,
297    revolution: &NurbsSurface,
298    tolerance: f64,
299) -> Option<Vec<NurbsCurve>> {
300    let plane = plane_data(plane_surface.analytic()?)?;
301    if matches!(revolution.analytic(), Some(AnalyticSurface::Plane { .. })) {
302        return None;
303    }
304    let structure = super::revolution::revolution_structure(revolution)?;
305    let frame = &structure.frame;
306    if plane.normal.dot(frame.axis).abs() < 1.0 - 1e-12 {
307        return None;
308    }
309    let generatrix = &structure.generatrix;
310    let [start, end] = generatrix.domain().ok()?;
311    let height = |t: f64| -> Option<f64> { Some(generatrix.evaluate(t).ok()?.sub(plane.origin).dot(plane.normal)) };
312    let scale = surface_scale(revolution).max(1.0);
313    let band = tolerance.max(1e-9 * scale);
314    let spans = generatrix.knots.windows(2).filter(|pair| pair[1] > pair[0]).count().max(1);
315    let stations = 64 * spans;
316    let mut previous_t = start;
317    let mut previous = height(start)?;
318    // A generatrix end ON the plane is a rim the face has as an edge.
319    if previous.abs() <= band || height(end)?.abs() <= band {
320        return None;
321    }
322    let mut roots = Vec::new();
323    for index in 1..=stations {
324        let t = start + (end - start) * index as f64 / stations as f64;
325        let value = height(t)?;
326        if value.abs() <= band && index < stations {
327            // A station on the plane: a touching height or a crossing exactly
328            // here; the bisection below cannot tell them apart.
329            return None;
330        }
331        if (previous < 0.0) != (value < 0.0) {
332            let (mut lo, mut hi, mut lo_value) = (previous_t, t, previous);
333            for _ in 0..200 {
334                let middle = 0.5 * (lo + hi);
335                if middle <= lo || middle >= hi {
336                    break;
337                }
338                let middle_value = height(middle)?;
339                if (middle_value < 0.0) == (lo_value < 0.0) {
340                    lo = middle;
341                    lo_value = middle_value;
342                } else {
343                    hi = middle;
344                }
345            }
346            roots.push(0.5 * (lo + hi));
347        }
348        previous_t = t;
349        previous = value;
350    }
351    if roots.is_empty() {
352        return None;
353    }
354    // The height's numerator `sum w_i ((P_i - o).n) N_i(t)` is a B-spline, so
355    // it has no more roots than its coefficients have sign changes (variation
356    // diminishing). A count above the scan's means two crossings may share a
357    // station, which the scan cannot see: decline rather than drop a circle.
358    let mut coefficient_signs = Vec::new();
359    for control in &generatrix.control_points {
360        if control.w <= 0.0 {
361            return None;
362        }
363        let value = control.point().ok()?.sub(plane.origin).dot(plane.normal);
364        if value.abs() <= band {
365            return None;
366        }
367        coefficient_signs.push(value > 0.0);
368    }
369    let sign_changes = coefficient_signs.windows(2).filter(|pair| pair[0] != pair[1]).count();
370    if sign_changes != roots.len() {
371        return None;
372    }
373    let radius_floor = (tolerance * 10.0).max(1e-9 * scale);
374    let mut curves = Vec::new();
375    for root in roots {
376        let derivatives = generatrix.derivatives(root, 1).ok()?;
377        let tangent = derivatives.get(1)?.normalized().ok()?;
378        if tangent.dot(plane.normal).abs() <= 1e-9 {
379            return None;
380        }
381        let point = generatrix.evaluate(root).ok()?;
382        let (_, radius, axial) = frame.cylindrical(point);
383        if radius <= radius_floor {
384            return None;
385        }
386        let center = frame.origin.add(frame.axis.scale(axial));
387        // The crossing turns from ITS azimuth: zero for a profile in the start
388        // meridian, not for a straight profile skew to the axis (a hyperboloid).
389        let phase = if generatrix_is_meridional_half_ray(generatrix, frame) {
390            0.0
391        } else {
392            let radial = point.sub(center);
393            radial.dot(frame.y_axis).atan2(radial.dot(frame.x_axis))
394        };
395        curves.push(make_arc(center, frame.x_axis, frame.y_axis, radius, phase, phase + structure.sweep).ok()?);
396    }
397    Some(curves)
398}
399
400/// Exact intersection of a plane CONTAINING the revolution axis with a
401/// surface of revolution: the meridian profile rotated to the (at most
402/// two) angles where the plane crosses the sweep. The marcher fits these
403/// as long noisy polylines otherwise (a revolve's start/end caps against
404/// the other operand's revolved walls in revolve-with-holes booleans).
405fn intersect_axial_plane_revolution(
406    plane_surface: &NurbsSurface,
407    revolved: &NurbsSurface,
408    _tolerance: f64,
409) -> Option<Vec<NurbsCurve>> {
410    let plane = match plane_surface.analytic()? {
411        AnalyticSurface::Plane {
412            origin,
413            u_dir,
414            v_dir,
415            ..
416        } => (*origin, u_dir.cross(*v_dir).normalized().ok()?),
417        _ => return None,
418    };
419    let structure = revolution_structure(revolved)?;
420    if !generatrix_is_meridional_half_ray(&structure.generatrix, &structure.frame) {
421        return None;
422    }
423    let scale = surface_scale(plane_surface)
424        .max(surface_scale(revolved))
425        .max(1.0);
426    let (plane_origin, plane_normal) = plane;
427    if structure.frame.axis.dot(plane_normal).abs() > 1e-9 {
428        return None;
429    }
430    if structure
431        .frame
432        .origin
433        .sub(plane_origin)
434        .dot(plane_normal)
435        .abs()
436        > 1e-9 * scale
437    {
438        return None;
439    }
440    let radial = structure.frame.axis.cross(plane_normal).normalized().ok()?;
441    let tau = std::f64::consts::TAU;
442    let mut curves = Vec::new();
443    for direction in [radial, radial.scale(-1.0)] {
444        let mut angle = direction
445            .dot(structure.frame.y_axis)
446            .atan2(direction.dot(structure.frame.x_axis));
447        if angle < -1e-9 {
448            angle += tau;
449        }
450        if angle <= structure.sweep + 1e-9 {
451            curves.push(rotate_curve_about_axis(
452                &structure.generatrix,
453                structure.frame.origin,
454                structure.frame.axis,
455                angle.clamp(0.0, structure.sweep),
456            )?);
457        }
458    }
459    Some(curves)
460}
461
462/// Plane x affine sphere (`geometry/affine_sphere.rs`, under
463/// `BREP_AFFINE_SPHERE`): the exact ellipse, either operand order. Nothing
464/// else pairs with an ellipsoid in closed form (sphere, cylinder and cone
465/// sections of it are quartics; the marcher keeps them).
466fn intersect_plane_affine_sphere(
467    first: &NurbsSurface,
468    second: &NurbsSurface,
469    tolerance: f64,
470) -> Option<Vec<NurbsCurve>> {
471    for (plane_surface, other) in [(first, second), (second, first)] {
472        let Some(ellipsoid) = other.affine_sphere() else { continue };
473        let Some(plane) = plane_surface.analytic().and_then(plane_data) else { continue };
474        return ellipsoid.plane_section(plane.origin, plane.normal, tolerance);
475    }
476    None
477}
478
479fn intersect_recognized_pair(
480    first: &NurbsSurface,
481    second: &NurbsSurface,
482    tolerance: f64,
483    gate: RuledGate,
484) -> Option<Vec<NurbsCurve>> {
485    let a = first.analytic()?;
486    let b = second.analytic()?;
487    if !matches!(b, AnalyticSurface::Plane { .. }) {
488        if let Some(plane) = plane_data(a) {
489            return intersect_plane_quadric(&plane, b, tolerance, gate);
490        }
491    }
492    if !matches!(a, AnalyticSurface::Plane { .. }) {
493        if let Some(plane) = plane_data(b) {
494            return intersect_plane_quadric(&plane, a, tolerance, gate);
495        }
496    }
497    // Sphere×sphere, whichever way each sphere is parameterized (a reflected
498    // sphere recognizes as a general `Revolution`; see `sphere_geometry`).
499    if let (Some((center_a, radius_a)), Some((center_b, radius_b))) =
500        (a.sphere_geometry(), b.sphere_geometry())
501    {
502        return intersect_sphere_sphere(center_a, radius_a, center_b, radius_b, tolerance);
503    }
504    if let Some(curves) = intersect_sphere_coaxial_ruled(a, b, tolerance, gate)
505        .or_else(|| intersect_sphere_coaxial_ruled(b, a, tolerance, gate))
506    {
507        return Some(curves);
508    }
509    if let Some(curves) = intersect_equal_cylinders_meeting_axes(first, second, a, b, tolerance, gate) {
510        return Some(curves);
511    }
512    // The residual conic is cut from the first carrier and checked on the
513    // second; a wide partial cone first can fail where the other order
514    // reads the same section, so both orders are asked.
515    if let Some(curves) = intersect_cones_sharing_a_ruling(a, b, tolerance, gate)
516        .or_else(|| intersect_cones_sharing_a_ruling(b, a, tolerance, gate))
517    {
518        return Some(curves);
519    }
520    // Plane×plane is deliberately NOT special-cased: the iso path
521    // already returns axis-aligned box intersections exactly, and a
522    // synthesized over-long line segment interacts poorly with the
523    // shared-parameter pcurve contract in process_curve (the pcurve is
524    // fitted over the face crossing only, so the curve's [t0,t1]
525    // subrange and the pcurve domain drift apart on long overhangs).
526    None
527}
528
529/// `BREP_SPHERE_CONE_COAXIAL` (default off, `1` on): a sphere against a cone,
530/// frustum or cylinder whose axis passes through the sphere's centre
531/// ([`intersect_sphere_coaxial_ruled`]).
532fn sphere_cone_coaxial_enabled() -> bool {
533    crate::switch!(live "BREP_SPHERE_CONE_COAXIAL", false)
534}
535
536/// A sphere (any carrier [`AnalyticSurface::sphere_geometry`] reads, a partial
537/// sweep included under `BREP_PARTIAL_SPHERE`) against a ruled revolution
538/// whose axis passes through its centre: the pair is coaxial, so the section
539/// is the circles about that axis at the heights `z` where the generatrix's
540/// radius `ρ(z) = ρ₀ + m z` reaches the sphere, `(z − z_c)² + ρ(z)² = r²`, a
541/// quadratic. Roots off the generatrix's own nappe or outside its axial band
542/// are dropped; no real root is a proved-empty pair.
543fn intersect_sphere_coaxial_ruled(
544    sphere: &AnalyticSurface,
545    ruled: &AnalyticSurface,
546    tolerance: f64,
547    gate: RuledGate,
548) -> Option<Vec<NurbsCurve>> {
549    if !sphere_cone_coaxial_enabled() {
550        return None;
551    }
552    let (center, radius) = sphere.sphere_geometry()?;
553    let (frame, rho0, rho1, height) = ruled_revolution_data(ruled, tolerance, gate)?;
554    let offset = center.sub(frame.origin);
555    let center_z = offset.dot(frame.axis);
556    let off_axis = offset.sub(frame.axis.scale(center_z)).length();
557    // Bands relative to the sphere, where the section is: never to the
558    // ruled carrier's length or its distance from its frame origin.
559    // The coaxial test is relative to the sphere; the section's own bands
560    // (a circle's radius, the carrier's axial ends) are the tolerance itself.
561    if off_axis > tolerance.max(1e-12) * (1.0 + radius) {
562        return None;
563    }
564    let margin = tolerance.max(1e-12);
565    let slope = (rho1 - rho0) / height;
566    // In the centre's axial frame, z' = z − z_c, with ρ_c the generatrix's
567    // radius at the centre's height: z'² + (ρ_c + m z')² = r² (no cancellation
568    // against a far frame origin).
569    let rho_center = rho0 + slope * center_z;
570    let a = 1.0 + slope * slope;
571    let b = 2.0 * slope * rho_center;
572    let c = rho_center * rho_center - radius * radius;
573    let discriminant = b * b - 4.0 * a * c;
574    let mut heights = Vec::new();
575    if discriminant > 0.0 {
576        let root = discriminant.sqrt();
577        let q = -0.5 * (b + if b >= 0.0 { root } else { -root });
578        if q != 0.0 {
579            heights.push(center_z + q / a);
580            heights.push(center_z + c / q);
581        } else {
582            heights.push(center_z);
583        }
584    }
585    // A tangent contact (a double root, the generatrix touching the sphere
586    // along a circle) is left to the tangent-contact lanes, which place the
587    // circle's seam and its touching vertices; this lane answers transverse
588    // sections only.
589    // Roots closer than 2e-6 of the radius (√disc / a is their separation)
590    // are a tangency up to round-off, e.g. an equator contact about a
591    // rotated axis: as ill-conditioned as an exact one, so left there too.
592    let separation_bar = 2e-6 * radius * a;
593    if discriminant.abs() <= 1e-9 * (b * b + (4.0 * a * c).abs()).max(radius * radius * 1e-24)
594        || (discriminant > 0.0 && discriminant <= separation_bar * separation_bar)
595    {
596        return None;
597    }
598    let (band_low, band_high) = (0.0_f64.min(height), 0.0_f64.max(height));
599    let mut circles = Vec::new();
600    for z in heights {
601        let rho = rho0 + slope * z;
602        if rho < -margin || z < band_low - margin || z > band_high + margin || rho <= margin {
603            continue;
604        }
605        circles.push(frame_circle(&frame, rho, z)?);
606    }
607    Some(circles)
608}
609
610/// `BREP_CONE_SHARED_RULING` (default off, `1` on): two cones tangent along a
611/// shared ruling ([`intersect_cones_sharing_a_ruling`]).
612fn cone_shared_ruling_enabled() -> bool {
613    crate::switch!(live "BREP_CONE_SHARED_RULING", false)
614}
615
616/// A cone (or frustum) carrier as its double cone: apex, unit axis, and
617/// `cos²` of the half-angle, with the frame and extent it was read from.
618struct ConeData {
619    apex: Vec3,
620    axis: Vec3,
621    cos2: f64,
622    frame: RevolutionFrame,
623    height: f64,
624    /// The swept angle from the frame's x axis (`TAU` for a full revolution).
625    sweep: f64,
626    /// The carrier's own size: its axial extent and largest radius.
627    size: f64,
628}
629
630fn cone_data(quadric: &AnalyticSurface, tolerance: f64, gate: RuledGate) -> Option<ConeData> {
631    let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
632    let slope = (rho1 - rho0) / height;
633    if !(slope.is_finite() && slope.abs() > 1e-9) {
634        return None;
635    }
636    let apex = frame.origin.add(frame.axis.scale(-rho0 / slope));
637    let sweep = match quadric {
638        AnalyticSurface::Revolution { sweep, .. } => *sweep,
639        _ => std::f64::consts::TAU,
640    };
641    let size = height.abs().max(rho0.abs()).max(rho1.abs());
642    Some(ConeData { apex, axis: frame.axis, cos2: 1.0 / (1.0 + slope * slope), frame, height, sweep, size })
643}
644
645impl ConeData {
646    /// `((X − A)·d)² − cos²α |X − A|²`: zero on the double cone.
647    fn value(&self, point: Vec3) -> f64 {
648        let d = point.sub(self.apex);
649        let along = d.dot(self.axis);
650        along * along - self.cos2 * d.dot(d)
651    }
652
653    /// The distance from `point` to the double cone, to first order.
654    fn distance(&self, point: Vec3) -> f64 {
655        let d = point.sub(self.apex);
656        let gradient = self.axis.scale(2.0 * d.dot(self.axis)).sub(d.scale(2.0 * self.cos2));
657        let norm = gradient.length();
658        if norm > 0.0 { self.value(point).abs() / norm } else { d.length() }
659    }
660
661    /// The quadric's symmetric 4×4 matrix on homogeneous `(x, 1)`.
662    fn matrix(&self) -> [[f64; 4]; 4] {
663        let d = [self.axis.x, self.axis.y, self.axis.z];
664        let a = [self.apex.x, self.apex.y, self.apex.z];
665        let mut m = [[0.0; 4]; 4];
666        let mut da = [0.0; 3];
667        for i in 0..3 {
668            for j in 0..3 {
669                m[i][j] = d[i] * d[j] - if i == j { self.cos2 } else { 0.0 };
670            }
671        }
672        for i in 0..3 {
673            da[i] = (0..3).map(|j| m[i][j] * a[j]).sum();
674        }
675        for i in 0..3 {
676            m[i][3] = -da[i];
677            m[3][i] = -da[i];
678        }
679        m[3][3] = (0..3).map(|i| a[i] * da[i]).sum();
680        m
681    }
682
683    /// Whether `point`'s azimuth about the axis lies in the swept range (with
684    /// `slack` radians either side); a point on the axis is in every one.
685    fn within_sweep(&self, point: Vec3, slack: f64) -> bool {
686        if self.sweep >= std::f64::consts::TAU - 1e-12 {
687            return true;
688        }
689        match self.frame.cylindrical(point).0 {
690            None => true,
691            Some(theta) => theta <= self.sweep + slack || theta >= std::f64::consts::TAU - slack,
692        }
693    }
694
695    /// Whether `point` lies within the carrier's axial extent (so on its own
696    /// nappe of the double cone), with `slack` either side.
697    fn within_extent(&self, point: Vec3, slack: f64) -> bool {
698        let axial = point.sub(self.frame.origin).dot(self.frame.axis);
699        axial >= 0.0_f64.min(self.height) - slack && axial <= 0.0_f64.max(self.height) + slack
700    }
701
702    /// The parameter range along the line `origin + s·direction` over which
703    /// it lies within this carrier's axial extent.
704    fn extent_along(&self, origin: Vec3, direction: Vec3) -> Option<[f64; 2]> {
705        let rate = direction.dot(self.frame.axis);
706        if rate.abs() <= 1e-12 {
707            return None;
708        }
709        let at = origin.sub(self.frame.origin).dot(self.frame.axis);
710        let (low, high) = (0.0_f64.min(self.height), 0.0_f64.max(self.height));
711        let (s0, s1) = ((low - at) / rate, (high - at) / rate);
712        Some([s0.min(s1), s0.max(s1)])
713    }
714}
715
716/// The pieces of `curve` (rational, degree at most 2) within `cone`'s axial
717/// extent, cut EXACTLY where it crosses either end of the band: within each
718/// knot span the axial coordinate times the homogeneous weight is a
719/// polynomial of degree at most 2 in the parameter, read from three
720/// homogeneous evaluations, so every crossing is a root of a quadratic and no
721/// arc that enters and leaves the band between samples is missed. `None` for a
722/// curve of higher degree or a cut that cannot be made.
723fn pieces_within_extent(curve: &NurbsCurve, cone: &ConeData, slack: f64) -> Option<Vec<NurbsCurve>> {
724    if curve.degree > 2 {
725        return None;
726    }
727    let (low, high) = (0.0_f64.min(cone.height) - slack, 0.0_f64.max(cone.height) + slack);
728    let axial_times_weight = |t: f64, bound: f64| -> Option<f64> {
729        let h = curve.evaluate_homogeneous(t).ok()?;
730        let along = Vec3::new(h.x, h.y, h.z).sub(cone.frame.origin.scale(h.w)).dot(cone.frame.axis);
731        Some(along - bound * h.w)
732    };
733    let mut breaks: Vec<f64> = curve.knots.iter().copied().collect();
734    breaks.sort_by(f64::total_cmp);
735    breaks.dedup();
736    let mut cuts = Vec::new();
737    for pair in breaks.windows(2) {
738        let (t0, t1) = (pair[0], pair[1]);
739        if !(t1 > t0) {
740            continue;
741        }
742        for bound in [low, high] {
743            // f(t) = a s² + b s + c on s ∈ [0, 1] from f(0), f(½), f(1).
744            let (f0, fm, f1) = (axial_times_weight(t0, bound)?, axial_times_weight(0.5 * (t0 + t1), bound)?, axial_times_weight(t1, bound)?);
745            let a = 2.0 * f1 - 4.0 * fm + 2.0 * f0;
746            let b = 4.0 * fm - f1 - 3.0 * f0;
747            let c = f0;
748            let mut roots = Vec::new();
749            if a.abs() <= 1e-14 * (b.abs() + c.abs()).max(1e-300) {
750                if b != 0.0 {
751                    roots.push(-c / b);
752                }
753            } else {
754                let discriminant = b * b - 4.0 * a * c;
755                if discriminant >= 0.0 {
756                    let root = discriminant.sqrt();
757                    let q = -0.5 * (b + b.signum() * root);
758                    if q != 0.0 {
759                        roots.push(q / a);
760                        roots.push(c / q);
761                    }
762                }
763            }
764            // A crossing at a span's end (an internal knot) is a cut too;
765            // the curve's own ends are dropped below.
766            for s in roots {
767                if s >= -1e-12 && s <= 1.0 + 1e-12 {
768                    cuts.push(t0 + s.clamp(0.0, 1.0) * (t1 - t0));
769                }
770            }
771        }
772    }
773    cuts.sort_by(f64::total_cmp);
774    cuts.dedup();
775    let inside = |point: Vec3| cone.within_extent(point, slack);
776    let mut pieces = Vec::new();
777    let mut rest = curve.clone();
778    for cut in cuts {
779        let [r0, r1] = rest.domain().ok()?;
780        if cut <= r0 + 1e-12 * (r1 - r0).abs().max(1.0) || cut >= r1 - 1e-12 * (r1 - r0).abs().max(1.0) {
781            continue;
782        }
783        let (left, right) = rest.split(cut).ok()?;
784        pieces.push(left);
785        rest = right;
786    }
787    pieces.push(rest);
788    let mut kept = Vec::new();
789    for piece in pieces {
790        let [p0, p1] = piece.domain().ok()?;
791        if inside(piece.evaluate(0.5 * (p0 + p1)).ok()?) {
792            kept.push(piece);
793        }
794    }
795    Some(kept)
796}
797
798/// Two cones TANGENT ALONG A SHARED RULING. A ruling of each passes through
799/// its apex, so a shared one is the line through both apexes; it lies on
800/// each double cone when it makes that cone's half-angle with the axis, and
801/// a cone's tangent plane is constant along a ruling, so the cones are
802/// tangent along the whole line when their tangent planes there agree. The
803/// quartic intersection is then the ruling twice and a residual conic: in
804/// the pencil `Q₁ − λQ₂` the member vanishing on the common tangent plane `T`
805/// (λ read at one point of `T` off the ruling, where each cone restricts to
806/// the doubled ruling) is the plane pair `T ∪ π`, and the conic is either cone
807/// cut by `π`. The ruling is returned over both carriers' axial extents and
808/// the conic as the first carrier's plane section, checked on the second.
809/// A pair whose residual section cannot be read is left to the marcher.
810///
811/// A cone filled out to its sphere and the revolves of its half-sections
812/// about a line through the apex plane (brep-bench cone-spun): the cones the
813/// half-section's generators sweep are tangent to the turned cone along the
814/// generators, and the marcher could not settle the tangent pair, so one
815/// union order refused.
816fn intersect_cones_sharing_a_ruling(
817    a: &AnalyticSurface,
818    b: &AnalyticSurface,
819    tolerance: f64,
820    gate: RuledGate,
821) -> Option<Vec<NurbsCurve>> {
822    if !cone_shared_ruling_enabled() {
823        return None;
824    }
825    let (first, second) = (cone_data(a, tolerance, gate)?, cone_data(b, tolerance, gate)?);
826    let between = second.apex.sub(first.apex);
827    let length = between.length();
828    // Bands relative to the carriers' own size, not to where they sit.
829    let scale = 1.0 + first.size.max(second.size);
830    if !(length > 1e-9 * scale) {
831        return None;
832    }
833    let line = between.scale(1.0 / length);
834    // The apex line lies on both double cones.
835    for cone in [&first, &second] {
836        let along = line.dot(cone.axis);
837        if (along * along - cone.cos2).abs() > 1e-9 {
838            return None;
839        }
840    }
841    // Their tangent planes along it agree.
842    let normal_first = first.axis.cross(line).cross(line).normalized().ok()?;
843    let normal_second = second.axis.cross(line).cross(line).normalized().ok()?;
844    if normal_first.cross(normal_second).length() > 1e-9 {
845        return None;
846    }
847    // λ at a point of T off the ruling.
848    let off = first.apex.add(normal_first.cross(line).scale(length.max(1.0)));
849    let (value_first, value_second) = (first.value(off), second.value(off));
850    if !(value_second.abs() > 1e-12 * (1.0 + value_first.abs())) {
851        return None;
852    }
853    let lambda = value_first / value_second;
854    let (m_first, m_second) = (first.matrix(), second.matrix());
855    let mut pencil = [[0.0; 4]; 4];
856    for i in 0..4 {
857        for j in 0..4 {
858            pencil[i][j] = m_first[i][j] - lambda * m_second[i][j];
859        }
860    }
861    let t = [normal_first.x, normal_first.y, normal_first.z, -normal_first.dot(first.apex)];
862    let homogeneous = |point: Vec3| [point.x, point.y, point.z, 1.0];
863    let apply = |m: &[[f64; 4]; 4], x: [f64; 4]| -> [f64; 4] {
864        let mut out = [0.0; 4];
865        for i in 0..4 {
866            out[i] = (0..4).map(|j| m[i][j] * x[j]).sum();
867        }
868        out
869    };
870    let dot4 = |p: [f64; 4], q: [f64; 4]| p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3];
871    // π from one point y off T: P y = ½(t (π·y) + π (t·y)).
872    let y = homogeneous(first.apex.add(normal_first.scale(length.max(1.0))));
873    let s = dot4(t, y);
874    if !(s.abs() > 1e-12) {
875        return None;
876    }
877    let py = apply(&pencil, y);
878    let pi_y = dot4(y, py) / s;
879    let mut pi = [0.0; 4];
880    for i in 0..4 {
881        pi[i] = (2.0 * py[i] - t[i] * pi_y) / s;
882    }
883    // The member is that plane pair: its value at a few points is (t·x)(π·x).
884    for probe in [second.apex.add(Vec3::new(0.37, -0.21, 0.53).scale(length)), first.apex.add(Vec3::new(-0.44, 0.61, 0.17).scale(length)), off.add(line.scale(0.3 * length))] {
885        let x = homogeneous(probe);
886        let member = dot4(x, apply(&pencil, x));
887        let pair = dot4(t, x) * dot4(pi, x);
888        if (member - pair).abs() > 1e-8 * (1.0 + member.abs().max(pair.abs())) {
889            return None;
890        }
891    }
892    let mut curves = Vec::new();
893    // The ruling over both carriers' axial extents.
894    if let (Some([a0, a1]), Some([b0, b1])) = (first.extent_along(first.apex, line), second.extent_along(first.apex, line)) {
895        let (s0, s1) = (a0.max(b0), a1.min(b1));
896        let (start, end) = (first.apex.add(line.scale(s0)), first.apex.add(line.scale(s1)));
897        let middle = start.add(end).scale(0.5);
898        if std::env::var_os("BREP_DEBUG_CONE_RULING").is_some() {
899            eprintln!(
900                "cone ruling: s [{s0:.6}, {s1:.6}] from {start:?} to {end:?}; middle theta first {:?} (sweep {:.6}) second {:?} (sweep {:.6})",
901                first.frame.cylindrical(middle).0, first.sweep, second.frame.cylindrical(middle).0, second.sweep
902            );
903        }
904        // A ruling outside a partial revolution's sweep is not on that face.
905        // Any ruling longer than the tolerance itself is a section.
906        if s1 - s0 > tolerance.max(1e-12) && first.within_sweep(middle, 1e-9) && second.within_sweep(middle, 1e-9) {
907            curves.push(crate::make_line(start, end).ok()?);
908        }
909    }
910    // The residual conic on π, when π is a real plane other than T.
911    let pi_normal = Vec3::new(pi[0], pi[1], pi[2]);
912    let pi_length = pi_normal.length();
913    if pi_length > 1e-12 * (1.0 + pi[3].abs()) {
914        let unit = pi_normal.scale(1.0 / pi_length);
915        let origin = pi_normal.scale(-pi[3] / (pi_length * pi_length));
916        let same_as_t = unit.cross(normal_first).length() <= 1e-9 && (unit.dot(first.apex) + pi[3] / pi_length).abs() <= tolerance;
917        if !same_as_t {
918            let plane = PlaneData { origin, normal: unit };
919            let conics = intersect_plane_quadric(&plane, a, tolerance, gate)?;
920            for conic in conics {
921                let [c0, c1] = conic.domain().ok()?;
922                let (mut inside, mut outside) = (0, 0);
923                for k in 0..=32 {
924                    let point = conic.evaluate(c0 + (c1 - c0) * k as f64 / 32.0).ok()?;
925                    if second.distance(point) > 1e3 * tolerance.max(1e-12) * scale {
926                        return None;
927                    }
928                    if first.within_sweep(point, 1e-9) && second.within_sweep(point, 1e-9) {
929                        inside += 1;
930                    } else {
931                        outside += 1;
932                    }
933                }
934                if std::env::var_os("BREP_DEBUG_CONE_RULING").is_some() {
935                    let ends = (conic.evaluate(c0).ok(), conic.evaluate(c1).ok());
936                    eprintln!("cone ruling conic: inside {inside} outside {outside}; ends {ends:?}; sweeps {:.6} {:.6}", first.sweep, second.sweep);
937                }
938                // The sweep counts above are read for the debug line only:
939                // nothing declines on them. The section is of the first
940                // carrier, whose plane section is returned whole once its
941                // band admits it (an ellipse is not cut to the first
942                // carrier's extent); on the second it must also lie on that
943                // carrier's own nappe and axial extent, so the pieces past it
944                // are cut off. A conic past a partial sweep's end continues on
945                // the revolution's own extension; the imprint clips it to the
946                // faces' trims.
947                let slack = tolerance.max(1e-12) * scale;
948                curves.extend(pieces_within_extent(&conic, &second, slack)?);
949            }
950        }
951    }
952    Some(curves)
953}
954
955/// `BREP_EQUAL_CYLINDER_SECTIONS` (default on, `0` off): two cylinders of one
956/// radius whose axes meet ([`intersect_equal_cylinders_meeting_axes`]).
957fn equal_cylinder_sections_enabled() -> bool {
958    crate::switch!(live "BREP_EQUAL_CYLINDER_SECTIONS", true)
959}
960
961/// Two cylinders of ONE radius whose axes meet at a point `C` (not parallel):
962/// a point at distance `r` from both axes lies on one of the two planes
963/// through `C` that bisect the axes (normals `a - b` and `a + b`), so the
964/// intersection is exactly the two plane sections of either cylinder, two
965/// ellipses that cross where the two surfaces are tangent (the points of
966/// the circle of radius `r` about `C` along `a x b`). This is the joint of
967/// two straight slides of one ball-ended tool, whose envelope cylinders
968/// share the joint ball: their crease is the section square to the mean
969/// axis, and at a shallow angle a march seeded at the tangent points reads
970/// the pair as touching only (2026-11-18, the ball-end raster). The sections
971/// are of the first carrier; every station is checked on the second.
972fn intersect_equal_cylinders_meeting_axes(
973    surface_a: &NurbsSurface,
974    surface_b: &NurbsSurface,
975    a: &AnalyticSurface,
976    b: &AnalyticSurface,
977    tolerance: f64,
978    gate: RuledGate,
979) -> Option<Vec<NurbsCurve>> {
980    if !equal_cylinder_sections_enabled() {
981        return None;
982    }
983    let (frame_a, rho0_a, rho1_a, _) = ruled_revolution_data(a, tolerance, gate)?;
984    let (frame_b, rho0_b, rho1_b, _) = ruled_revolution_data(b, tolerance, gate)?;
985    // An absolute band at the caller's tolerance: one radius means one radius
986    // to the tolerance whatever the size (floored at what the radius itself
987    // can represent), never a share of the size or of the distance from the
988    // world origin.
989    let band = tolerance.max(4.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(rho0_b.abs()));
990    // ONE radius means one radius to round-off, not to the tolerance: two
991    // radii a tolerance apart meet in two branches that pass each other near
992    // the tangent points (a gap of order sqrt(r dr)), not in two crossing
993    // ellipses, and such a pair is the march's.
994    let same_radius = 16.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(rho0_b.abs());
995    if (rho0_a - rho1_a).abs() > band || (rho0_b - rho1_b).abs() > band || (rho0_a - rho0_b).abs() > same_radius || rho0_a <= band {
996        return None;
997    }
998    let (radius, radius_b) = (rho0_a, rho0_b);
999    let (da, mut db) = (frame_a.axis.normalized().ok()?, frame_b.axis.normalized().ok()?);
1000    if da.dot(db) < 0.0 {
1001        db = db.scale(-1.0);
1002    }
1003    let cross = da.cross(db);
1004    let sine = cross.length();
1005    // Parallel axes are the coaxial / parallel lanes' business; below this
1006    // angle the meeting point is not determined to `band`.
1007    if sine <= 1e-6 {
1008        return None;
1009    }
1010    // The axes must MEET, to round-off as the radii must agree: axes a
1011    // tolerance apart (skew) give two branches that pass each other near the
1012    // tangent points (a gap of order sqrt(r d)), not crossing ellipses.
1013    let offset = frame_b.origin.sub(frame_a.origin);
1014    let skew = offset.dot(cross.scale(1.0 / sine)).abs();
1015    let meet = 16.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(frame_a.origin.length()).max(frame_b.origin.length());
1016    if std::env::var_os("BREP_DEBUG_EQUAL_CYLINDERS").is_some() {
1017        eprintln!("equal cylinders: skew {skew:.3e} (round-off bar {meet:.3e}), radii {rho0_a} / {rho0_b}");
1018    }
1019    if skew > meet {
1020        return None;
1021    }
1022    // C = A0 + s da with (A0 + s da - B0) x db = 0: s = ((B0 - A0) x db)·(da x db) / |da x db|^2.
1023    let s = offset.cross(db).dot(cross) / (sine * sine);
1024    let centre = frame_a.origin.add(da.scale(s));
1025    let off_axis = |point: Vec3, origin: Vec3, axis: Vec3, rho: f64| {
1026        let delta = point.sub(origin);
1027        (delta.sub(axis.scale(delta.dot(axis))).length() - rho).abs()
1028    };
1029    // Each CARRIER is the cylinder its recognition names: a straight
1030    // generatrix with equal end radii also describes a hyperboloid (a line
1031    // skew to the axis), which is not this closed form.
1032    for (surface, origin, axis, rho) in [(surface_a, frame_a.origin, da, radius), (surface_b, frame_b.origin, db, radius_b)] {
1033        let ([u0, u1], [v0, v1]) = (surface.domain_u().ok()?, surface.domain_v().ok()?);
1034        for i in 0..=6 {
1035            for j in 0..=6 {
1036                let point = surface.evaluate(u0 + (u1 - u0) * i as f64 / 6.0, v0 + (v1 - v0) * j as f64 / 6.0).ok()?;
1037                if off_axis(point, origin, axis, rho) > band {
1038                    return None;
1039                }
1040            }
1041        }
1042    }
1043    let on_b = |point: Vec3| off_axis(point, frame_b.origin, db, radius_b);
1044    // Where the surfaces are tangent and the two ellipses cross.
1045    let across = cross.scale(radius / sine);
1046    let tangent_points = [centre.add(across), centre.sub(across)];
1047    let mut curves = Vec::new();
1048    for normal in [da.sub(db), da.add(db)] {
1049        let normal = normal.normalized().ok()?;
1050        let plane = PlaneData { origin: centre, normal };
1051        for curve in intersect_plane_quadric(&plane, a, tolerance, gate)? {
1052            let [t0, t1] = curve.domain().ok()?;
1053            for index in 0..=16 {
1054                let point = curve.evaluate(t0 + (t1 - t0) * index as f64 / 16.0).ok()?;
1055                if on_b(point) > band * 10.0 {
1056                    return None;
1057                }
1058            }
1059            if equal_cylinder_tangent_split_enabled() {
1060                curves.extend(split_at_points(curve, &tangent_points, band * 10.0)?);
1061            } else {
1062                curves.push(curve);
1063            }
1064        }
1065    }
1066    Some(curves)
1067}
1068
1069/// `BREP_EQUAL_CYLINDER_TANGENT_SPLIT` (default on; `=0` keeps them whole): each ellipse of
1070/// [`intersect_equal_cylinders_meeting_axes`] is split at the two points where
1071/// the surfaces are tangent, where it crosses the other ellipse, so the four
1072/// arcs meet at shared vertices. Whole, the two closed ellipses of a Steinmetz
1073/// pair at the origin crossed without a junction: every boolean of the pair
1074/// left open loops, and the perturbation ladder then marched for minutes.
1075fn equal_cylinder_tangent_split_enabled() -> bool {
1076    crate::switch!(live "BREP_EQUAL_CYLINDER_TANGENT_SPLIT", true)
1077}
1078
1079/// `curve` cut at each of `points` it passes within `reach` of (by its nearest
1080/// parameter), pieces in order; the curve whole when it passes none. A point
1081/// an end of the curve already stands on needs no cut (that end is the
1082/// junction). `None`, so the caller declines to the march, when a cut cannot
1083/// be made where the point is: the split refuses a parameter at an end, and
1084/// it snaps one near a knot, so every cut's junction is read again after it.
1085fn split_at_points(curve: NurbsCurve, points: &[Vec3], reach: f64) -> Option<Vec<NurbsCurve>> {
1086    let [t0, t1] = curve.domain().ok()?;
1087    let (start, end) = (curve.evaluate(t0).ok()?, curve.evaluate(t1).ok()?);
1088    let mut cuts: Vec<(f64, Vec3)> = Vec::new();
1089    for &point in points {
1090        if start.sub(point).length() <= reach || end.sub(point).length() <= reach {
1091            continue;
1092        }
1093        let foot = crate::project_point_to_curve(&curve, point).ok()?;
1094        if foot.distance <= reach {
1095            if !(foot.u > t0 && foot.u < t1) {
1096                return None;
1097            }
1098            cuts.push((foot.u, point));
1099        }
1100    }
1101    cuts.sort_by(|a, b| a.0.total_cmp(&b.0));
1102    cuts.dedup_by(|a, b| (a.0 - b.0).abs() <= 1e-12 * (t1 - t0));
1103    let mut pieces = Vec::new();
1104    let mut rest = curve;
1105    for (cut, point) in cuts.into_iter().rev() {
1106        let (left, right) = rest.split(cut).ok()?;
1107        let [_, left_end] = left.domain().ok()?;
1108        let [right_start, _] = right.domain().ok()?;
1109        if left.evaluate(left_end).ok()?.sub(point).length() > reach || right.evaluate(right_start).ok()?.sub(point).length() > reach {
1110            return None;
1111        }
1112        pieces.push(right);
1113        rest = left;
1114    }
1115    pieces.push(rest);
1116    pieces.reverse();
1117    Some(pieces)
1118}
1119
1120/// Frame/meridian data for any revolution with a straight-line generatrix:
1121/// the `RuledRevolution` quadrics themselves, plus partial-sweep
1122/// `Revolution`s whose generatrix the named gate admits as straight (fillet
1123/// cutter walls are quarter cylinders of this shape). The plane
1124/// intersectors only need the carrier geometry — the boolean trims the
1125/// returned curves to the actual face domains afterwards.
1126fn ruled_revolution_data(
1127    quadric: &AnalyticSurface,
1128    tolerance: f64,
1129    gate: RuledGate,
1130) -> Option<(RevolutionFrame, f64, f64, f64)> {
1131    match quadric {
1132        AnalyticSurface::RuledRevolution {
1133            frame,
1134            rho0,
1135            rho1,
1136            height,
1137        } => Some((frame.clone(), *rho0, *rho1, *height)),
1138        AnalyticSurface::Revolution {
1139            frame, generatrix, ..
1140        } => {
1141            // A straight profile skew to the axis sweeps a hyperboloid, not a
1142            // cone: only a profile in the start meridian reads as one.
1143            if !generatrix_is_meridional_half_ray(generatrix, frame) {
1144                return None;
1145            }
1146            let (start, end) = match gate {
1147                RuledGate::Count => {
1148                    let controls = &generatrix.control_points;
1149                    if generatrix.degree != 1
1150                        || controls.len() != 2
1151                        || (controls[0].w - 1.0).abs() > RECOGNITION_TOLERANCE
1152                        || (controls[1].w - 1.0).abs() > RECOGNITION_TOLERANCE
1153                    {
1154                        return None;
1155                    }
1156                    (controls[0].point().ok()?, controls[1].point().ok()?)
1157                }
1158                RuledGate::Geometry => generatrix.straight_segment(tolerance)?,
1159            };
1160            let (_, rho0, z0) = frame.cylindrical(start);
1161            let (_, rho1, z1) = frame.cylindrical(end);
1162            let height = z1 - z0;
1163            if height.abs() <= 1e-12 * (1.0 + rho0.abs().max(rho1.abs())) {
1164                return None;
1165            }
1166            let origin = frame.origin.add(frame.axis.scale(z0));
1167            Some((
1168                RevolutionFrame {
1169                    origin,
1170                    ..frame.clone()
1171                },
1172                rho0,
1173                rho1,
1174                height,
1175            ))
1176        }
1177        _ => None,
1178    }
1179}
1180
1181/// CENSUS ONLY (`BREP_FIT_CENSUS=1`): a description of `surface`'s generatrix
1182/// when it is a general revolution the two generatrix gates answer
1183/// differently, `None` otherwise.
1184pub fn ruled_gate_census(surface: &NurbsSurface, tolerance: f64) -> Option<String> {
1185    let quadric = surface.analytic()?;
1186    let AnalyticSurface::Revolution { generatrix, .. } = quadric else {
1187        return None;
1188    };
1189    let count = ruled_revolution_data(quadric, tolerance, RuledGate::Count).is_some();
1190    let geometry = ruled_revolution_data(quadric, tolerance, RuledGate::Geometry).is_some();
1191    if count == geometry {
1192        return None;
1193    }
1194    let controls = &generatrix.control_points;
1195    let points: Vec<Vec3> = controls
1196        .iter()
1197        .map(|control| control.point().unwrap_or_default())
1198        .collect();
1199    let (first, last) = (points[0], points[points.len() - 1]);
1200    let direction = last.sub(first);
1201    let length_squared = direction.length_squared();
1202    let mut collinearity = 0.0_f64;
1203    for point in &points {
1204        collinearity = collinearity.max(if length_squared <= 0.0 {
1205            point.sub(first).length()
1206        } else {
1207            let fraction = (point.sub(first).dot(direction) / length_squared).clamp(0.0, 1.0);
1208            point.sub(first.add(direction.scale(fraction))).length()
1209        });
1210    }
1211    let unit_weights = controls
1212        .iter()
1213        .all(|control| (control.w - 1.0).abs() <= RECOGNITION_TOLERANCE);
1214    Some(format!(
1215        "degree={} controls={} collinearity={collinearity:.3e} unit_weights={unit_weights} \
1216         count_gate={count} geometry_gate={geometry}",
1217        generatrix.degree,
1218        controls.len()
1219    ))
1220}
1221
1222/// TRUE when a recognized frustum's radius drift is below the precision floor
1223/// of the cone construction itself, so the plane section must take the
1224/// CYLINDER branch. The cone branch builds its conic as a projective image of
1225/// a base circle toward the apex at distance ~|height|·max|ρ|/|Δρ|; the map's
1226/// floating-point error grows like that distance × machine epsilon, so for a
1227/// near-cylinder frustum (t363: Δρ = 2.23e-12 over height 1500, apex ~1.5e16)
1228/// the "exact analytic" section comes back up to ~1 mm off BOTH surfaces.
1229/// Downstream, `build_pcurve_on_surface` honestly measures that deviation on
1230/// the curved operand, drops every interior sample, and collapses the ring's
1231/// pcurve to a single point — the face under-splits and the boolean fails
1232/// with one-use edges / non-integral genus.
1233///
1234/// Branch selection by error balance: the cylinder approximation errs by at
1235/// most |Δρ|, the cone construction by ~ε·|height|·max|ρ|/|Δρ|; prefer the
1236/// cylinder when its error is smaller, i.e. Δρ² ≤ ε·|height|·max|ρ| (with a
1237/// modest constant for the map's factors). This is a deterministic choice
1238/// between two exact-in-infinite-precision constructions — not a tolerance —
1239/// and can only ever pick the MORE accurate branch. The legacy absolute
1240/// 1e-12 acceptance remains as a floor at the call site. Escape hatch:
1241/// BREP_CONE_APEX_GUARD=0 restores the bare 1e-12 discrimination.
1242fn degenerate_apex_frustum(rho0: f64, rho1: f64, height: f64) -> bool {
1243    if std::env::var("BREP_CONE_APEX_GUARD").as_deref() == Ok("0") {
1244        return false;
1245    }
1246    let delta = rho1 - rho0;
1247    delta * delta <= 64.0 * f64::EPSILON * height.abs() * rho0.abs().max(rho1.abs())
1248}
1249
1250/// The EXACT arc of `plane ∩ ruled revolution` spanning a given AZIMUTH range
1251/// about the carrier's own frame — the arc-restricted, seam-anchorable form of
1252/// the full sections `intersect_plane_quadric` returns.
1253///
1254/// ADDITION, not a change: `intersect_plane_quadric` is untouched and still
1255/// answers every pair it answered before, bit for bit. This function exists
1256/// because a direct edit needs the section as an EDGE, not as a carrier
1257/// section, and an edge has endpoints: a closed rim must START at the face's
1258/// own seam vertex (which need not sit at the carrier's `u = 0` — see the
1259/// push-face seam fix), and an open rim is a sub-arc between two re-solved
1260/// corners. `intersect_plane_quadric` always returns the whole section anchored
1261/// at the frame's `x_axis`, so neither is expressible through it.
1262///
1263/// Both constructions below are the ones that function already uses, and both
1264/// preserve AZIMUTH — the cylinder's map adds only an axial component, the
1265/// cone's is a central projection from a point ON the axis — so "the arc from
1266/// azimuth `a` through `sweep`" is well defined on the section itself and the
1267/// anchoring is exact rather than fitted:
1268///
1269/// - **Cylinder** (`rho1 ≈ rho0`): the section is the AFFINE image of the base
1270///   circle under the axial shear `X ↦ X + axis·(c − n·X)/(n·axis)`, which is
1271///   linear in the homogeneous control point, so a rational-quadratic arc maps
1272///   to a rational-quadratic arc on the SAME knot vector.
1273/// - **Cone/frustum**: the section is the PROJECTIVE image from the apex,
1274///   `X ↦ apex + (k/((X−apex)·n))·(X−apex)`, again linear in the homogeneous
1275///   control point. A parabolic or hyperbolic section is built like an
1276///   elliptic one while the ARC stays clear of the generatrices parallel to the
1277///   plane: every point of it is then a finite image on one nappe and the
1278///   weights keep one sign. An arc that reaches such a generatrix (a closed rim
1279///   always does) has weights that change sign, and is refused by name rather
1280///   than silently mis-built — that generatrix never meets the plane.
1281///
1282/// `sweep` must be positive and at most a full turn; a reversed rim is built
1283/// forward and reversed by the caller, which is what keeps the knot vector the
1284/// arc construction's own.
1285pub fn plane_ruled_section_arc(
1286    plane_origin: Vec3,
1287    plane_normal: Vec3,
1288    frame: &RevolutionFrame,
1289    rho0: f64,
1290    rho1: f64,
1291    height: f64,
1292    start_azimuth: f64,
1293    sweep: f64,
1294    tolerance: f64,
1295) -> Result<NurbsCurve, String> {
1296    let tau = std::f64::consts::TAU;
1297    if !(start_azimuth.is_finite() && sweep.is_finite()) {
1298        return Err("plane_ruled_section_arc: non-finite azimuth range".into());
1299    }
1300    if sweep <= 1e-12 || sweep > tau + 1e-9 {
1301        return Err(format!(
1302            "plane_ruled_section_arc: the section arc sweeps {sweep:.6e} rad, which is not a \
1303             positive arc of at most one turn — refusing"
1304        ));
1305    }
1306    let normal = plane_normal.normalized()?;
1307    let radius_scale = rho0.abs().max(rho1.abs()).max(1.0);
1308    let axis = frame.axis;
1309    let is_cylinder = (rho1 - rho0).abs() <= 1e-9 * radius_scale
1310        || degenerate_apex_frustum(rho0, rho1, height);
1311    let curve = if is_cylinder {
1312        let alignment = normal.dot(axis);
1313        if alignment.abs() <= 1e-12 {
1314            return Err(
1315                "plane_ruled_section_arc: the plane is parallel to the cylinder axis, so the \
1316                 section is a generatrix pair rather than a conic — refusing"
1317                    .into(),
1318            );
1319        }
1320        if rho0.abs() <= tolerance {
1321            return Err("plane_ruled_section_arc: the cylinder carrier has no radius".into());
1322        }
1323        let base = make_arc(
1324            frame.origin,
1325            frame.x_axis,
1326            frame.y_axis,
1327            rho0.abs(),
1328            start_azimuth,
1329            start_azimuth + sweep,
1330        )?;
1331        let origin_dot = plane_origin.dot(normal);
1332        map_rational_curve(&base, |p| {
1333            let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / alignment;
1334            crate::Vec4 {
1335                x: p.x + axis.x * t,
1336                y: p.y + axis.y * t,
1337                z: p.z + axis.z * t,
1338                w: p.w,
1339            }
1340        })
1341        .ok_or_else(|| {
1342            "plane_ruled_section_arc: the cylinder section's weights are not one-signed \
1343             — refusing"
1344                .to_string()
1345        })?
1346    } else {
1347        let apex = frame.origin.add(axis.scale(height * rho0 / (rho0 - rho1)));
1348        let k = plane_origin.sub(apex).dot(normal);
1349        if k.abs() <= tolerance {
1350            return Err(
1351                "plane_ruled_section_arc: the plane passes through the cone apex, so the \
1352                 section is a line pair rather than a conic — refusing"
1353                    .into(),
1354            );
1355        }
1356        let (reference_rho, reference_z) = if rho0.abs() > rho1.abs() {
1357            (rho0.abs(), 0.0)
1358        } else {
1359            (rho1.abs(), height)
1360        };
1361        if reference_rho <= tolerance {
1362            return Err("plane_ruled_section_arc: the cone carrier degenerates to its apex".into());
1363        }
1364        let base = make_arc(
1365            frame.origin.add(axis.scale(reference_z)),
1366            frame.x_axis,
1367            frame.y_axis,
1368            reference_rho,
1369            start_azimuth,
1370            start_azimuth + sweep,
1371        )?;
1372        map_rational_curve(&base, |p| {
1373            let relative = Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
1374            let w_new = relative.dot(normal);
1375            let scaled = relative.scale(k);
1376            crate::Vec4 {
1377                x: apex.x * w_new + scaled.x,
1378                y: apex.y * w_new + scaled.y,
1379                z: apex.z * w_new + scaled.z,
1380                w: w_new,
1381            }
1382        })
1383        .ok_or_else(|| {
1384            "plane_ruled_section_arc: the section crosses the cone's apex plane (a parabolic \
1385             or hyperbolic branch, whose weights change sign) — refusing"
1386                .to_string()
1387        })?
1388    };
1389    // The construction is exact, so this measures rather than fits: every
1390    // sample must sit on BOTH carriers, at the carrier's own radius for its own
1391    // axial station and on the plane.
1392    let [d0, d1] = curve.domain()?;
1393    let slope = if height == 0.0 {
1394        0.0
1395    } else {
1396        (rho1 - rho0) / height
1397    };
1398    for step in 0..=8 {
1399        let point = curve.evaluate(d0 + (d1 - d0) * (step as f64 / 8.0))?;
1400        let delta = point.sub(frame.origin);
1401        let axial = delta.dot(axis);
1402        let radial = delta.sub(axis.scale(axial)).length();
1403        let off_ruled = (radial - (rho0 + slope * axial)).abs();
1404        let off_plane = point.sub(plane_origin).dot(normal).abs();
1405        if off_ruled > 10.0 * tolerance || off_plane > 10.0 * tolerance {
1406            return Err(format!(
1407                "plane_ruled_section_arc: the section does not lie on both carriers (off ruled \
1408                 {off_ruled:.3e}, off plane {off_plane:.3e}) — refusing"
1409            ));
1410        }
1411    }
1412    Ok(curve)
1413}
1414
1415fn intersect_plane_quadric(
1416    plane: &PlaneData,
1417    quadric: &AnalyticSurface,
1418    tolerance: f64,
1419    gate: RuledGate,
1420) -> Option<Vec<NurbsCurve>> {
1421    match quadric {
1422        AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. }
1423            if ruled_revolution_data(quadric, tolerance, gate).is_some() =>
1424        {
1425            let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
1426            let (frame, rho0, rho1, height) = (&frame, &rho0, &rho1, &height);
1427            let alignment = plane.normal.dot(frame.axis);
1428            if alignment.abs() >= 1.0 - 1e-12 {
1429                // Perpendicular plane: one circle at the plane's height.
1430                let z = plane.origin.sub(frame.origin).dot(frame.axis);
1431                let t = z / height;
1432                if !(-1e-9..=1.0 + 1e-9).contains(&t) {
1433                    return Some(Vec::new());
1434                }
1435                let rho = rho0 + (rho1 - rho0) * t.clamp(0.0, 1.0);
1436                if rho <= tolerance {
1437                    return Some(Vec::new());
1438                }
1439                return Some(vec![frame_circle(frame, rho, z)?]);
1440            }
1441            if (rho1 - rho0).abs() <= 1e-12 || degenerate_apex_frustum(*rho0, *rho1, *height) {
1442                // Cylinder.
1443                if alignment.abs() <= 1e-12 {
1444                    // Plane parallel to the axis: zero, one, or two
1445                    // generatrix lines at the circle/line crossing angles.
1446                    return cylinder_parallel_plane_lines(plane, frame, *rho0, *height, tolerance);
1447                }
1448                // Oblique section: exact ellipse as the affine image of a
1449                // base circle along the axis direction.
1450                let circle = frame_circle(frame, *rho0, 0.0)?;
1451                let denominator = alignment;
1452                let origin_dot = plane.origin.dot(plane.normal);
1453                let normal = plane.normal;
1454                let axis = frame.axis;
1455                let ellipse = map_rational_curve(&circle, |p| {
1456                    let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / denominator;
1457                    crate::Vec4 {
1458                        x: p.x + axis.x * t,
1459                        y: p.y + axis.y * t,
1460                        z: p.z + axis.z * t,
1461                        w: p.w,
1462                    }
1463                })?;
1464                if !section_within_band(&ellipse, frame, *height, tolerance) {
1465                    return Some(Vec::new());
1466                }
1467                return Some(vec![ellipse]);
1468            }
1469            // Cone/frustum: projective image of a base circle toward the
1470            // apex. Weight signs flip for parabolic/hyperbolic sections and
1471            // map_rational_curve refuses those (marcher fallback).
1472            let apex_t = rho0 / (rho0 - rho1);
1473            let apex = frame.origin.add(frame.axis.scale(height * apex_t));
1474            let reference_rho = if rho0.abs() > rho1.abs() {
1475                *rho0
1476            } else {
1477                *rho1
1478            };
1479            let reference_z = if rho0.abs() > rho1.abs() {
1480                0.0
1481            } else {
1482                *height
1483            };
1484            let circle = frame_circle(frame, reference_rho, reference_z)?;
1485            let k = plane.origin.sub(apex).dot(plane.normal);
1486            if k.abs() <= tolerance {
1487                // Plane through the apex: line pair; leave to the marcher.
1488                return None;
1489            }
1490            let normal = plane.normal;
1491            let project = |p: crate::Vec4| {
1492                let relative =
1493                    Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
1494                let w_new = relative.dot(normal);
1495                let scaled = relative.scale(k);
1496                crate::Vec4 {
1497                    x: apex.x * w_new + scaled.x,
1498                    y: apex.y * w_new + scaled.y,
1499                    z: apex.z * w_new + scaled.z,
1500                    w: w_new,
1501                }
1502            };
1503            let Some(conic) = map_rational_curve(&circle, project) else {
1504                // A parabola or hyperbola: its arcs inside the band.
1505                if cone_plane_open_section_enabled() {
1506                    return cone_plane_open_section(frame, *height, apex, reference_rho, reference_z, k, normal, tolerance, &project);
1507                }
1508                return None;
1509            };
1510            if !section_within_band(&conic, frame, *height, tolerance) {
1511                return Some(Vec::new());
1512            }
1513            Some(vec![conic])
1514        }
1515        AnalyticSurface::Sphere { frame, radius } => {
1516            plane_sphere_section(plane, frame.origin, *radius, tolerance)
1517        }
1518        AnalyticSurface::Torus {
1519            frame,
1520            major_radius,
1521            minor_radius,
1522        } => plane_torus_section(plane, frame, *major_radius, *minor_radius, tolerance),
1523        AnalyticSurface::Plane { .. } => None,
1524        AnalyticSurface::RuledRevolution { .. } => None,
1525        // A REFLECTED sphere or torus (mirror feature, negative-determinant
1526        // transform) recognizes as a general `Revolution` — same point set,
1527        // opposite parameter handedness — and keeps its closed-form sections.
1528        // Any other general revolution has none; the axial-plane and
1529        // tangential-contact paths in imprint own those.
1530        AnalyticSurface::Revolution { .. } => {
1531            if let Some((center, radius)) = quadric.sphere_geometry() {
1532                return plane_sphere_section(plane, center, radius, tolerance);
1533            }
1534            if let Some((frame, major_radius, minor_radius)) = quadric.torus_geometry() {
1535                return plane_torus_section(plane, &frame, major_radius, minor_radius, tolerance);
1536            }
1537            None
1538        }
1539    }
1540}
1541
1542/// Plane × sphere: one circle, or provably empty when the plane misses or
1543/// merely TOUCHES the sphere (a point contact imprints nothing).
1544fn plane_sphere_section(
1545    plane: &PlaneData,
1546    center: Vec3,
1547    radius: f64,
1548    tolerance: f64,
1549) -> Option<Vec<NurbsCurve>> {
1550    let distance = center.sub(plane.origin).dot(plane.normal);
1551    if distance.abs() >= radius - tolerance {
1552        return Some(Vec::new());
1553    }
1554    let circle_center = center.sub(plane.normal.scale(distance));
1555    let circle_radius = (radius * radius - distance * distance).sqrt();
1556    let x_axis = plane.normal.perpendicular().ok()?;
1557    let y_axis = plane.normal.cross(x_axis);
1558    Some(vec![make_arc(
1559        circle_center,
1560        x_axis,
1561        y_axis,
1562        circle_radius,
1563        0.0,
1564        std::f64::consts::TAU,
1565    )
1566    .ok()?])
1567}
1568
1569/// Plane ⟂ torus axis: the two latitude circles at the plane's height (one
1570/// when it grazes the tube's inner side), or provably empty above/below the
1571/// tube.  `frame.origin` must sit at the tube centre's axial position.  An
1572/// oblique plane has no closed form here (`None` → marcher).
1573fn plane_torus_section(
1574    plane: &PlaneData,
1575    frame: &RevolutionFrame,
1576    major_radius: f64,
1577    minor_radius: f64,
1578    tolerance: f64,
1579) -> Option<Vec<NurbsCurve>> {
1580    let alignment = plane.normal.dot(frame.axis);
1581    if alignment.abs() < 1.0 - 1e-12 {
1582        return None;
1583    }
1584    let z = plane.origin.sub(frame.origin).dot(frame.axis);
1585    if z.abs() >= minor_radius - tolerance {
1586        return Some(Vec::new());
1587    }
1588    let offset = (minor_radius * minor_radius - z * z).sqrt();
1589    let mut circles = Vec::new();
1590    for rho in [major_radius - offset, major_radius + offset] {
1591        if rho > tolerance {
1592            circles.push(frame_circle(frame, rho, z)?);
1593        }
1594    }
1595    Some(circles)
1596}
1597
1598/// Reject sections that entirely miss the ruled surface's axial band; the
1599/// imprint trimmer would discard them anyway, but skipping early avoids
1600/// building pcurves for out-of-band curves.
1601///
1602/// Uses the convex-hull property of a same-sign-weight rational curve: every
1603/// curve point's axial coordinate lies within the [min, max] axial span of the
1604/// Cartesian control points. So the section can only miss the band when the
1605/// WHOLE control-point span sits above or below it. The earlier `any(CP in
1606/// band)` test was wrong for near-axis-parallel oblique sections: the affine
1607/// map divides the axial displacement by `alignment`, flinging the rational
1608/// control points far to BOTH sides of the band (they straddle it with none
1609/// landing inside), so a genuine crossing arc was falsely rejected — the
1610/// missing cap∩cylinder imprint behind the curved-primitive open-edge /
1611/// non-integral-genus booleans. An interval-overlap test can never falsely
1612/// reject (hull property); a false accept is harmless (the imprint trimmer
1613/// clips the returned curve to the real face domains regardless).
1614fn section_within_band(
1615    curve: &NurbsCurve,
1616    frame: &RevolutionFrame,
1617    height: f64,
1618    tolerance: f64,
1619) -> bool {
1620    let (band_low, band_high) = if height >= 0.0 {
1621        (0.0, height)
1622    } else {
1623        (height, 0.0)
1624    };
1625    let margin = tolerance.max(1e-9) + 1e-9;
1626    let mut min_z = f64::INFINITY;
1627    let mut max_z = f64::NEG_INFINITY;
1628    for p in &curve.control_points {
1629        let z = Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)
1630            .sub(frame.origin)
1631            .dot(frame.axis);
1632        min_z = min_z.min(z);
1633        max_z = max_z.max(z);
1634    }
1635    // The control-point axial span overlaps the band.
1636    max_z >= band_low - margin && min_z <= band_high + margin
1637}
1638
1639fn cylinder_parallel_plane_lines(
1640    plane: &PlaneData,
1641    frame: &RevolutionFrame,
1642    radius: f64,
1643    height: f64,
1644    tolerance: f64,
1645) -> Option<Vec<NurbsCurve>> {
1646    // Distance from the axis to the plane, measured in the cross-section.
1647    let axis_to_plane = plane.origin.sub(frame.origin).dot(plane.normal);
1648    if axis_to_plane.abs() >= radius - tolerance {
1649        return Some(Vec::new());
1650    }
1651    // In-plane offset of the chord from the axis foot.
1652    let chord_half = (radius * radius - axis_to_plane * axis_to_plane).sqrt();
1653    let chord_direction = frame.axis.cross(plane.normal).normalized().ok()?;
1654    let foot = frame.origin.add(plane.normal.scale(axis_to_plane));
1655    let mut lines = Vec::new();
1656    for sign in [-1.0, 1.0] {
1657        let base = foot.add(chord_direction.scale(sign * chord_half));
1658        let top = base.add(frame.axis.scale(height));
1659        lines.push(crate::make_line(base, top).ok()?);
1660    }
1661    Some(lines)
1662}
1663
1664fn intersect_sphere_sphere(
1665    center_a: Vec3,
1666    radius_a: f64,
1667    center_b: Vec3,
1668    radius_b: f64,
1669    tolerance: f64,
1670) -> Option<Vec<NurbsCurve>> {
1671    let offset = center_b.sub(center_a);
1672    let distance = offset.length();
1673    if distance <= tolerance {
1674        // Concentric: empty or coincident; the cosurface path owns
1675        // coincident carriers.
1676        return if (radius_a - radius_b).abs() <= tolerance {
1677            None
1678        } else {
1679            Some(Vec::new())
1680        };
1681    }
1682    if distance >= radius_a + radius_b - tolerance
1683        || distance <= (radius_a - radius_b).abs() + tolerance
1684    {
1685        return Some(Vec::new());
1686    }
1687    let normal = offset.scale(1.0 / distance);
1688    let along =
1689        (distance * distance + radius_a * radius_a - radius_b * radius_b) / (2.0 * distance);
1690    let circle_radius_squared = radius_a * radius_a - along * along;
1691    if circle_radius_squared <= tolerance * tolerance {
1692        return Some(Vec::new());
1693    }
1694    let center = center_a.add(normal.scale(along));
1695    let x_axis = normal.perpendicular().ok()?;
1696    let y_axis = normal.cross(x_axis);
1697    Some(vec![make_arc(
1698        center,
1699        x_axis,
1700        y_axis,
1701        circle_radius_squared.sqrt(),
1702        0.0,
1703        std::f64::consts::TAU,
1704    )
1705    .ok()?])
1706}
1707
1708
1709
1710