Skip to main content

brepkit_math/
analytic_intersection.rs

1//! Closed-form and semi-analytic intersections of analytic surfaces with planes.
2//!
3//! Provides specialized intersection algorithms for cylinder, cone, sphere,
4//! and torus surfaces with planes, as well as a general marching approach
5//! for analytic-analytic surface intersections.
6
7use std::f64::consts::{FRAC_PI_2, TAU};
8
9use crate::MathError;
10use crate::curves::{Circle3D, Ellipse3D};
11use crate::frame::Frame3;
12use crate::nurbs::curve::NurbsCurve;
13use crate::nurbs::fitting::interpolate;
14use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
15use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
16use crate::tolerance::Tolerance;
17use crate::vec::{Point3, Vec3};
18
19/// Exact curve type resulting from plane-analytic surface intersection.
20#[derive(Debug, Clone)]
21pub enum ExactIntersectionCurve {
22    /// A circle (plane perpendicular to axis of cylinder/cone/sphere).
23    Circle(Circle3D),
24    /// An ellipse (plane oblique to cylinder/cone axis).
25    Ellipse(Ellipse3D),
26    /// Fallback to sampled point chain (torus, degenerate cases).
27    Points(Vec<Point3>),
28}
29
30/// Compute exact intersection curves between a plane and an analytic surface.
31///
32/// Returns exact `Circle3D` or `Ellipse3D` where possible, falling back to
33/// sampled points for complex cases (torus).
34///
35/// The plane is defined by `dot(normal, p) = d`.
36///
37/// # Errors
38///
39/// Returns an error if the intersection computation fails.
40pub fn exact_plane_analytic(
41    surface: AnalyticSurface<'_>,
42    plane_normal: Vec3,
43    plane_d: f64,
44) -> Result<Vec<ExactIntersectionCurve>, MathError> {
45    exact_plane_analytic_reaching(surface, plane_normal, plane_d, 0.0)
46}
47
48/// [`exact_plane_analytic`] with a cone's sampled hyperbola or parabola
49/// carried at least `reach` from the apex, so it spans whatever faces the
50/// caller will trim it to.
51///
52/// # Errors
53///
54/// Returns an error if the intersection computation fails.
55pub fn exact_plane_analytic_reaching(
56    surface: AnalyticSurface<'_>,
57    plane_normal: Vec3,
58    plane_d: f64,
59    reach: f64,
60) -> Result<Vec<ExactIntersectionCurve>, MathError> {
61    match surface {
62        AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
63        AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
64        AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d, reach),
65        AnalyticSurface::Torus(torus) => {
66            if let Some(circles) = exact_plane_torus(torus, plane_normal, plane_d)? {
67                return Ok(circles);
68            }
69            if let Some(loops) = plane_torus_winding_loops(torus, plane_normal, plane_d, 128) {
70                return Ok(loops
71                    .into_iter()
72                    .map(ExactIntersectionCurve::Points)
73                    .collect());
74            }
75            // Other torus sections are degree-4 — fall back to sampling.
76            let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
77            Ok(chains
78                .into_iter()
79                .map(ExactIntersectionCurve::Points)
80                .collect())
81        }
82    }
83}
84
85/// The plane-torus sections that are circles:
86///
87/// - a plane across the axis at height `h` from the centre, `|h| < r`: the
88///   two circles of radius `R ± sqrt(r² − h²)` about the axis;
89/// - a plane through the axis: the two tube cross-sections of radius `r`,
90///   `R` either side of the axis.
91///
92/// `Some` of no curves for a plane across the axis that misses the tube;
93/// `None` for any other plane, a plane tangent to the tube, or a torus whose
94/// tube reaches its axis.
95fn exact_plane_torus(
96    torus: &ToroidalSurface,
97    normal: Vec3,
98    d: f64,
99) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
100    let len = normal.length();
101    let n = normal.normalize()?;
102    let d = d / len;
103    let axis = torus.z_axis();
104    let center = torus.center();
105    let (big, small) = (torus.major_radius(), torus.minor_radius());
106    let height = d - dot_np(n, center);
107    let along = n.dot(axis);
108    if along.abs() > 1.0 - 1e-10 {
109        if height.abs() >= small - 1e-10 * small {
110            return Ok(if height.abs() > small + 1e-10 * small {
111                Some(Vec::new())
112            } else {
113                None
114            });
115        }
116        let reach = small.mul_add(small, -(height * height)).sqrt();
117        if big - reach <= 1e-10 * big {
118            return Ok(None);
119        }
120        let middle = center + n * height;
121        return Ok(Some(vec![
122            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big + reach)?),
123            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big - reach)?),
124        ]));
125    }
126    if along.abs() < 1e-10 && height.abs() < 1e-10 * (big + small) {
127        let out = axis.cross(n).normalize()?;
128        return Ok(Some(vec![
129            ExactIntersectionCurve::Circle(Circle3D::new(center + out * big, n, small)?),
130            ExactIntersectionCurve::Circle(Circle3D::new(center - out * big, n, small)?),
131        ]));
132    }
133    Ok(None)
134}
135
136/// Exact plane-cylinder intersection.
137///
138/// - Plane perpendicular to axis → `Circle3D`
139/// - Plane oblique to axis → `Ellipse3D`
140/// - Plane parallel to axis → `Points` fallback (0 or 2 lines)
141fn exact_plane_cylinder(
142    cyl: &CylindricalSurface,
143    normal: Vec3,
144    d: f64,
145) -> Result<Vec<ExactIntersectionCurve>, MathError> {
146    let axis = cyl.axis();
147    let cos_theta = normal.dot(axis).abs();
148    let r = cyl.radius();
149
150    if cos_theta < 1e-10 {
151        // Plane parallel to cylinder axis → 0 or 2 line segments.
152        // Fall back to sampled points.
153        let chains = sample_plane_cylinder(cyl, normal, d)?;
154        return Ok(chains
155            .into_iter()
156            .map(ExactIntersectionCurve::Points)
157            .collect());
158    }
159
160    // Find where axis intersects the plane: axis_point + t*axis, dot(normal, P) = d
161    // t = (d - dot(normal, origin)) / dot(normal, axis)
162    let n_dot_axis = normal.dot(axis);
163    let n_dot_origin = dot_np(normal, cyl.origin());
164    let t = (d - n_dot_origin) / n_dot_axis;
165    let center_on_axis = Point3::new(
166        cyl.origin().x() + t * axis.x(),
167        cyl.origin().y() + t * axis.y(),
168        cyl.origin().z() + t * axis.z(),
169    );
170
171    if cos_theta > 1.0 - 1e-10 {
172        // Plane perpendicular to axis → Circle
173        let circle = Circle3D::new(center_on_axis, normal, r)?;
174        Ok(vec![ExactIntersectionCurve::Circle(circle)])
175    } else {
176        // Oblique plane → Ellipse
177        // Semi-minor = r (the cylinder radius, unchanged)
178        // Semi-major = r / cos(θ) where θ = angle between plane normal and axis
179        let semi_minor = r;
180        let semi_major = r / cos_theta;
181
182        // The major axis direction lies in the intersection of the plane
183        // with the plane containing the axis and the plane normal.
184        // It's the projection of the axis onto the cutting plane, normalized.
185        let axis_proj = Vec3::new(
186            axis.x() - n_dot_axis * normal.x(),
187            axis.y() - n_dot_axis * normal.y(),
188            axis.z() - n_dot_axis * normal.z(),
189        );
190        let u_axis = axis_proj.normalize()?;
191        let v_axis = normal.cross(u_axis);
192
193        let ellipse = Ellipse3D::with_axes(
194            center_on_axis,
195            normal,
196            semi_major,
197            semi_minor,
198            u_axis,
199            v_axis,
200        )?;
201        Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
202    }
203}
204
205/// Exact plane-sphere intersection.
206///
207/// Always produces a `Circle3D` (or empty if no intersection).
208fn exact_plane_sphere(
209    sphere: &SphericalSurface,
210    normal: Vec3,
211    d: f64,
212) -> Result<Vec<ExactIntersectionCurve>, MathError> {
213    let h = dot_np(normal, sphere.center()) - d;
214    let r = sphere.radius();
215
216    if h.abs() > r - 1e-10 {
217        return Ok(vec![]);
218    }
219
220    let circle_r = (r.mul_add(r, -(h * h))).sqrt();
221    let circle_center = Point3::new(
222        h.mul_add(-normal.x(), sphere.center().x()),
223        h.mul_add(-normal.y(), sphere.center().y()),
224        h.mul_add(-normal.z(), sphere.center().z()),
225    );
226
227    let circle = Circle3D::new(circle_center, normal, circle_r)?;
228    Ok(vec![ExactIntersectionCurve::Circle(circle)])
229}
230
231/// Exact plane-cone intersection.
232///
233/// The conic type is set by the cone's half-opening angle from the axis
234/// (`γ = π/2 − half_angle`) versus the plane-axis angle `ψ`:
235/// - Plane perpendicular to axis (`ψ = π/2`) → `Circle3D`
236/// - `ψ > γ` (ellipse) → closed-form `Ellipse3D`
237/// - `ψ ≤ γ` (parabola/hyperbola) → bounded single-branch `Points` (one chain
238///   per branch — a hyperbola's two nappes never share a chain)
239fn exact_plane_cone(
240    cone: &ConicalSurface,
241    normal: Vec3,
242    d: f64,
243    reach: f64,
244) -> Result<Vec<ExactIntersectionCurve>, MathError> {
245    let axis = cone.axis();
246    let cos_theta = normal.dot(axis).abs();
247    let half_angle = cone.half_angle();
248
249    if cos_theta > 1.0 - 1e-10 {
250        // Plane perpendicular to axis → Circle
251        // Find where axis meets the plane
252        let n_dot_axis = normal.dot(axis);
253        let n_dot_apex = dot_np(normal, cone.apex());
254        let t = (d - n_dot_apex) / n_dot_axis;
255
256        // t is the signed distance from apex to plane along the axis.
257        // The real cone is a single nappe; the perpendicular-plane section is a
258        // circle whose radius follows from the axial offset |t|.
259        // |t| ≈ 0 means the plane passes through the apex → degenerate point.
260        if t.abs() < 1e-10 {
261            return Ok(vec![]);
262        }
263
264        let center = Point3::new(
265            cone.apex().x() + t * axis.x(),
266            cone.apex().y() + t * axis.y(),
267            cone.apex().z() + t * axis.z(),
268        );
269        // half_angle is the angle from the radial plane to the surface.
270        // Axial distance t = v * sin(half_angle), so v = t / sin(half_angle).
271        // Radius at v = v * cos(half_angle) = t * cos(half_angle) / sin(half_angle).
272        let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
273        if circle_r < 1e-15 {
274            return Ok(vec![]);
275        }
276
277        let circle = Circle3D::new(center, normal, circle_r)?;
278        return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
279    }
280
281    // Oblique plane. Classify the conic in the plane-aligned frame.
282    //
283    // Decompose the (unit) axis as a = c·n + p·e1, where c = n·a, e1 is the unit
284    // in-plane projection of the axis, and p = |projection| = sqrt(1−c²). Write a
285    // point Q on the plane as Q = apex + e·n + s·e1 + t·e2 (e = d − n·apex,
286    // e2 = n×e1). The cone equation (w·a)² = cos²γ·(w·w) with k = cos²γ =
287    // sin²(half_angle) reduces to (no s·t cross term, since e1/e2 align with the
288    // conic axes):
289    //     (p²−k)·s² + 2ecp·s + e²(c²−k) = k·t²
290    // The s² coefficient A = p²−k = sin²θ − sin²(half_angle) sets the type:
291    // A < 0 → ellipse, A = 0 → parabola, A > 0 → hyperbola.
292    let c = normal.dot(axis);
293    let p2 = (1.0 - c * c).max(0.0);
294    let p = p2.sqrt();
295    let k = half_angle.sin().powi(2);
296    let a_coeff = p2 - k;
297
298    // Build the plane-aligned frame e1 (in-plane axis projection), e2 = n×e1.
299    let m = Vec3::new(
300        axis.x() - c * normal.x(),
301        axis.y() - c * normal.y(),
302        axis.z() - c * normal.z(),
303    );
304    let m_len = m.length();
305    if m_len < 1e-12 {
306        // Axis parallel to normal — handled by the perpendicular branch above;
307        // fall back to sampling for safety.
308        let chains = sample_plane_cone(cone, normal, d, reach)?;
309        return Ok(chains
310            .into_iter()
311            .map(ExactIntersectionCurve::Points)
312            .collect());
313    }
314    let e1 = m * (1.0 / m_len);
315    let e2 = normal.cross(e1);
316    let apex = cone.apex();
317    let e = d - dot_np(normal, apex);
318
319    // Ellipse → closed form. A = p²−k < 0 with a margin to keep the
320    // near-parabolic regime on the robust sampled path.
321    if a_coeff < -1e-9 {
322        let abs_a = -a_coeff; // = k − p² > 0
323        // Real-nappe guard: in the ellipse regime n·g(u) keeps constant sign(c),
324        // so v = e/(n·g) ≥ 0 only when e and c share a sign. When e·c < 0 the
325        // plane is offset to the far side of the apex from the cone's opening —
326        // the section lies entirely on the phantom nappe, so there is no real
327        // curve (RHS below is positive regardless of sign, so it can't catch this).
328        if e * c < 0.0 {
329            return Ok(vec![]);
330        }
331        // |A|(s − s_c)² + k·t² = RHS, with s_c = ecp/|A| and
332        // RHS = e²·k·(1−k)/|A| (always > 0 for a real ellipse).
333        let s_c = e * c * p / abs_a;
334        let rhs = e * e * k * (1.0 - k) / abs_a;
335        if rhs <= 0.0 {
336            return Ok(vec![]);
337        }
338        let semi_s = (rhs / abs_a).sqrt(); // extent along e1
339        let semi_t = (rhs / k).sqrt(); // extent along e2
340        if semi_s < 1e-12 || semi_t < 1e-12 {
341            return Ok(vec![]);
342        }
343        let center = apex + normal * e + e1 * s_c;
344        let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
345            (semi_s, semi_t, e1, e2)
346        } else {
347            (semi_t, semi_s, e2, e1)
348        };
349        let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
350        return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
351    }
352
353    // Parabola / hyperbola (and the near-parabolic ellipse margin): the section
354    // is unbounded, so emit bounded, branch-separated sample chains.
355    let chains = sample_plane_cone(cone, normal, d, reach)?;
356    Ok(chains
357        .into_iter()
358        .map(ExactIntersectionCurve::Points)
359        .collect())
360}
361
362/// The exact arc from `from` to `to` of a plane's parabola or hyperbola
363/// section of a cone, both ends on one branch of it, as a rational quadratic
364/// NURBS.
365///
366/// A hyperbola `x = a cosh φ, y = b sinh φ` (in the plane frame of
367/// `exact_plane_cone`) is cut into pieces of at most one unit of `φ`, each
368/// a conic Bézier: its middle point is where the end tangents meet and its
369/// middle weight is the cosh of half the piece's span. A parabola is one
370/// polynomial quadratic. `None` for an elliptic or circular section, a plane
371/// through the apex, or ends off one branch of the section.
372///
373/// # Errors
374///
375/// Returns an error if the plane normal is zero or the curve cannot be built.
376#[allow(clippy::many_single_char_names)]
377pub fn plane_cone_conic_arc(
378    cone: &ConicalSurface,
379    normal: Vec3,
380    d: f64,
381    from: Point3,
382    to: Point3,
383) -> Result<Option<NurbsCurve>, MathError> {
384    let len = normal.length();
385    if len < 1e-15 {
386        return Err(MathError::ZeroVector);
387    }
388    let (normal, d) = (normal * (1.0 / len), d / len);
389    let axis = cone.axis();
390    let c = normal.dot(axis);
391    let p2 = (1.0 - c * c).max(0.0);
392    let p = p2.sqrt();
393    let k = cone.half_angle().sin().powi(2);
394    let a_coeff = p2 - k;
395    let m = Vec3::new(
396        axis.x() - c * normal.x(),
397        axis.y() - c * normal.y(),
398        axis.z() - c * normal.z(),
399    );
400    let m_len = m.length();
401    if m_len < 1e-12 || a_coeff < -1e-9 {
402        return Ok(None);
403    }
404    let e1 = m * (1.0 / m_len);
405    let e2 = normal.cross(e1);
406    let apex = cone.apex();
407    let e = d - dot_np(normal, apex);
408    let origin = apex + normal * e;
409    let plane_st = |q: Point3| {
410        let w = q - origin;
411        (w.dot(e1), w.dot(e2))
412    };
413    let ((s0, t0), (s1, t1)) = (plane_st(from), plane_st(to));
414    let scale = s0.abs().max(t0.abs()).max(s1.abs()).max(t1.abs()).max(1.0);
415    if e.abs() < 1e-9 * scale || (from - to).length() <= 1e-9 * scale {
416        return Ok(None);
417    }
418    let point = |s: f64, t: f64| origin + e1 * s + e2 * t;
419    let on_curve = |q: Point3, r: Point3| (q - r).length() <= 1e-6 * scale;
420    let (control, weights) = if a_coeff.abs() <= 1e-9 {
421        // (p² − k) s² vanishes: 2ecp·s + e²(c² − k) = k·t², s = α t² + β.
422        let lin = 2.0 * e * c * p;
423        if lin.abs() < 1e-12 * scale {
424            return Ok(None);
425        }
426        let (alpha, beta) = (k / lin, -e * e * (c * c - k) / lin);
427        if !on_curve(point(alpha * t0 * t0 + beta, t0), from)
428            || !on_curve(point(alpha * t1 * t1 + beta, t1), to)
429        {
430            return Ok(None);
431        }
432        let mid = point(alpha * t0 * t1 + beta, 0.5 * (t0 + t1));
433        (vec![from, mid, to], vec![1.0; 3])
434    } else {
435        // A (s − s_c)² − k t² = R with R = e² k (1 − k) / A.
436        let s_c = -e * c * p / a_coeff;
437        let r = e * e * k * (1.0 - k) / a_coeff;
438        if r <= 0.0 {
439            return Ok(None);
440        }
441        let (a, b) = ((r / a_coeff).sqrt(), (r / k).sqrt());
442        let (x0, x1) = (s0 - s_c, s1 - s_c);
443        if x0 * x1 <= 0.0 {
444            return Ok(None);
445        }
446        let side = x0.signum();
447        let hyperbola = |phi: f64| point(s_c + side * a * phi.cosh(), b * phi.sinh());
448        let (phi0, phi1) = ((t0 / b).asinh(), (t1 / b).asinh());
449        if !on_curve(hyperbola(phi0), from) || !on_curve(hyperbola(phi1), to) {
450            return Ok(None);
451        }
452        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
453        let pieces = ((phi1 - phi0).abs().ceil() as usize).max(1);
454        let mut control = vec![from];
455        let mut weights = vec![1.0];
456        for i in 0..pieces {
457            #[allow(clippy::cast_precision_loss)]
458            let (fa, fb) = (i as f64 / pieces as f64, (i + 1) as f64 / pieces as f64);
459            let (pa, pb) = (phi0 + (phi1 - phi0) * fa, phi0 + (phi1 - phi0) * fb);
460            let (mid, half) = (0.5 * (pa + pb), 0.5 * (pb - pa));
461            let w = half.cosh();
462            control.push(point(s_c + side * a * mid.cosh() / w, b * mid.sinh() / w));
463            weights.push(w);
464            control.push(if i + 1 == pieces { to } else { hyperbola(pb) });
465            weights.push(1.0);
466        }
467        (control, weights)
468    };
469    let pieces = (control.len() - 1) / 2;
470    let mut knots = vec![0.0; 3];
471    for i in 1..pieces {
472        #[allow(clippy::cast_precision_loss)]
473        knots.extend([i as f64; 2]);
474    }
475    #[allow(clippy::cast_precision_loss)]
476    knots.extend([pieces as f64; 3]);
477    let curve = NurbsCurve::new(2, knots, control, weights)?;
478    // The closed forms drop terms that vanish only on the exact conic (a
479    // barely elliptic section read as a parabola), so the arc must meet the
480    // cone between its ends too: a point at radius ρ and height h off the
481    // apex lies |ρ sin α − |h| cos α| from it.
482    let (sin_a, cos_a) = cone.half_angle().sin_cos();
483    let off_cone = |q: Point3| {
484        let w = q - apex;
485        let h = w.dot(axis);
486        (w - axis * h)
487            .length()
488            .mul_add(sin_a, -(h.abs() * cos_a))
489            .abs()
490    };
491    for i in 0..pieces {
492        for f in [0.25, 0.5, 0.75] {
493            #[allow(clippy::cast_precision_loss)]
494            if off_cone(curve.evaluate(i as f64 + f)) > 1e-9 * scale {
495                return Ok(None);
496            }
497        }
498    }
499    Ok(Some(curve))
500}
501
502/// Reference to an analytic surface for intersection dispatch.
503#[derive(Clone, Copy)]
504pub enum AnalyticSurface<'a> {
505    /// Cylindrical surface reference.
506    Cylinder(&'a CylindricalSurface),
507    /// Conical surface reference.
508    Cone(&'a ConicalSurface),
509    /// Spherical surface reference.
510    Sphere(&'a SphericalSurface),
511    /// Toroidal surface reference.
512    Torus(&'a ToroidalSurface),
513}
514
515/// Compute `n . p` treating a `Point3` as a position vector.
516fn dot_np(n: Vec3, p: Point3) -> f64 {
517    n.dot(Vec3::new(p.x(), p.y(), p.z()))
518}
519
520/// Intersect a plane with an analytic surface.
521///
522/// The plane is defined by `dot(normal, p) = d`.
523///
524/// # Errors
525///
526/// Returns an error if the intersection computation fails.
527pub fn intersect_plane_analytic(
528    surface: AnalyticSurface<'_>,
529    normal: Vec3,
530    d: f64,
531) -> Result<Vec<IntersectionCurve>, MathError> {
532    match surface {
533        AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
534        AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
535        AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
536        AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
537    }
538}
539
540/// Sample points on the plane-analytic intersection without NURBS curve fitting.
541///
542/// Returns chains of ordered 3D sample points. Each chain is one connected
543/// component of the intersection curve. This is much faster than
544/// `intersect_plane_analytic` when only sample points are needed (e.g. for
545/// boolean intersection segment generation).
546///
547/// # Errors
548///
549/// Returns an error if the intersection computation fails.
550pub fn sample_plane_analytic(
551    surface: AnalyticSurface<'_>,
552    normal: Vec3,
553    d: f64,
554) -> Result<Vec<Vec<Point3>>, MathError> {
555    match surface {
556        AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
557        AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d, 0.0),
558        AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
559        AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
560    }
561}
562
563/// Sample the plane-cylinder intersection as ordered 3D points.
564#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
565fn sample_plane_cylinder(
566    cyl: &CylindricalSurface,
567    normal: Vec3,
568    d: f64,
569) -> Result<Vec<Vec<Point3>>, MathError> {
570    let n_samples = 64_usize;
571    let mut points = Vec::with_capacity(n_samples + 1);
572
573    for i in 0..=n_samples {
574        let u = TAU * (i as f64) / (n_samples as f64);
575        let base = cyl.evaluate(u, 0.0);
576        let n_dot_axis = normal.dot(cyl.axis());
577        let n_dot_base = dot_np(normal, base);
578
579        if n_dot_axis.abs() < 1e-12 {
580            if (n_dot_base - d).abs() < 1e-6 {
581                points.push(base);
582            }
583        } else {
584            let v = (d - n_dot_base) / n_dot_axis;
585            if v.abs() <= 100.0 {
586                points.push(cyl.evaluate(u, v));
587            }
588        }
589    }
590
591    if points.len() < 2 {
592        Ok(vec![])
593    } else {
594        Ok(vec![points])
595    }
596}
597
598/// Sample the plane-sphere intersection as ordered 3D points.
599#[allow(clippy::cast_precision_loss)]
600fn sample_plane_sphere(
601    sphere: &SphericalSurface,
602    normal: Vec3,
603    d: f64,
604) -> Result<Vec<Vec<Point3>>, MathError> {
605    let h = dot_np(normal, sphere.center()) - d;
606    let r = sphere.radius();
607
608    if h.abs() > r - 1e-10 {
609        return Ok(vec![]);
610    }
611
612    let circle_r = (r.mul_add(r, -(h * h))).sqrt();
613    let circle_center = Point3::new(
614        h.mul_add(-normal.x(), sphere.center().x()),
615        h.mul_add(-normal.y(), sphere.center().y()),
616        h.mul_add(-normal.z(), sphere.center().z()),
617    );
618
619    let basis = Frame3::from_normal(circle_center, normal)?;
620    let u_dir = basis.x;
621    let v_dir = basis.y;
622
623    let n_samples = 64_usize;
624    let mut points = Vec::with_capacity(n_samples + 1);
625
626    for i in 0..=n_samples {
627        let theta = TAU * (i as f64) / (n_samples as f64);
628        let (sin_t, cos_t) = theta.sin_cos();
629        points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
630    }
631
632    Ok(vec![points])
633}
634
635/// Sample the plane-cone intersection as ordered 3D points.
636///
637/// The cone is the single real nappe `v >= 0` of `P(u,v) = apex + v·g(u)`.
638/// Along each generator `g(u)` the plane `n·P = d` is linear in `v`, so
639/// `v = (d − n·apex) / (n·g(u))`. We keep only `v >= 0` (the phantom `v < 0`
640/// nappe is geometrically absent) and `v` below a finite bound (near an
641/// asymptote `n·g(u) → 0` so `v → ∞` — those points run off the surface and
642/// must be excluded). The angular samples that survive form one contiguous arc
643/// (ellipse) or two (parabola/hyperbola, one per branch); each contiguous run
644/// is returned as a separate ordered chain so the consumer never stitches two
645/// disjoint branches into one curve.
646#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
647fn sample_plane_cone(
648    cone: &ConicalSurface,
649    normal: Vec3,
650    d: f64,
651    reach: f64,
652) -> Result<Vec<Vec<Point3>>, MathError> {
653    let apex = cone.apex();
654    let n_dot_apex = dot_np(normal, apex);
655    let e = d - n_dot_apex;
656
657    // Per-generator solve: along g(u) the plane is linear in v, v = e / (n·g(u)).
658    // Sample u densely; keep only the real nappe (v >= 0) and skip near-asymptote
659    // generators (n·g(u) ≈ 0 → v → ∞).
660    let n_samples = 512_usize;
661    let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
662    let mut v_min = f64::INFINITY;
663    for i in 0..n_samples {
664        let u = TAU * (i as f64) / (n_samples as f64);
665        let g = cone.evaluate(u, 1.0) - apex;
666        let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
667        if n_dot_g.abs() < 1e-12 {
668            vs.push(None);
669            continue;
670        }
671        let v = e / n_dot_g;
672        if v >= -1e-12 {
673            let v = v.max(0.0);
674            v_min = v_min.min(v);
675            vs.push(Some(v));
676        } else {
677            vs.push(None);
678        }
679    }
680
681    if !v_min.is_finite() {
682        return Ok(Vec::new());
683    }
684
685    // Bound the arc around the conic vertex (closest approach to the apex, at
686    // v_min). An ellipse is naturally bounded; a parabola/hyperbola is not, so
687    // cap the cone radius at a generous multiple of the vertex radius. This is
688    // scale-invariant and centred on where any finite cone face's overlap lies;
689    // the downstream consumer trims the fitted curve to the actual face AABB, so
690    // over-coverage is harmless. The floor handles a vertex at the apex (v_min≈0).
691    // A caller that knows its faces asks for their reach: an open hyperbola
692    // (a vertex close to the axis) crosses a rim far past eight vertex radii.
693    let v_max = (8.0 * v_min).max(v_min + 4.0).max(reach);
694
695    // Per-sample v within the cap; the raw values stay in `vs` for the
696    // boundary solve below.
697    let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
698
699    let point_at = |u: f64, v: f64| -> Point3 {
700        let g = cone.evaluate(u, 1.0) - apex;
701        apex + g * v
702    };
703    #[allow(clippy::cast_precision_loss)]
704    let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
705    let n_dot_g_at = |u: f64| -> f64 {
706        let g = cone.evaluate(u, 1.0) - apex;
707        normal.dot(Vec3::new(g.x(), g.y(), g.z()))
708    };
709
710    if kept.iter().all(Option::is_some) {
711        // Closed loop (ellipse regime): emit all points and repeat the first.
712        let mut pts: Vec<Point3> = kept
713            .iter()
714            .enumerate()
715            .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
716            .collect();
717        if let Some(&first) = pts.first() {
718            pts.push(first);
719        }
720        return Ok(vec![pts]);
721    }
722
723    // A hyperbola/parabola tail diverges as 1/(n·g), so between the last kept
724    // sample and its dropped neighbour v can leap far past `v_max` in one
725    // uniform-u pitch — and any finite face window inside that leap is lost
726    // (a taper cone grazed 0.05 by a prism plane lost its entire 0.5-tall
727    // section to exactly this aliasing). Extend each run end to the exact
728    // `v_max` boundary: bisect u for `n·g(u) = e/v_max` inside the dropped
729    // pitch (n·g is monotone there — its extrema sit at the conic vertex,
730    // far from any asymptote), then fill the tail with uniform-u samples.
731    let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
732        let Some(v_end) = kept[i_end] else {
733            return Vec::new();
734        };
735        let u_end = u_of(i_end);
736        #[allow(clippy::cast_precision_loss)]
737        let pitch = TAU / (n_samples as f64);
738        let u_next = if forward {
739            u_end + pitch
740        } else {
741            u_end - pitch
742        };
743        let target = e / v_max;
744        let h_end = n_dot_g_at(u_end) - target;
745        let h_next = n_dot_g_at(u_next) - target;
746        if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
747            return Vec::new();
748        }
749        let (mut lo, mut hi) = (u_end, u_next);
750        for _ in 0..60 {
751            let mid = f64::midpoint(lo, hi);
752            if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
753                lo = mid;
754            } else {
755                hi = mid;
756            }
757        }
758        let u_star = f64::midpoint(lo, hi);
759        let tail_n = 8_usize;
760        (1..=tail_n)
761            .filter_map(|k| {
762                #[allow(clippy::cast_precision_loss)]
763                let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
764                let ng = n_dot_g_at(u);
765                if ng.abs() < 1e-12 {
766                    return None;
767                }
768                let v = e / ng;
769                (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
770            })
771            .collect()
772    };
773
774    // Split into contiguous runs of kept samples, treating the array as
775    // circular (rotate past a gap) so a branch straddling u=0 stays whole.
776    let gap = kept.iter().position(Option::is_none).unwrap_or(0);
777    let mut chains: Vec<Vec<Point3>> = Vec::new();
778    let mut run: Vec<usize> = Vec::new();
779    let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
780        if run.len() >= 2 {
781            let first = run[0];
782            let last = run[run.len() - 1];
783            let mut pts: Vec<Point3> = tail(first, false, &kept);
784            pts.reverse();
785            pts.extend(
786                run.iter()
787                    .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
788            );
789            pts.extend(tail(last, true, &kept));
790            chains.push(pts);
791        }
792        run.clear();
793    };
794    for k in 0..n_samples {
795        let idx = (gap + k) % n_samples;
796        if kept[idx].is_some() {
797            run.push(idx);
798        } else {
799            flush(&mut run, &mut chains);
800        }
801    }
802    flush(&mut run, &mut chains);
803    Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
804}
805
806/// Sample the plane-torus intersection as ordered 3D points.
807///
808/// Uses the same closed-form crossings and chaining as `intersect_plane_torus`
809/// but skips NURBS curve fitting (the callers here only need the points).
810#[allow(clippy::unnecessary_wraps)] // sibling match-arms and `?` callers need `Result`
811fn sample_plane_torus(
812    torus: &ToroidalSurface,
813    normal: Vec3,
814    d: f64,
815) -> Result<Vec<Vec<Point3>>, MathError> {
816    let crossing_pts = plane_torus_crossings(torus, normal, d, 128);
817    Ok(chain_torus_crossings(&crossing_pts)
818        .into_iter()
819        .map(|run| run.into_iter().map(|p| p.point).collect())
820        .collect())
821}
822
823/// Intersect a plane with a cylindrical surface.
824///
825/// For each `u` in `[0, 2pi)`, the cylinder point is linear in `v`,
826/// so the plane equation `dot(normal, P(u,v)) = d` is linear in `v`
827/// and can be solved directly.
828///
829/// # Errors
830///
831/// Returns an error if curve fitting fails.
832#[allow(clippy::cast_precision_loss)]
833pub fn intersect_plane_cylinder(
834    cyl: &CylindricalSurface,
835    normal: Vec3,
836    d: f64,
837) -> Result<Vec<IntersectionCurve>, MathError> {
838    let n_samples = 64_usize;
839    let mut points_3d = Vec::new();
840    let mut ipoints = Vec::new();
841
842    for i in 0..=n_samples {
843        let u = TAU * (i as f64) / (n_samples as f64);
844        // P(u, v) = origin + r*(cos(u)*x + sin(u)*y) + v*axis
845        // dot(normal, P) = d  =>  dot(normal, base(u)) + v * dot(normal, axis) = d
846        let base = cyl.evaluate(u, 0.0);
847        let n_dot_axis = normal.dot(cyl.axis());
848        let n_dot_base = dot_np(normal, base);
849
850        if n_dot_axis.abs() < 1e-12 {
851            // Plane parallel to axis -- check if base is on plane.
852            if (n_dot_base - d).abs() < 1e-6 {
853                let pt = base;
854                points_3d.push(pt);
855                ipoints.push(IntersectionPoint {
856                    point: pt,
857                    param1: (u, 0.0),
858                    param2: (0.0, 0.0),
859                });
860            }
861        } else {
862            let v = (d - n_dot_base) / n_dot_axis;
863            // Only keep points within a reasonable v range.
864            if v.abs() <= 100.0 {
865                let pt = cyl.evaluate(u, v);
866                points_3d.push(pt);
867                ipoints.push(IntersectionPoint {
868                    point: pt,
869                    param1: (u, v),
870                    param2: (0.0, 0.0),
871                });
872            }
873        }
874    }
875
876    build_curves_from_points(&points_3d, ipoints)
877}
878
879/// Intersect a plane with a spherical surface.
880///
881/// The intersection of a plane with a sphere is a circle (or empty/point).
882/// Computes the circle center, radius, and samples points on it.
883///
884/// # Errors
885///
886/// Returns an error if curve fitting fails.
887#[allow(clippy::cast_precision_loss)]
888pub fn intersect_plane_sphere(
889    sphere: &SphericalSurface,
890    normal: Vec3,
891    d: f64,
892) -> Result<Vec<IntersectionCurve>, MathError> {
893    let h = dot_np(normal, sphere.center()) - d;
894    let r = sphere.radius();
895
896    // No intersection if plane is too far from center.
897    if h.abs() > r - 1e-10 {
898        return Ok(vec![]);
899    }
900
901    let circle_r = (r.mul_add(r, -(h * h))).sqrt();
902    let circle_center = Point3::new(
903        h.mul_add(-normal.x(), sphere.center().x()),
904        h.mul_add(-normal.y(), sphere.center().y()),
905        h.mul_add(-normal.z(), sphere.center().z()),
906    );
907
908    // Build a local frame on the plane.
909    let basis = Frame3::from_normal(circle_center, normal)?;
910    let u_dir = basis.x;
911    let v_dir = basis.y;
912
913    let n_samples = 64_usize;
914    let mut points_3d = Vec::new();
915    let mut ipoints = Vec::new();
916
917    for i in 0..=n_samples {
918        let theta = TAU * (i as f64) / (n_samples as f64);
919        let (sin_t, cos_t) = theta.sin_cos();
920        let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
921        points_3d.push(pt);
922        ipoints.push(IntersectionPoint {
923            point: pt,
924            param1: (theta, 0.0),
925            param2: (0.0, 0.0),
926        });
927    }
928
929    build_curves_from_points(&points_3d, ipoints)
930}
931
932/// Intersect a plane with a conical surface.
933///
934/// Like a cylinder, the cone is linear along each generatrix, so the plane
935/// equation is linear in `v` for each fixed `u`.
936///
937/// # Errors
938///
939/// Returns an error if curve fitting fails.
940#[allow(clippy::cast_precision_loss)]
941pub fn intersect_plane_cone(
942    cone: &ConicalSurface,
943    normal: Vec3,
944    d: f64,
945) -> Result<Vec<IntersectionCurve>, MathError> {
946    let n_samples = 64_usize;
947    let mut points_3d = Vec::new();
948    let mut ipoints = Vec::new();
949
950    for i in 0..n_samples {
951        let u = TAU * (i as f64) / (n_samples as f64);
952        // P(u, v) = apex + v * dir(u)
953        // dot(normal, apex) + v * dot(normal, dir(u)) = d
954        let apex = cone.apex();
955        let n_dot_apex = dot_np(normal, apex);
956        // dir(u) = P(u,1) - apex
957        let p1 = cone.evaluate(u, 1.0);
958        let dir = p1 - apex;
959        let n_dot_dir = normal.dot(dir);
960
961        if n_dot_dir.abs() < 1e-12 {
962            continue;
963        }
964
965        let v = (d - n_dot_apex) / n_dot_dir;
966        // Allow negative v — the cone surface extends in both directions from the apex.
967        if v.abs() > 1e-10 && v.abs() < 100.0 {
968            let pt = cone.evaluate(u, v);
969            points_3d.push(pt);
970            ipoints.push(IntersectionPoint {
971                point: pt,
972                param1: (u, v),
973                param2: (0.0, 0.0),
974            });
975        }
976    }
977
978    build_curves_from_points(&points_3d, ipoints)
979}
980
981/// Intersect a plane with a toroidal surface.
982///
983/// The section is a degree-4 curve, but for each `v` the `u` values solve in
984/// closed form (see `plane_torus_crossings`), so it is sampled by a v-scan
985/// and each connected loop is fitted to a NURBS curve.
986///
987/// # Errors
988///
989/// Never returns an error today (curve-fit failures drop the affected loop);
990/// the `Result` is kept for signature parity with the other plane-analytic
991/// intersectors.
992#[allow(clippy::unnecessary_wraps)]
993pub fn intersect_plane_torus(
994    torus: &ToroidalSurface,
995    normal: Vec3,
996    d: f64,
997) -> Result<Vec<IntersectionCurve>, MathError> {
998    // The section satisfies a per-v closed form (see `plane_torus_crossings`),
999    // so scan v and solve u directly instead of a 2D sign-change grid with
1000    // Newton refinement: O(n) rather than O(n²), and every point is exact.
1001    let crossing_pts = plane_torus_crossings(torus, normal, d, 128);
1002
1003    let mut curves = Vec::new();
1004    for ipts in chain_torus_crossings(&crossing_pts) {
1005        let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
1006        if let Ok(curve) = interpolate(&pts, 3.min(pts.len() - 1)) {
1007            curves.push(IntersectionCurve {
1008                curve,
1009                points: ipts,
1010            });
1011        }
1012    }
1013
1014    Ok(curves)
1015}
1016
1017/// Greedy nearest-neighbour chaining of torus-plane crossing points into
1018/// closed section loops. Runs shorter than four points are dropped.
1019///
1020/// Plane × full torus is always a set of CLOSED loops, but the greedy walk
1021/// stops one step short of closing (the first point is already `used`, so it
1022/// is never re-added and the last point sits ~one step from the start).
1023/// A loop whose end-to-start gap is within ~2 point-spacings is closed by
1024/// repeating its first point, so a fitted NURBS closes exactly and downstream
1025/// consumers see a closed curve. A fragmented chain (greedy walk broke a loop
1026/// at a near-tangency) ends far from its start and is left open — it must not
1027/// be force-closed into a wrong loop.
1028fn chain_torus_crossings(crossing_pts: &[(f64, f64, Point3)]) -> Vec<Vec<IntersectionPoint>> {
1029    let mut used = vec![false; crossing_pts.len()];
1030    let mut runs = Vec::new();
1031
1032    for start in 0..crossing_pts.len() {
1033        if used[start] {
1034            continue;
1035        }
1036        used[start] = true;
1037        let mut chain = vec![start];
1038
1039        loop {
1040            let last = chain[chain.len() - 1];
1041            let last_pt = crossing_pts[last].2;
1042            let mut best_idx = None;
1043            let mut best_dist = 1.0_f64;
1044
1045            for (j, &is_used) in used.iter().enumerate() {
1046                if is_used {
1047                    continue;
1048                }
1049                let dist = (crossing_pts[j].2 - last_pt).length();
1050                if dist < best_dist {
1051                    best_dist = dist;
1052                    best_idx = Some(j);
1053                }
1054            }
1055
1056            if let Some(j) = best_idx {
1057                used[j] = true;
1058                chain.push(j);
1059            } else {
1060                break;
1061            }
1062        }
1063
1064        if chain.len() < 4 {
1065            continue;
1066        }
1067        let mut ipts: Vec<IntersectionPoint> = chain
1068            .iter()
1069            .map(|&i| IntersectionPoint {
1070                point: crossing_pts[i].2,
1071                param1: (crossing_pts[i].0, crossing_pts[i].1),
1072                param2: (0.0, 0.0),
1073            })
1074            .collect();
1075
1076        let closing_gap = (ipts[ipts.len() - 1].point - ipts[0].point).length();
1077        let median_spacing = {
1078            let mut spac: Vec<f64> = ipts
1079                .windows(2)
1080                .map(|w| (w[1].point - w[0].point).length())
1081                .collect();
1082            spac.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1083            spac.get(spac.len() / 2).copied().unwrap_or(0.0)
1084        };
1085        // Wrap when the closing gap is within ~2 point-spacings (measured
1086        // ratio ≈ 1.0 for the census ovals) and not already coincident — but
1087        // only for a SIMPLE loop. A self-touching section (the inner/outer
1088        // tangent figure-eight) is traced as one chain that folds back through
1089        // its node and also ends near its start; sealing it would misrepresent
1090        // a non-manifold singularity as a closed loop, so leave it open.
1091        if closing_gap > 1e-9
1092            && median_spacing > 1e-12
1093            && closing_gap <= 2.0 * median_spacing
1094            && !chain_self_touches(&ipts, median_spacing)
1095        {
1096            ipts.push(ipts[0]);
1097        }
1098        runs.push(ipts);
1099    }
1100
1101    runs
1102}
1103
1104/// Whether a chain folds back on itself in its interior — the signature of a
1105/// self-touching section (a tangent figure-eight), as opposed to a simple
1106/// loop whose only near-return is the intended closure at its two ends.
1107///
1108/// Checks whether two chain points far apart in index (and both away from the
1109/// endpoints, so the closure region is excluded) come within ~1.5 spacings of
1110/// each other. A convex/simple oval never does; a figure-eight does, at its
1111/// node. Only called when a chain already looks closeable, so the O(m²) scan
1112/// is rare.
1113fn chain_self_touches(ipts: &[IntersectionPoint], median_spacing: f64) -> bool {
1114    let m = ipts.len();
1115    let k = (m / 4).clamp(1, 6);
1116    if m < 3 * k || median_spacing <= 0.0 {
1117        return false;
1118    }
1119    let thresh = median_spacing * 1.5;
1120    for i in k..(m - k) {
1121        for j in (i + k)..(m - k) {
1122            if (ipts[i].point - ipts[j].point).length() < thresh {
1123                return true;
1124            }
1125        }
1126    }
1127    false
1128}
1129
1130/// Closed-form `(u, v, point)` crossings of a plane with a torus.
1131///
1132/// In the torus's own frame let `a = n·X`, `b = n·Y`, `c = n·Z`,
1133/// `s = hypot(a, b)`, `phi = atan2(b, a)`. Substituting the torus
1134/// parameterization into `n·P = d` gives
1135///   `(R + r·cos v)·s·cos(u − phi) + r·c·sin v = d − n·center`,
1136/// so for each `v` the two `u` branches solve directly as
1137/// `u = phi ± acos((d − n·center − r·c·sin v) / (s·(R + r·cos v)))`.
1138/// Scanning `v` at `n_v` samples replaces a 2D sign-change grid plus Newton
1139/// refinement: each point is `torus.evaluate(u, v)` (on the torus by
1140/// construction) with `u` solved so it lies on the plane to floating-point
1141/// precision, so no iterative refinement is needed.
1142///
1143/// When `s ≈ 0` the plane is perpendicular to the axis and the section is up
1144/// to two full circles at the `v` values solving `r·c·sin v = d − n·center`;
1145/// those are sampled by scanning `u`.
1146#[allow(clippy::cast_precision_loss)]
1147fn plane_torus_crossings(
1148    torus: &ToroidalSurface,
1149    normal: Vec3,
1150    d: f64,
1151    n_v: usize,
1152) -> Vec<(f64, f64, Point3)> {
1153    let big_r = torus.major_radius();
1154    let small_r = torus.minor_radius();
1155    let a = normal.dot(torus.x_axis());
1156    let b = normal.dot(torus.y_axis());
1157    let c = normal.dot(torus.z_axis());
1158    let s = a.hypot(b);
1159    let phi = b.atan2(a);
1160    let d_local = d - dot_np(normal, torus.center());
1161
1162    let mut pts: Vec<(f64, f64, Point3)> = Vec::new();
1163
1164    // Plane perpendicular to the axis: the section is up to two full circles.
1165    if s < 1e-12 {
1166        if c.abs() < 1e-12 {
1167            return pts;
1168        }
1169        let sin_v = d_local / (small_r * c);
1170        if sin_v.abs() > 1.0 + 1e-9 {
1171            return pts;
1172        }
1173        let v0 = sin_v.clamp(-1.0, 1.0).asin();
1174        let v1 = std::f64::consts::PI - v0;
1175        let mut vs = vec![v0];
1176        // Skip the mirror circle when the plane is tangent (v0 == v1).
1177        if (v1 - v0).abs() > 1e-9 {
1178            vs.push(v1);
1179        }
1180        for v in vs {
1181            for i in 0..n_v {
1182                let u = TAU * (i as f64) / (n_v as f64);
1183                pts.push((u, v, torus.evaluate(u, v)));
1184            }
1185        }
1186        return pts;
1187    }
1188
1189    // General plane: scan v, solve the two u branches per v. Offset the scan
1190    // by half a step so it never lands exactly on a tangency node (e.g. the
1191    // inner-tangent figure-eight at v = π, where the two u branches collapse
1192    // to one point) — a coincident node lets greedy chaining thread through
1193    // and wrongly seal a self-touching section into a closed loop.
1194    let v_off = TAU / (n_v as f64) * 0.5;
1195    for i in 0..n_v {
1196        let v = (i as f64).mul_add(TAU / (n_v as f64), v_off);
1197        let tube_r = small_r.mul_add(v.cos(), big_r); // R + r·cos v > 0
1198        let rhs = (d_local - small_r * c * v.sin()) / (s * tube_r);
1199        if rhs.abs() > 1.0 {
1200            continue;
1201        }
1202        let delta = rhs.clamp(-1.0, 1.0).acos();
1203        for u in [phi + delta, phi - delta] {
1204            pts.push((u, v, torus.evaluate(u, v)));
1205        }
1206    }
1207    pts
1208}
1209
1210/// The two sections of a plane that crosses every tube cross-section of a
1211/// torus twice (one parallel to the axis within `R − r` of it, or tilted a
1212/// little from that): both branches `u = phi ± acos(rhs(v))` of
1213/// [`plane_torus_crossings`] are then defined for every `v`, so each closes
1214/// into a loop that winds once around the tube. Sampled at `n_v` steps from
1215/// `v = 0`, the outer equator, so every such loop on a torus starts on one
1216/// latitude, as the tube cross-sections of a plane through the axis do.
1217/// `None` when a branch lapses somewhere or the two come close to meeting.
1218#[allow(clippy::cast_precision_loss)]
1219fn plane_torus_winding_loops(
1220    torus: &ToroidalSurface,
1221    normal: Vec3,
1222    d: f64,
1223    n_v: usize,
1224) -> Option<Vec<Vec<Point3>>> {
1225    let big_r = torus.major_radius();
1226    let small_r = torus.minor_radius();
1227    let a = normal.dot(torus.x_axis());
1228    let b = normal.dot(torus.y_axis());
1229    let c = normal.dot(torus.z_axis());
1230    let s = a.hypot(b);
1231    if s < 1e-12 * normal.length() || small_r >= big_r {
1232        return None;
1233    }
1234    let phi = b.atan2(a);
1235    let d_local = d - dot_np(normal, torus.center());
1236    let rhs = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.mul_add(v.cos(), big_r));
1237    let dense = 8 * n_v;
1238    if (0..dense).any(|i| rhs(TAU * i as f64 / dense as f64).abs() > 1.0 - 1e-3) {
1239        return None;
1240    }
1241    let mut loops = [Vec::with_capacity(n_v + 1), Vec::with_capacity(n_v + 1)];
1242    for i in 0..n_v {
1243        let v = TAU * i as f64 / n_v as f64;
1244        let delta = rhs(v).acos();
1245        loops[0].push(torus.evaluate(phi + delta, v));
1246        loops[1].push(torus.evaluate(phi - delta, v));
1247    }
1248    Some(
1249        loops
1250            .into_iter()
1251            .map(|mut run| {
1252                run.push(run[0]);
1253                run
1254            })
1255            .collect(),
1256    )
1257}
1258
1259/// Real intersection parameters `t` of the line `origin + t·dir` with a torus.
1260///
1261/// A line meets a torus in up to four points (degree-4). Substituting the line
1262/// into the torus implicit `(a² + b² + c² + R² − r²)² = 4R²(a² + b²)` — where
1263/// `(a, b, c)` are the line point's coordinates in the torus frame — gives a
1264/// quartic in `t`, solved here for its real roots (each refined by one Newton
1265/// step against the implicit). `dir` need not be unit length; `t` is in units of
1266/// `dir`. Returns the roots sorted ascending (0–4 of them).
1267///
1268/// Used by the boolean section trimmer to find where a plane×torus oval exits a
1269/// box face's straight boundary edge — the exact crossing shared by the two
1270/// adjacent faces, which is what makes the notch watertight.
1271#[must_use]
1272pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1273    let c = torus.center();
1274    let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1275    let big_r = torus.major_radius();
1276    let small_r = torus.minor_radius();
1277
1278    // Line point in torus frame: a(t)=a0+a1 t, b(t)=b0+b1 t, c(t)=c0+c1 t.
1279    let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1280    let (a0, a1) = (xa.dot(o), xa.dot(dir));
1281    let (b0, b1) = (ya.dot(o), ya.dot(dir));
1282    let (c0, c1) = (za.dot(o), za.dot(dir));
1283
1284    // G(t) = a² + b² + c² + R² − r²  (quadratic: g2 t² + g1 t + g0)
1285    let g2 = a1.mul_add(a1, b1.mul_add(b1, c1 * c1));
1286    let g1 = 2.0 * a1.mul_add(a0, b1.mul_add(b0, c1 * c0));
1287    let g0 = a0.mul_add(
1288        a0,
1289        b0.mul_add(b0, c0.mul_add(c0, big_r.mul_add(big_r, -small_r * small_r))),
1290    );
1291
1292    // H(t) = 4R² (a² + b²)  (quadratic: h2 t² + h1 t + h0)
1293    let four_rr = 4.0 * big_r * big_r;
1294    let h2 = four_rr * a1.mul_add(a1, b1 * b1);
1295    let h1 = four_rr * (2.0 * a1.mul_add(a0, b1 * b0));
1296    let h0 = four_rr * a0.mul_add(a0, b0 * b0);
1297
1298    // Quartic G² − H = 0:  e4 t⁴ + e3 t³ + e2 t² + e1 t + e0.
1299    let e4 = g2 * g2;
1300    let e3 = 2.0 * g2 * g1;
1301    let e2 = g1.mul_add(g1, 2.0 * g2 * g0) - h2;
1302    let e1 = 2.0f64.mul_add(g1 * g0, -h1);
1303    let e0 = g0.mul_add(g0, -h0);
1304
1305    let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1306    // One Newton polish against the torus implicit for full precision.
1307    let impl_f = |t: f64| -> f64 {
1308        let p = origin + dir * t;
1309        let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1310        let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1311        (a.hypot(b) - big_r).hypot(cc) - small_r
1312    };
1313    for t in &mut roots {
1314        let eps = 1e-7;
1315        let f = impl_f(*t);
1316        let df = (impl_f(*t + eps) - impl_f(*t - eps)) / (2.0 * eps);
1317        if df.abs() > 1e-12 {
1318            *t -= f / df;
1319        }
1320    }
1321    roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1322    roots
1323}
1324
1325/// Real roots of `c4 x⁴ + c3 x³ + c2 x² + c1 x + c0` via Durand–Kerner, falling
1326/// back to the lower-degree solvers when the leading coefficients vanish.
1327fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
1328    // Degenerate leading coefficient → lower degree.
1329    if c4.abs() < 1e-14 {
1330        return real_roots_cubic(c3, c2, c1, c0);
1331    }
1332    // Monic: x⁴ + a x³ + b x² + c x + d.
1333    let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
1334    let eval = |z: Complex| -> Complex {
1335        // Horner.
1336        let mut acc = Complex::new(1.0, 0.0);
1337        acc = acc * z + Complex::new(a, 0.0);
1338        acc = acc * z + Complex::new(b, 0.0);
1339        acc = acc * z + Complex::new(c, 0.0);
1340        acc * z + Complex::new(d, 0.0)
1341    };
1342    // Durand–Kerner: four roots seeded on a circle, iterated to convergence.
1343    let seed = Complex::new(0.4, 0.9);
1344    let mut r = [
1345        Complex::new(1.0, 0.0),
1346        seed,
1347        seed * seed,
1348        seed * seed * seed,
1349    ];
1350    for _ in 0..100 {
1351        let mut max_step = 0.0_f64;
1352        for i in 0..4 {
1353            let mut denom = Complex::new(1.0, 0.0);
1354            for j in 0..4 {
1355                if i != j {
1356                    denom = denom * (r[i] - r[j]);
1357                }
1358            }
1359            if denom.norm() < 1e-300 {
1360                continue;
1361            }
1362            let step = eval(r[i]) / denom;
1363            r[i] = r[i] - step;
1364            max_step = max_step.max(step.norm());
1365        }
1366        if max_step < 1e-14 {
1367            break;
1368        }
1369    }
1370    // Keep roots with negligible imaginary part AND a small REAL-polynomial
1371    // residual — Durand–Kerner stops after a fixed iteration cap whether or not
1372    // it converged, so a non-converged iterate could otherwise be returned as a
1373    // spurious root. Evaluate the monic quartic at each candidate (real part) and
1374    // keep only |p(x)| below a magnitude-scaled tolerance; de-dup near-equal
1375    // roots (a double root converges to two near-identical iterates).
1376    let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
1377    let mut out: Vec<f64> = Vec::new();
1378    for z in r {
1379        if z.im.abs() >= 1e-7 {
1380            continue;
1381        }
1382        let x = z.re;
1383        // Residual tolerance scales with the polynomial's coefficient magnitude
1384        // and |x|^4 so large-coefficient quartics are not over-rejected.
1385        let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
1386        if p_real(x).abs() > 1e-6 * scale {
1387            continue;
1388        }
1389        if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
1390            continue;
1391        }
1392        out.push(x);
1393    }
1394    out
1395}
1396
1397/// Real roots of `a x³ + b x² + c x + d` (Cardano), with quadratic fallback.
1398fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
1399    if a.abs() < 1e-14 {
1400        return real_roots_quadratic(b, c, d);
1401    }
1402    // Depressed cubic t³ + p t + q via x = t − b/(3a).
1403    let (b, c, d) = (b / a, c / a, d / a);
1404    let p = c - b * b / 3.0;
1405    let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
1406    let shift = -b / 3.0;
1407    let disc = q * q / 4.0 + p * p * p / 27.0;
1408    if disc > 1e-14 {
1409        let sq = disc.sqrt();
1410        let u = (-q / 2.0 + sq).cbrt();
1411        let v = (-q / 2.0 - sq).cbrt();
1412        vec![u + v + shift]
1413    } else if disc < -1e-14 {
1414        // Three real roots (trigonometric).
1415        let m = 2.0 * (-p / 3.0).sqrt();
1416        let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
1417        (0..3)
1418            .map(|k| {
1419                m.mul_add(
1420                    (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
1421                    shift,
1422                )
1423            })
1424            .collect()
1425    } else {
1426        // Repeated roots.
1427        let u = (-q / 2.0).cbrt();
1428        vec![2.0 * u + shift, -u + shift]
1429    }
1430}
1431
1432/// Real roots of `a x² + b x + c`, with linear fallback.
1433fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
1434    if a.abs() < 1e-14 {
1435        if b.abs() < 1e-14 {
1436            return Vec::new();
1437        }
1438        return vec![-c / b];
1439    }
1440    let disc = b * b - 4.0 * a * c;
1441    if disc < 0.0 {
1442        Vec::new()
1443    } else {
1444        let sq = disc.sqrt();
1445        vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
1446    }
1447}
1448
1449/// Minimal complex number for the quartic root finder.
1450#[derive(Clone, Copy)]
1451struct Complex {
1452    re: f64,
1453    im: f64,
1454}
1455
1456impl Complex {
1457    const fn new(re: f64, im: f64) -> Self {
1458        Self { re, im }
1459    }
1460    fn norm(self) -> f64 {
1461        self.re.hypot(self.im)
1462    }
1463}
1464
1465impl std::ops::Add for Complex {
1466    type Output = Self;
1467    fn add(self, o: Self) -> Self {
1468        Self::new(self.re + o.re, self.im + o.im)
1469    }
1470}
1471
1472impl std::ops::Sub for Complex {
1473    type Output = Self;
1474    fn sub(self, o: Self) -> Self {
1475        Self::new(self.re - o.re, self.im - o.im)
1476    }
1477}
1478
1479impl std::ops::Mul for Complex {
1480    type Output = Self;
1481    fn mul(self, o: Self) -> Self {
1482        Self::new(
1483            self.re.mul_add(o.re, -(self.im * o.im)),
1484            self.re.mul_add(o.im, self.im * o.re),
1485        )
1486    }
1487}
1488
1489impl std::ops::Div for Complex {
1490    type Output = Self;
1491    fn div(self, o: Self) -> Self {
1492        let den = o.re.mul_add(o.re, o.im * o.im);
1493        Self::new(
1494            self.re.mul_add(o.re, self.im * o.im) / den,
1495            self.im.mul_add(o.re, -(self.re * o.im)) / den,
1496        )
1497    }
1498}
1499
1500/// Build intersection curves from a collection of ordered 3D points.
1501///
1502/// If there are enough points, fits a NURBS curve through them.
1503fn build_curves_from_points(
1504    points_3d: &[Point3],
1505    ipoints: Vec<IntersectionPoint>,
1506) -> Result<Vec<IntersectionCurve>, MathError> {
1507    if points_3d.len() < 2 {
1508        return Ok(vec![]);
1509    }
1510
1511    let degree = 3.min(points_3d.len() - 1);
1512    let curve = interpolate(points_3d, degree)?;
1513    Ok(vec![IntersectionCurve {
1514        curve,
1515        points: ipoints,
1516    }])
1517}
1518
1519// -- Analytic-Analytic Intersection -------------------------------------------
1520
1521/// Intersect two analytic surfaces using a general marching approach.
1522///
1523/// Seeds intersection points by sampling both parameter spaces on a grid,
1524/// then marches along the intersection curve using the cross product of
1525/// the two surface normals as the tangent direction.
1526///
1527/// # Errors
1528///
1529/// Returns an error if curve fitting fails.
1530#[allow(
1531    clippy::cast_precision_loss,
1532    clippy::too_many_lines,
1533    clippy::similar_names,
1534    clippy::unnecessary_wraps,
1535    clippy::type_complexity
1536)]
1537pub fn intersect_analytic_analytic(
1538    a: AnalyticSurface<'_>,
1539    b: AnalyticSurface<'_>,
1540    grid_res: usize,
1541) -> Result<Vec<IntersectionCurve>, MathError> {
1542    intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
1543}
1544
1545/// Intersect two analytic surfaces with optional v-range overrides.
1546///
1547/// When `v_range_hint_a` or `v_range_hint_b` is `Some((min, max))`, the
1548/// marching algorithm searches that v-range instead of the hardcoded default.
1549/// This is essential for cylinders and cones whose default v-range is small
1550/// (-1..1 or 0.01..2) but whose actual face may extend much further.
1551///
1552/// # Errors
1553///
1554/// Returns `MathError` if algebraic intersection fails or marching diverges.
1555pub fn intersect_analytic_analytic_bounded(
1556    a: AnalyticSurface<'_>,
1557    b: AnalyticSurface<'_>,
1558    grid_res: usize,
1559    v_range_hint_a: Option<(f64, f64)>,
1560    v_range_hint_b: Option<(f64, f64)>,
1561) -> Result<Vec<IntersectionCurve>, MathError> {
1562    // Try algebraic specialization for known surface pairs before falling
1563    // back to the general marching approach.
1564    if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
1565        return Ok(result);
1566    }
1567
1568    let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
1569    let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
1570    let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
1571    let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
1572
1573    // Compute characteristic surface dimensions for adaptive parameters.
1574    let diag_a = {
1575        let p00 = surf_a(u_range_a.0, v_range_a.0);
1576        let p11 = surf_a(u_range_a.1, v_range_a.1);
1577        (p00 - p11).length()
1578    };
1579    let diag_b = {
1580        let p00 = surf_b(u_range_b.0, v_range_b.0);
1581        let p11 = surf_b(u_range_b.1, v_range_b.1);
1582        (p00 - p11).length()
1583    };
1584    let char_size = diag_a.min(diag_b).max(0.1);
1585
1586    // Sample surface A on a grid. For each grid point, project it
1587    // analytically onto surface B to find the closest point, then check
1588    // if the distance is below threshold (indicating near-intersection).
1589    #[allow(clippy::type_complexity)]
1590    let mut seeds: Vec<(Point3, (f64, f64), (f64, f64))> = Vec::new();
1591    // Coarse threshold scales with the surface size — the distance from
1592    // a grid point on A to its projection on B can be large even near
1593    // the intersection (e.g., sphere R=2 and cylinder R=1 → gap ≈ 1).
1594    let seed_threshold = diag_a.max(diag_b).max(1.0) * 0.5;
1595    let mut min_dist = f64::INFINITY;
1596
1597    #[allow(clippy::cast_precision_loss)]
1598    for ia in 0..grid_res {
1599        for ja in 0..grid_res {
1600            let ua =
1601                u_range_a.0 + (u_range_a.1 - u_range_a.0) * (ia as f64 + 0.5) / (grid_res as f64);
1602            let va =
1603                v_range_a.0 + (v_range_a.1 - v_range_a.0) * (ja as f64 + 0.5) / (grid_res as f64);
1604
1605            let pa = surf_a(ua, va);
1606
1607            // Analytically project onto surface B.
1608            let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
1609            let pb = surf_b(ub, vb);
1610            let dist = (pa - pb).length();
1611            min_dist = min_dist.min(dist);
1612
1613            if dist < seed_threshold {
1614                // Use the coarse seed directly. The marching algorithm
1615                // corrects positions at each step via projection, so seeds
1616                // don't need to be on the exact intersection — they just
1617                // need to be close enough for the marcher to converge.
1618                let mid = Point3::new(
1619                    (pa.x() + pb.x()) * 0.5,
1620                    (pa.y() + pb.y()) * 0.5,
1621                    (pa.z() + pb.z()) * 0.5,
1622                );
1623                seeds.push((mid, (ua, va), (ub, vb)));
1624            }
1625        }
1626    }
1627
1628    // Cheap rejection: the grid samples surface A; the closest sample's
1629    // distance to B lower-bounds how near the two bounded patches come. A
1630    // transversal crossing puts a sample within ~one grid cell of it
1631    // (distance on the order of a cell), so if even the nearest sample is
1632    // several cells away the patches cannot cross — skip the expensive
1633    // marching and return empty. Result-preserving: non-crossing pairs
1634    // already march to nothing, just slowly (this is the gridfinity lip's
1635    // ~80 inner-wall × outer-wall pairs that dominate pavefiller time).
1636    let reject_dist = (char_size / grid_res as f64) * 3.0;
1637    if min_dist > reject_dist {
1638        return Ok(vec![]);
1639    }
1640
1641    if seeds.is_empty() {
1642        return Ok(vec![]);
1643    }
1644
1645    // Aggressively deduplicate seeds — we only need 1-2 per intersection
1646    // branch. Scale dedup radius to ~2% of characteristic surface size
1647    // (at least 10× the march step size) to avoid redundant marches.
1648    let march_step = (char_size * 0.02).clamp(0.005, 0.5);
1649    let dedup_radius = march_step * 10.0;
1650    let mut unique_seeds = Vec::new();
1651    for seed in &seeds {
1652        let dominated = unique_seeds
1653            .iter()
1654            .any(|s: &(Point3, (f64, f64), (f64, f64))| (s.0 - seed.0).length() < dedup_radius);
1655        if !dominated {
1656            unique_seeds.push(*seed);
1657        }
1658    }
1659
1660    // March from each seed.
1661    let mut curves = Vec::new();
1662    let mut used_seeds = vec![false; unique_seeds.len()];
1663
1664    for si in 0..unique_seeds.len() {
1665        if used_seeds[si] {
1666            continue;
1667        }
1668        used_seeds[si] = true;
1669
1670        let march_result = march_analytic_intersection(
1671            &a,
1672            &b,
1673            surf_a.as_ref(),
1674            norm_a.as_ref(),
1675            surf_b.as_ref(),
1676            norm_b.as_ref(),
1677            unique_seeds[si].0,
1678            u_range_a,
1679            v_range_a,
1680            u_range_b,
1681            v_range_b,
1682            march_step,
1683            is_u_periodic(&a),
1684            is_u_periodic(&b),
1685        );
1686
1687        if march_result.len() >= 2 {
1688            for (sj, other) in unique_seeds.iter().enumerate() {
1689                if !used_seeds[sj]
1690                    && march_result
1691                        .iter()
1692                        .any(|p| (*p - other.0).length() < dedup_radius)
1693                {
1694                    used_seeds[sj] = true;
1695                }
1696            }
1697
1698            let ipts: Vec<IntersectionPoint> = march_result
1699                .iter()
1700                .map(|&pt| IntersectionPoint {
1701                    point: pt,
1702                    param1: (0.0, 0.0),
1703                    param2: (0.0, 0.0),
1704                })
1705                .collect();
1706
1707            let degree = 3.min(march_result.len() - 1);
1708            if let Ok(curve) = interpolate(&march_result, degree) {
1709                curves.push(IntersectionCurve {
1710                    curve,
1711                    points: ipts,
1712                });
1713            }
1714        }
1715    }
1716
1717    Ok(curves)
1718}
1719
1720/// Try algebraic (closed-form or semi-algebraic) intersection for known
1721/// surface pairs before falling back to general marching.
1722///
1723/// Returns `Some(curves)` if a specialized method exists, `None` otherwise.
1724///
1725/// Currently handles:
1726/// - **Sphere-sphere**: intersection is a circle (plane through the two centers)
1727/// - **Coaxial cylinders**: same axis → circle(s) or empty
1728/// - **Sphere-cylinder**: reduce to quadratic in one parameter
1729/// - **Cone-cylinder**: parallel axes in the cone's own `v`, other axes
1730///   along the cylinder's rulings
1731#[allow(clippy::too_many_lines)]
1732fn try_algebraic_intersection(
1733    a: &AnalyticSurface<'_>,
1734    b: &AnalyticSurface<'_>,
1735    v_range_a: Option<(f64, f64)>,
1736    v_range_b: Option<(f64, f64)>,
1737) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
1738    match (a, b) {
1739        (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => Ok(
1740            algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)?
1741                .or_else(|| ruling_cone_cylinder(cone, cyl, true)),
1742        ),
1743        (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => Ok(
1744            algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)?
1745                .or_else(|| ruling_cone_cylinder(cone, cyl, false)),
1746        ),
1747        (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
1748            algebraic_sphere_sphere(s1, s2).map(Some)
1749        }
1750        (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
1751            let axis_dot = c1.axis().dot(c2.axis()).abs();
1752            if axis_dot > 1.0 - 1e-10 {
1753                // Axes are parallel — check if they're the same line.
1754                let delta = c2.origin() - c1.origin();
1755                let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
1756                let along = delta_vec.dot(c1.axis());
1757                let perp = (delta_vec - c1.axis() * along).length();
1758                if perp < 1e-8 {
1759                    // Coaxial: same axis, different radii → no intersection
1760                    // (unless equal radius → degenerate overlap, skip)
1761                    if (c1.radius() - c2.radius()).abs() < 1e-8 {
1762                        return Ok(None); // Overlapping — let marcher handle
1763                    }
1764                    return Ok(Some(vec![])); // Coaxial, different radii
1765                }
1766            }
1767            // Non-coaxial: algebraic quadratic in v.
1768            algebraic_cylinder_cylinder(c1, c2)
1769        }
1770        // Sphere-cylinder (both orderings).
1771        (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c)) => {
1772            algebraic_sphere_cylinder(s, c, true)
1773        }
1774        (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
1775            algebraic_sphere_cylinder(s, c, false)
1776        }
1777        (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => algebraic_cone_cone(c1, c2),
1778        (AnalyticSurface::Torus(t), AnalyticSurface::Cylinder(c)) => {
1779            Ok(parallel_axis_torus_cylinder(t, c, true)
1780                .or_else(|| ruling_torus_cylinder(t, c, true)))
1781        }
1782        (AnalyticSurface::Cylinder(c), AnalyticSurface::Torus(t)) => {
1783            Ok(parallel_axis_torus_cylinder(t, c, false)
1784                .or_else(|| ruling_torus_cylinder(t, c, false)))
1785        }
1786        _ => Ok(None),
1787    }
1788}
1789
1790/// A torus and a cylinder whose axes are parallel but distinct (a drill
1791/// through a ring parallel to its axis), traced along the cylinder's
1792/// rulings. A ruling stays at one distance `ρ` from the torus axis, so it
1793/// meets the tube where `(ρ − R)² + z² = r²`: a quadratic in its axial
1794/// parameter. `None` for any other pair (tilted or coaxial axes) and when
1795/// the sampling misses a window narrower than itself.
1796fn parallel_axis_torus_cylinder(
1797    torus: &ToroidalSurface,
1798    cyl: &CylindricalSurface,
1799    torus_first: bool,
1800) -> Option<Vec<IntersectionCurve>> {
1801    let axis = torus.z_axis();
1802    let along = cyl.axis().dot(axis);
1803    if along.abs() < 1.0 - 1e-10 {
1804        return None;
1805    }
1806    let offset = cyl.origin() - torus.center();
1807    if (offset - axis * offset.dot(axis)).length() < Tolerance::new().linear {
1808        return None;
1809    }
1810    let (major, minor) = (torus.major_radius(), torus.minor_radius());
1811    let roots = |u: f64| {
1812        let q = cyl.evaluate(u, 0.0) - torus.center();
1813        let height = q.dot(axis);
1814        let rho = (q - axis * height).length();
1815        let reach = minor * minor - (rho - major) * (rho - major);
1816        ruling_quadratic(1.0, 2.0 * along.signum() * height, height * height - reach)
1817    };
1818    let samples = ruling_samples(cyl, &roots);
1819    let loops = if samples.iter().all(Option::is_some) {
1820        closed_ruling_loops(&samples)
1821    } else {
1822        partial_ruling_loops(cyl, &roots, &samples)
1823    };
1824    if loops.is_empty() {
1825        return None;
1826    }
1827    Some(fit_ruling_loops(&loops, |p| {
1828        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
1829    }))
1830}
1831
1832/// Where two circles in a half-plane through an axis cross, as `(rho, z)`
1833/// pairs (distance from the axis, height along it): each sweeps a circle
1834/// about the axis. `None` (defer to the marcher) when the circles coincide
1835/// or touch, or a crossing lands on or past the axis; `Some` of none when
1836/// they miss.
1837fn meridian_crossings(
1838    first: (f64, f64, f64),
1839    second: (f64, f64, f64),
1840    scale: f64,
1841) -> Option<Vec<(f64, f64)>> {
1842    let ((x1, z1, r1), (x2, z2, r2)) = (first, second);
1843    let (dx, dz) = (x2 - x1, z2 - z1);
1844    let dist = dx.hypot(dz);
1845    let slack = 1e-9 * scale;
1846    if dist < slack || (dist - (r1 + r2)).abs() < slack || (dist - (r1 - r2).abs()).abs() < slack {
1847        return None;
1848    }
1849    if dist > r1 + r2 || dist < (r1 - r2).abs() {
1850        return Some(Vec::new());
1851    }
1852    let along = r2.mul_add(-r2, r1.mul_add(r1, dist * dist)) / (2.0 * dist);
1853    let across = r1.mul_add(r1, -(along * along)).max(0.0).sqrt();
1854    let (ux, uz) = (dx / dist, dz / dist);
1855    let mut crossings = Vec::with_capacity(2);
1856    for side in [1.0, -1.0] {
1857        let rho = x1 + along * ux - side * across * uz;
1858        if rho <= slack {
1859            return None;
1860        }
1861        crossings.push((rho, z1 + along * uz + side * across * ux));
1862    }
1863    Some(crossings)
1864}
1865
1866/// Circles about an axis through `base`, at the given `(rho, z)` crossings.
1867fn circles_about_axis(
1868    base: Point3,
1869    axis: Vec3,
1870    crossings: &[(f64, f64)],
1871) -> Result<Vec<ExactIntersectionCurve>, MathError> {
1872    crossings
1873        .iter()
1874        .map(|&(rho, z)| {
1875            Circle3D::new(base + axis * z, axis, rho).map(ExactIntersectionCurve::Circle)
1876        })
1877        .collect()
1878}
1879
1880/// Exact intersection of two tori sharing an axis: their tube cross-sections
1881/// in a half-plane through the axis cross in up to two points, and each sweeps
1882/// a circle about the axis.
1883///
1884/// `None` (defer to the marcher) unless the axes lie on one line, or when the
1885/// cross-sections coincide or touch.
1886///
1887/// # Errors
1888///
1889/// Returns an error if a section circle cannot be built.
1890pub fn exact_torus_torus(
1891    first: &ToroidalSurface,
1892    second: &ToroidalSurface,
1893) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1894    let axis = first.z_axis();
1895    let scale = first.major_radius() + second.major_radius();
1896    let offset = second.center() - first.center();
1897    // A spindle torus's tube also crosses the far side of the axis.
1898    if first.minor_radius() >= first.major_radius()
1899        || second.minor_radius() >= second.major_radius()
1900        || axis.cross(second.z_axis()).length() > 1e-9
1901        || offset.cross(axis).length() > 1e-9 * scale
1902    {
1903        return Ok(None);
1904    }
1905    let Some(crossings) = meridian_crossings(
1906        (first.major_radius(), 0.0, first.minor_radius()),
1907        (
1908            second.major_radius(),
1909            offset.dot(axis),
1910            second.minor_radius(),
1911        ),
1912        scale,
1913    ) else {
1914        return Ok(None);
1915    };
1916    circles_about_axis(first.center(), axis, &crossings).map(Some)
1917}
1918
1919/// Exact intersection of a torus with a cylinder sharing its axis.
1920///
1921/// The wall line and the tube's cross-section in a half-plane through the
1922/// axis cross in up to two points, each sweeping a circle about the axis.
1923///
1924/// `None` (defer to the marcher) unless the axes lie on one line, or when
1925/// the wall touches the tube.
1926///
1927/// # Errors
1928///
1929/// Returns an error if a section circle cannot be built.
1930pub fn exact_cylinder_torus(
1931    cylinder: &CylindricalSurface,
1932    torus: &ToroidalSurface,
1933) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1934    let axis = torus.z_axis();
1935    let scale = torus.major_radius() + cylinder.radius();
1936    let offset = cylinder.origin() - torus.center();
1937    // A spindle torus's tube also crosses the far side of the axis.
1938    if torus.minor_radius() >= torus.major_radius()
1939        || axis.cross(cylinder.axis()).length() > 1e-9
1940        || offset.cross(axis).length() > 1e-9 * scale
1941    {
1942        return Ok(None);
1943    }
1944    let gap = cylinder.radius() - torus.major_radius();
1945    let small = torus.minor_radius();
1946    if (gap.abs() - small).abs() < 1e-9 * scale {
1947        return Ok(None);
1948    }
1949    if gap.abs() > small {
1950        return Ok(Some(Vec::new()));
1951    }
1952    let height = small.mul_add(small, -(gap * gap)).sqrt();
1953    circles_about_axis(
1954        torus.center(),
1955        axis,
1956        &[(cylinder.radius(), height), (cylinder.radius(), -height)],
1957    )
1958    .map(Some)
1959}
1960
1961/// Exact intersection of a torus with a sphere centred on its axis.
1962///
1963/// The sphere's great circle and the tube's cross-section in a half-plane
1964/// through the axis cross in up to two points, and each sweeps a circle
1965/// about the axis.
1966///
1967/// `None` (defer to the marcher) unless the sphere's centre lies on the axis,
1968/// or when the two circles touch.
1969///
1970/// # Errors
1971///
1972/// Returns an error if a section circle cannot be built.
1973pub fn exact_sphere_torus(
1974    sphere: &SphericalSurface,
1975    torus: &ToroidalSurface,
1976) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1977    let axis = torus.z_axis();
1978    let scale = torus.major_radius() + sphere.radius();
1979    let offset = sphere.center() - torus.center();
1980    // A spindle torus's tube also crosses the far side of the axis.
1981    if torus.minor_radius() >= torus.major_radius() || offset.cross(axis).length() > 1e-9 * scale {
1982        return Ok(None);
1983    }
1984    let Some(crossings) = meridian_crossings(
1985        (0.0, offset.dot(axis), sphere.radius()),
1986        (torus.major_radius(), 0.0, torus.minor_radius()),
1987        scale,
1988    ) else {
1989        return Ok(None);
1990    };
1991    circles_about_axis(torus.center(), axis, &crossings).map(Some)
1992}
1993
1994/// Exact coaxial cone-cone intersection: returns the shared circle.
1995///
1996/// Two cones that share an axis are concentric circles at every axial
1997/// station, so they meet only where their radii are equal. Each cone's
1998/// radius is linear in the axial coordinate `t` (measured along the shared
1999/// axis from cone 1's apex): `r1 = m1·t` and `r2 = m2·σ·(t − d2)`, where
2000/// `m_i = cot(half_angle_i)`, `σ = sign(axis2·axis1)`, and `d2` is cone 2's
2001/// apex position in that coordinate. Equating gives a single crossing `t*`
2002/// → one circle (the shared rim). The general marcher mishandles this case:
2003/// at the radii-crossing the surfaces are nearly tangent, so a grid-seeded
2004/// march fragments the clean circle into dozens of degenerate micro-curves.
2005///
2006/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
2007/// the cones do not meet (parallel radius lines or a crossing on the wrong
2008/// nappe), and `None` for the identical-cone overlap or a degenerate
2009/// (near-flat) cone — both of which fall through to the general path.
2010/// Parallel-but-offset axes with equal half-angle tangents reduce to a
2011/// radical-plane conic (`offset_parallel_cone_cone`); other offset
2012/// configurations defer to the marcher with `None`.
2013///
2014/// # Errors
2015///
2016/// Returns [`MathError`] if the shared-rim `Circle3D` cannot be constructed
2017/// (e.g. a non-finite center or radius from a malformed cone).
2018pub fn exact_cone_cone(
2019    c1: &ConicalSurface,
2020    c2: &ConicalSurface,
2021) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2022    let axis = c1.axis();
2023    let axis2 = c2.axis();
2024
2025    // Coaxial check: parallel axes and the second apex lies on the first axis.
2026    if axis.dot(axis2).abs() < 1.0 - 1e-10 {
2027        return Ok(None); // Non-coaxial: quartic curve, let the marcher handle.
2028    }
2029    let apex1 = c1.apex();
2030    let apex2 = c2.apex();
2031    let delta = apex2 - apex1;
2032    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2033    let along = delta_v.dot(axis);
2034    if (delta_v - axis * along).length() > 1e-8 {
2035        return offset_parallel_cone_cone(c1, c2);
2036    }
2037
2038    let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
2039    if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
2040        return Ok(None); // Degenerate (near-flat) cone.
2041    }
2042    let m1 = c1.half_angle().cos() / s1;
2043    let m2 = c2.half_angle().cos() / s2;
2044    let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
2045    let d2 = along; // apex2 position along `axis`, measured from apex1.
2046
2047    let denom = m1 - m2 * sigma;
2048    if denom.abs() < 1e-12 {
2049        // Parallel radius lines: identical cones (coincident apex, same opening)
2050        // overlap — defer to the general/same-domain path; otherwise no meeting.
2051        if sigma > 0.0 && d2.abs() < 1e-9 {
2052            return Ok(None);
2053        }
2054        return Ok(Some(vec![]));
2055    }
2056
2057    let t_star = (-m2 * sigma * d2) / denom;
2058    let radius = m1 * t_star;
2059    if radius < 1e-12 {
2060        return Ok(Some(vec![])); // Crossing on the wrong nappe / no real circle.
2061    }
2062
2063    let center = Point3::new(
2064        apex1.x() + axis.x() * t_star,
2065        apex1.y() + axis.y() * t_star,
2066        apex1.z() + axis.z() * t_star,
2067    );
2068    let circle = Circle3D::new(center, axis, radius)?;
2069    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
2070}
2071
2072/// Parallel-axis (or anti-parallel), offset-apex cones with equal half-angle
2073/// tangents: subtracting the two quadric equations cancels both the radial
2074/// and the axial quadratic terms (their coefficients depend only on
2075/// `tan²(half_angle)`), so every intersection point lies on a plane — the
2076/// degenerate member of the quadric pencil — and plane ∩ cone is an exact
2077/// conic. The gridfinity spacer lip fuse hits this exactly: opposed 45°
2078/// corner cones offset 0.25mm, which the marcher shreds into ~64 closed
2079/// micro-loops per pair (#1570). Unequal angles keep a genuine quadratic
2080/// term, and an unbounded section (hyperbola/parabola) has no closed-form
2081/// win over the marcher — both defer with `None`.
2082fn offset_parallel_cone_cone(
2083    c1: &ConicalSurface,
2084    c2: &ConicalSurface,
2085) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2086    if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
2087        return Ok(None); // Degenerate (near-flat) cone, as in the coaxial path.
2088    }
2089    let t1 = c1.half_angle().tan();
2090    let t2 = c2.half_angle().tan();
2091    if !t1.is_finite() || !t2.is_finite() {
2092        return Ok(None);
2093    }
2094    if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
2095        return Ok(None);
2096    }
2097
2098    let w = c1.axis();
2099    let apex1 = c1.apex();
2100    let apex2 = c2.apex();
2101    let delta = apex2 - apex1;
2102    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2103    let s = delta_v.dot(w);
2104    let tm = 0.5 * (t1 + t2);
2105    let k = 1.0 + tm * tm;
2106
2107    // In the apex1 frame each cone is |P|² − k(P·w)² = 0 (shifted by δ for
2108    // cone 2; the axis SIGN drops out since only (P·w)² appears). Their
2109    // difference: P·(2δ − 2ksw) = |δ|² − ks².
2110    let n = (delta_v - w * (k * s)) * 2.0;
2111    let n_len = n.length();
2112    if n_len < 1e-12 {
2113        return Ok(None);
2114    }
2115    let n_hat = n * (1.0 / n_len);
2116    let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
2117
2118    // `exact_plane_cone` already rejects sections on cone 1's phantom nappe;
2119    // cone 2's nappe must be checked here. A conic on the shared quadric
2120    // pencil cannot cross between nappes except exactly through apex 2, so
2121    // sampled quarter-points either all pass or all fail; a mixed verdict
2122    // means an apex-touching degeneracy — defer to the marcher.
2123    let axis2 = c2.axis();
2124    let scale = 1.0 + delta_v.length();
2125    let mut out = Vec::new();
2126    for curve in exact_plane_cone(c1, n_hat, d, 0.0)? {
2127        let samples: Vec<Point3> = match &curve {
2128            ExactIntersectionCurve::Circle(c) => (0..4)
2129                .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
2130                .collect(),
2131            ExactIntersectionCurve::Ellipse(e) => (0..4)
2132                .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
2133                .collect(),
2134            ExactIntersectionCurve::Points(_) => return Ok(None),
2135        };
2136        let on_real_nappe = |p: &Point3| {
2137            let rel = *p - apex2;
2138            Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
2139        };
2140        let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
2141        match hits {
2142            0 => {}
2143            4 => out.push(curve),
2144            _ => return Ok(None),
2145        }
2146    }
2147    Ok(Some(out))
2148}
2149
2150/// Exact coaxial cone-cylinder intersection: returns the shared circle.
2151///
2152/// A cone and a cylinder sharing an axis are concentric circles at every
2153/// axial station, so they meet only where the cone's radius equals the
2154/// cylinder's. The cone radius is linear in the axial coordinate `t` from its
2155/// apex (`r = m·t`, `m = cot(half_angle)`), the cylinder radius is the
2156/// constant `R`, so `m·t = R` gives a single crossing `t*` → one circle. This
2157/// is the gridfinity lip's top knife edge (inner tapered corner = cone, outer
2158/// corner = cylinder, concentric, radii matching at `Z_PEAK`); the general
2159/// marcher fragments that near-tangent contact into dozens of degenerate
2160/// micro-curves.
2161///
2162/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
2163/// the crossing degenerates to the apex, and `None` (defer to the marcher)
2164/// when the surfaces are not coaxial or the cone is near-flat / near-axial.
2165///
2166/// # Errors
2167///
2168/// Returns [`MathError`] if the shared `Circle3D` cannot be constructed.
2169pub fn exact_cone_cylinder(
2170    cone: &ConicalSurface,
2171    cyl: &CylindricalSurface,
2172) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2173    let axis = cone.axis();
2174    let cyl_axis = cyl.axis();
2175
2176    // Coaxial check: parallel axes and the cone apex on the cylinder's axis.
2177    if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
2178        return Ok(None);
2179    }
2180    let apex = cone.apex();
2181    let delta = apex - cyl.origin();
2182    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2183    let along = delta_v.dot(cyl_axis);
2184    if (delta_v - cyl_axis * along).length() > 1e-8 {
2185        return Ok(None);
2186    }
2187
2188    let s = cone.half_angle().sin();
2189    if s.abs() < 1e-12 {
2190        return Ok(None); // near-flat cone.
2191    }
2192    let m = cone.half_angle().cos() / s; // dr/dt along the cone axis.
2193    if m.abs() < 1e-12 {
2194        return Ok(None); // near-axial cone: radius ~constant.
2195    }
2196
2197    let t_star = cyl.radius() / m; // where the cone radius m·t equals R.
2198    if t_star.abs() < 1e-12 {
2199        return Ok(Some(vec![])); // crossing at the apex — no real circle.
2200    }
2201    let center = Point3::new(
2202        apex.x() + axis.x() * t_star,
2203        apex.y() + axis.y() * t_star,
2204        apex.z() + axis.z() * t_star,
2205    );
2206    let circle = Circle3D::new(center, axis, cyl.radius())?;
2207    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
2208}
2209
2210/// Algebraic cone-cone intersection (NURBS form for the general bounded
2211/// path). Delegates to [`exact_cone_cone`] and samples each exact conic
2212/// (coaxial circle or offset-parallel radical-plane ellipse) into an
2213/// interpolated NURBS `IntersectionCurve`, mirroring the
2214/// sphere-cylinder algebraic path. phase FF prefers the exact circle form
2215/// directly (so the section edge links to the coincident boundary), but a
2216/// caller of `intersect_analytic_analytic_bounded` still gets one clean
2217/// curve instead of the marcher's fragments.
2218fn algebraic_cone_cone(
2219    c1: &ConicalSurface,
2220    c2: &ConicalSurface,
2221) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2222    let Some(exacts) = exact_cone_cone(c1, c2)? else {
2223        return Ok(None);
2224    };
2225    let mut curves = Vec::new();
2226    for exact in exacts {
2227        let n_samples = 33;
2228        let mut positions = Vec::with_capacity(n_samples);
2229        let mut points = Vec::with_capacity(n_samples);
2230        #[allow(clippy::cast_precision_loss)]
2231        for i in 0..n_samples {
2232            let theta = TAU * i as f64 / (n_samples - 1) as f64;
2233            let pt = match &exact {
2234                ExactIntersectionCurve::Circle(circle) => {
2235                    crate::traits::ParametricCurve::evaluate(circle, theta)
2236                }
2237                ExactIntersectionCurve::Ellipse(ellipse) => {
2238                    crate::traits::ParametricCurve::evaluate(ellipse, theta)
2239                }
2240                ExactIntersectionCurve::Points(_) => break,
2241            };
2242            positions.push(pt);
2243            points.push(IntersectionPoint {
2244                point: pt,
2245                param1: (0.0, 0.0),
2246                param2: (0.0, 0.0),
2247            });
2248        }
2249        if positions.is_empty() {
2250            continue;
2251        }
2252        let degree = 3.min(positions.len() - 1);
2253        let curve = interpolate(&positions, degree)?;
2254        curves.push(IntersectionCurve { curve, points });
2255    }
2256    Ok(Some(curves))
2257}
2258
2259/// Exact coaxial sphere-cylinder intersection: returns the shared circle(s).
2260///
2261/// A sphere of radius `R` centered at `C` and a cylinder of radius `r` whose
2262/// axis passes through `C` meet in concentric circles of radius `r` at the
2263/// axial stations where `sqrt(R² − z²) = r`, i.e. `z = ±sqrt(R² − r²)`
2264/// measured from `C` along the axis. A proper crossing yields two circles; a
2265/// tangent contact (`r = R`) yields one; a cylinder wider than the sphere, or
2266/// a non-coaxial configuration (quartic curve), yields none/defers.
2267///
2268/// Mirrors [`exact_cone_cylinder`] so phase FF can emit the section as an
2269/// exact `Circle3D` (which the closed-circle split + seam adoption recognise)
2270/// rather than the marcher's NURBS fragments.
2271///
2272/// Returns `Some(vec![..])` (0, 1, or 2 circles) for the coaxial case, and
2273/// `None` (defer to the general marcher) when the axes are not coaxial.
2274///
2275/// # Errors
2276///
2277/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
2278pub fn exact_sphere_cylinder(
2279    sphere: &SphericalSurface,
2280    cyl: &CylindricalSurface,
2281) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2282    let sc = sphere.center();
2283    let r_sphere = sphere.radius();
2284    let co = cyl.origin();
2285    let axis = cyl.axis();
2286    let r_cyl = cyl.radius();
2287
2288    // Project sphere center onto the cylinder axis.
2289    let delta = sc - co;
2290    let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2291    let along = delta_vec.dot(axis);
2292    let perp_vec = delta_vec - axis * along;
2293    let d_perp = perp_vec.length();
2294
2295    // Non-coaxial sphere-cylinder intersections produce quartic curves;
2296    // defer those to the general marcher.
2297    if d_perp > 1e-7 {
2298        return Ok(None);
2299    }
2300
2301    // Coaxial: the sphere center lies on the cylinder axis. No real circle
2302    // when the cylinder is wider than the sphere or they are tangent-internal.
2303    if r_cyl > r_sphere + 1e-10 {
2304        return Ok(Some(vec![]));
2305    }
2306    let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
2307    if z_sq < 0.0 {
2308        return Ok(Some(vec![]));
2309    }
2310    let z = z_sq.sqrt();
2311
2312    // The sphere center projected onto the axis is the midpoint of the two
2313    // section circles, each offset by ±z along the axis with radius `r_cyl`.
2314    let center_axis_pt = Point3::new(
2315        co.x() + axis.x() * along,
2316        co.y() + axis.y() * along,
2317        co.z() + axis.z() * along,
2318    );
2319
2320    let mut circles = Vec::new();
2321    let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
2322    for &z_offset in offsets {
2323        let center = Point3::new(
2324            center_axis_pt.x() + axis.x() * z_offset,
2325            center_axis_pt.y() + axis.y() * z_offset,
2326            center_axis_pt.z() + axis.z() * z_offset,
2327        );
2328        let circle = Circle3D::new(center, axis, r_cyl)?;
2329        circles.push(ExactIntersectionCurve::Circle(circle));
2330    }
2331    Ok(Some(circles))
2332}
2333
2334/// Algebraic sphere-cylinder intersection (NURBS form for the general bounded
2335/// path). A coaxial pair delegates to [`exact_sphere_cylinder`] and samples
2336/// each exact circle into an interpolated NURBS `IntersectionCurve`. phase FF
2337/// prefers the exact circle form directly (so the section edge links to the
2338/// coincident boundary and the closed-circle splitter can carve the spherical
2339/// band), but a caller of `intersect_analytic_analytic_bounded` still gets
2340/// clean curves instead of the marcher's fragments. Any other pair is traced
2341/// along the cylinder's rulings ([`off_axis_sphere_cylinder`]).
2342fn algebraic_sphere_cylinder(
2343    sphere: &SphericalSurface,
2344    cyl: &CylindricalSurface,
2345    sphere_first: bool,
2346) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2347    let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
2348        return Ok(off_axis_sphere_cylinder(sphere, cyl, sphere_first));
2349    };
2350
2351    let mut curves = Vec::new();
2352    for exact in exacts {
2353        let ExactIntersectionCurve::Circle(circle) = exact else {
2354            continue;
2355        };
2356        let n_samples = 33;
2357        let mut points = Vec::with_capacity(n_samples);
2358        let mut positions = Vec::with_capacity(n_samples);
2359        #[allow(clippy::cast_precision_loss)]
2360        for i in 0..n_samples {
2361            let theta = TAU * i as f64 / (n_samples - 1) as f64;
2362            let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
2363            positions.push(pt);
2364            let (param1, param2) = in_order(
2365                sphere.project_point(pt),
2366                cyl.project_point(pt),
2367                sphere_first,
2368            );
2369            points.push(IntersectionPoint {
2370                point: pt,
2371                param1,
2372                param2,
2373            });
2374        }
2375        let degree = 3.min(positions.len() - 1);
2376        let curve = interpolate(&positions, degree)?;
2377        curves.push(IntersectionCurve { curve, points });
2378    }
2379
2380    Ok(Some(curves))
2381}
2382
2383/// A sphere and a cylinder whose axis misses the sphere's centre (a drill
2384/// entering a ball off its axis), traced along the cylinder's rulings: the
2385/// ruling `c(u) + v·a` meets the sphere where `v² + 2(q·a)·v + |q|² − R² = 0`,
2386/// with `q = c(u) − C`. When every ruling meets the sphere (the cylinder
2387/// passes wholly through it) the roots trace an entry and an exit loop;
2388/// otherwise each window of meeting rulings carries one loop. `Some(empty)`
2389/// when the two cannot meet, `None` when the sampling misses a window
2390/// narrower than itself.
2391fn off_axis_sphere_cylinder(
2392    sphere: &SphericalSurface,
2393    cyl: &CylindricalSurface,
2394    sphere_first: bool,
2395) -> Option<Vec<IntersectionCurve>> {
2396    let (centre, radius) = (sphere.center(), sphere.radius());
2397    let axis = cyl.axis();
2398    let offset = centre - cyl.origin();
2399    let axis_distance = (offset - axis * offset.dot(axis)).length();
2400    let lin_tol = Tolerance::new().linear;
2401    if axis_distance > radius + cyl.radius() + lin_tol
2402        || axis_distance + radius < cyl.radius() - lin_tol
2403    {
2404        return Some(Vec::new());
2405    }
2406    let roots = |u: f64| {
2407        let q = cyl.evaluate(u, 0.0) - centre;
2408        ruling_quadratic(1.0, 2.0 * q.dot(axis), q.dot(q) - radius * radius)
2409    };
2410    let samples = ruling_samples(cyl, &roots);
2411    let loops = if samples.iter().all(Option::is_some) {
2412        closed_ruling_loops(&samples)
2413    } else {
2414        partial_ruling_loops(cyl, &roots, &samples)
2415    };
2416    if loops.is_empty() {
2417        return None;
2418    }
2419    Some(fit_ruling_loops(&loops, |p| {
2420        in_order(sphere.project_point(p), cyl.project_point(p), sphere_first)
2421    }))
2422}
2423
2424/// Parameters on the pair's first and second surfaces, from those on `a`
2425/// and `b` and whether `a` came first.
2426const fn in_order(a: (f64, f64), b: (f64, f64), a_first: bool) -> ((f64, f64), (f64, f64)) {
2427    if a_first { (a, b) } else { (b, a) }
2428}
2429
2430/// Algebraic cylinder-cylinder intersection for non-coaxial cylinders.
2431///
2432/// For two cylinders with axes that are NOT parallel, the intersection
2433/// consists of up to two closed space curves. These are found by
2434/// parameterizing one cylinder's angular coordinate `u ∈ [0, 2π]` and
2435/// solving a quadratic in the axial parameter `v` to find where each
2436/// "ring" of cylinder A sits on cylinder B.
2437///
2438/// The quadratic is:
2439///   `v²·(1 - α²) + 2v·(q·a₁ - α·q·a₂) + (|q|² - (q·a₂)² - r₂²) = 0`
2440/// where `α = a₁·a₂`, `q(u)` is the radial point on cylinder 1 minus
2441/// cylinder 2's origin, `a₁`/`a₂` are the cylinder axes, and `r₂` is
2442/// cylinder 2's radius.
2443#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
2444fn algebraic_cylinder_cylinder(
2445    c1: &CylindricalSurface,
2446    c2: &CylindricalSurface,
2447) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2448    let alpha = c1.axis().dot(c2.axis());
2449    let a_coeff = 1.0 - alpha * alpha;
2450
2451    // Should only be called for non-parallel axes.
2452    if a_coeff.abs() < 1e-12 {
2453        return Ok(None);
2454    }
2455
2456    let r1 = c1.radius();
2457    let r2 = c2.radius();
2458    let o1 = c1.origin();
2459    let o2 = c2.origin();
2460    let a1 = c1.axis();
2461    let a2 = c2.axis();
2462
2463    // Separation check: distance between axes vs sum of radii.
2464    // Closest approach of two skew lines:
2465    let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
2466    let cross = a1.cross(a2);
2467    let cross_len = cross.length();
2468    if cross_len > 1e-12 {
2469        let axis_dist = delta.dot(cross).abs() / cross_len;
2470        if axis_dist > r1 + r2 + Tolerance::new().linear {
2471            return Ok(Some(vec![])); // No intersection
2472        }
2473    }
2474
2475    // Solve every ruling of one cylinder against the other. When EVERY
2476    // ruling of the swept cylinder meets the other (the thinner of two
2477    // crossing tubes), the two roots trace the curve's two closed loops.
2478    // Swept the other way only a window of rulings meets, and each root
2479    // traces an open arc of one loop.
2480    let roots = |sweep: &CylindricalSurface, other: &CylindricalSurface| {
2481        let (o, a, radius) = (other.origin(), other.axis(), other.radius());
2482        let alpha = sweep.axis().dot(a);
2483        let quad = 1.0 - alpha * alpha;
2484        let (axis, sweep) = (sweep.axis(), sweep.clone());
2485        move |u: f64| {
2486            let q = sweep.evaluate(u, 0.0) - o;
2487            let (q_a1, q_a2) = (q.dot(axis), q.dot(a));
2488            let b = 2.0 * (q_a1 - alpha * q_a2);
2489            let c = q.dot(q) - q_a2 * q_a2 - radius * radius;
2490            ruling_quadratic(quad, b, c)
2491        }
2492    };
2493    let (roots1, roots2) = (roots(c1, c2), roots(c2, c1));
2494    let samples1 = ruling_samples(c1, &roots1);
2495    let loops = if samples1.iter().all(Option::is_some) {
2496        closed_ruling_loops(&samples1)
2497    } else {
2498        let samples2 = ruling_samples(c2, &roots2);
2499        if samples2.iter().all(Option::is_some) {
2500            closed_ruling_loops(&samples2)
2501        } else if samples1.iter().any(Option::is_some) {
2502            partial_ruling_loops(c1, &roots1, &samples1)
2503        } else {
2504            partial_ruling_loops(c2, &roots2, &samples2)
2505        }
2506    };
2507    if loops.is_empty() {
2508        return Ok(None);
2509    }
2510    Ok(Some(fit_ruling_loops(&loops, |p| {
2511        (c1.project_point(p), c2.project_point(p))
2512    })))
2513}
2514
2515/// A cone and a cylinder whose axes are not parallel, traced along the
2516/// cylinder's rulings. A ruling `q + t w` meets the cone's double quadric
2517/// `|p - apex|^2 = h^2 / sin^2(half_angle)`, with `h` the offset along the
2518/// cone's axis, where a quadratic in `t` vanishes. `None` (the marcher's
2519/// case) when a ruling meets the far nappe, where no cone face lies, when
2520/// the rulings run along the cone's generators, or when no ruling meets it.
2521fn ruling_cone_cylinder(
2522    cone: &ConicalSurface,
2523    cyl: &CylindricalSurface,
2524    cone_first: bool,
2525) -> Option<Vec<IntersectionCurve>> {
2526    let (sin_t, cos_t) = cone.half_angle().sin_cos();
2527    if sin_t < 1e-12 || cos_t < 1e-12 {
2528        return None;
2529    }
2530    let (apex, d, w) = (cone.apex(), cone.axis(), cyl.axis());
2531    let s = 1.0 / (sin_t * sin_t);
2532    let alpha = w.dot(d);
2533    let quad = 1.0 - s * alpha * alpha;
2534    if quad.abs() < 1e-9 {
2535        return None;
2536    }
2537    let roots = |u: f64| {
2538        let delta = cyl.evaluate(u, 0.0) - apex;
2539        let (dd, dw) = (delta.dot(d), delta.dot(w));
2540        let b = 2.0 * (dw - s * dd * alpha);
2541        let c = delta.dot(delta) - s * dd * dd;
2542        ruling_quadratic(quad, b, c)
2543    };
2544    let lin_tol = Tolerance::new().linear;
2545    let far_nappe = (0..WINDOW_SCAN * RULING_SAMPLES).any(|k| {
2546        #[allow(clippy::cast_precision_loss)]
2547        let u = TAU * (k as f64 + 0.5) / (WINDOW_SCAN * RULING_SAMPLES) as f64;
2548        let (disc, vp, vm) = roots(u);
2549        disc >= -lin_tol
2550            && [vp, vm]
2551                .iter()
2552                .any(|&t| (cyl.evaluate(u, t) - apex).dot(d) < -lin_tol)
2553    });
2554    if far_nappe {
2555        return None;
2556    }
2557    let samples = ruling_samples(cyl, &roots);
2558    // A window of meeting rulings narrower than the sampling would vanish
2559    // (a cone's tip just through the wall) while the others still made
2560    // loops; a finer scan finds every window, and any that the sampling
2561    // covers thinly goes to the marcher.
2562    let scan = WINDOW_SCAN * RULING_SAMPLES;
2563    // Ruling sample `i` lies midway between scan points
2564    // `WINDOW_SCAN i + 7` and `WINDOW_SCAN i + 8`.
2565    #[allow(clippy::cast_precision_loss)]
2566    let meets = |k: usize| roots(TAU * ((k % scan) as f64 + 0.5) / scan as f64).0 >= -lin_tol;
2567    if let Some(start) = (0..scan).find(|&k| !meets(k)) {
2568        let mut k = start;
2569        while k < start + scan {
2570            if !meets(k) {
2571                k += 1;
2572                continue;
2573            }
2574            let first = k;
2575            while k < start + scan && meets(k) {
2576                k += 1;
2577            }
2578            let covered = (first..k)
2579                .filter(|&j| j % WINDOW_SCAN == WINDOW_SCAN / 2 - 1 && meets(j + 1))
2580                .count();
2581            if covered < WINDOW_MIN_SAMPLES {
2582                return None;
2583            }
2584        }
2585    }
2586    let loops = if samples.iter().all(Option::is_some) {
2587        closed_ruling_loops(&samples)
2588    } else {
2589        partial_ruling_loops(cyl, &roots, &samples)
2590    };
2591    if loops.is_empty() {
2592        return None;
2593    }
2594    Some(fit_ruling_loops(&loops, |p| {
2595        in_order(cone.project_point(p), cyl.project_point(p), cone_first)
2596    }))
2597}
2598
2599/// A torus and a cylinder whose axes are not parallel, where every ruling
2600/// of the cylinder meets the torus the same nonzero even number of times (a
2601/// rod through the ring's tube): a ruling meets the torus where a quartic in
2602/// its parameter vanishes, and each of its roots, taken in order, sweeps one
2603/// closed loop around the cylinder. `None` (the marcher's case) when the
2604/// count varies between rulings, where the curve turns back between them,
2605/// checked on a scan finer than the sampling so a narrow window of missing
2606/// rulings is not stepped over, and for a spindle torus, whose quartic also
2607/// holds its inner lemon.
2608fn ruling_torus_cylinder(
2609    torus: &ToroidalSurface,
2610    cyl: &CylindricalSurface,
2611    torus_first: bool,
2612) -> Option<Vec<IntersectionCurve>> {
2613    if cyl.axis().dot(torus.z_axis()).abs() > 1.0 - 1e-9
2614        || torus.minor_radius() >= torus.major_radius()
2615    {
2616        return None;
2617    }
2618    let roots = |u: f64| intersect_line_torus(torus, cyl.evaluate(u, 0.0), cyl.axis());
2619    let rows: Vec<Vec<f64>> = (0..RULING_SAMPLES).map(|i| roots(ruling_u(i))).collect();
2620    let count = rows[0].len();
2621    let scan = WINDOW_SCAN * RULING_SAMPLES;
2622    #[allow(clippy::cast_precision_loss)]
2623    if count == 0
2624        || count % 2 == 1
2625        || (0..scan).any(|k| roots(TAU * (k as f64 + 0.5) / scan as f64).len() != count)
2626    {
2627        return None;
2628    }
2629    let loops: Vec<Vec<Point3>> = (0..count)
2630        .map(|j| {
2631            let mut pts: Vec<Point3> = rows
2632                .iter()
2633                .enumerate()
2634                .map(|(i, r)| cyl.evaluate(ruling_u(i), r[j]))
2635                .collect();
2636            pts.push(pts[0]);
2637            pts
2638        })
2639        .collect();
2640    Some(fit_ruling_loops(&loops, |p| {
2641        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
2642    }))
2643}
2644
2645/// Scan points per ruling sample when looking for windows of meeting
2646/// rulings, and the fewest samples a window needs to be fit.
2647const WINDOW_SCAN: usize = 16;
2648const WINDOW_MIN_SAMPLES: usize = 8;
2649
2650/// Rulings sampled around a swept cylinder, half a step off u = 0 so the
2651/// branches of a self-touching curve (equal crossing cylinders) do not share
2652/// a sample.
2653const RULING_SAMPLES: usize = 128;
2654
2655#[allow(clippy::cast_precision_loss)]
2656fn ruling_u(i: usize) -> f64 {
2657    TAU * (i as f64 + 0.5) / RULING_SAMPLES as f64
2658}
2659
2660/// The discriminant and roots of `quad·v² + b·v + c = 0`.
2661fn ruling_quadratic(quad: f64, b: f64, c: f64) -> (f64, f64, f64) {
2662    let disc = b * b - 4.0 * quad * c;
2663    let root = disc.max(0.0).sqrt();
2664    (disc, (-b + root) / (2.0 * quad), (-b - root) / (2.0 * quad))
2665}
2666
2667/// The two points where each sampled ruling of `sweep` meets the other
2668/// surface, from `roots(u)` (the discriminant and the two axial parameters),
2669/// or `None` for a ruling that misses it.
2670fn ruling_samples(
2671    sweep: &CylindricalSurface,
2672    roots: &impl Fn(f64) -> (f64, f64, f64),
2673) -> Vec<Option<(Point3, Point3)>> {
2674    let lin_tol = Tolerance::new().linear;
2675    (0..RULING_SAMPLES)
2676        .map(|i| {
2677            let u = ruling_u(i);
2678            let (disc, vp, vm) = roots(u);
2679            (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
2680        })
2681        .collect()
2682}
2683
2684/// Every ruling meets the other surface: each root traces a closed loop.
2685fn closed_ruling_loops(samples: &[Option<(Point3, Point3)>]) -> Vec<Vec<Point3>> {
2686    let mut plus: Vec<Point3> = samples.iter().flatten().map(|s| s.0).collect();
2687    let mut minus: Vec<Point3> = samples.iter().flatten().map(|s| s.1).collect();
2688    plus.push(plus[0]);
2689    minus.push(minus[0]);
2690    vec![plus, minus]
2691}
2692
2693/// Only windows of rulings meet the other surface: each cyclic window
2694/// carries one loop, out along one root and back along the other, the two
2695/// joined where the discriminant vanishes. Empty when no sample meets it (a
2696/// window narrower than the sampling).
2697fn partial_ruling_loops(
2698    sweep: &CylindricalSurface,
2699    roots: &impl Fn(f64) -> (f64, f64, f64),
2700    samples: &[Option<(Point3, Point3)>],
2701) -> Vec<Vec<Point3>> {
2702    let branch_point = |inside: usize, outside: usize| -> Point3 {
2703        let (mut lo, mut hi) = (ruling_u(inside), ruling_u(outside));
2704        if (hi - lo).abs() > std::f64::consts::PI {
2705            hi += if hi < lo { TAU } else { -TAU };
2706        }
2707        for _ in 0..60 {
2708            let mid = 0.5 * (lo + hi);
2709            if roots(mid).0 >= 0.0 {
2710                lo = mid;
2711            } else {
2712                hi = mid;
2713            }
2714        }
2715        let (_, vp, vm) = roots(lo);
2716        sweep.evaluate(lo, 0.5 * (vp + vm))
2717    };
2718    let Some(first_gap) = samples.iter().position(Option::is_none) else {
2719        return Vec::new();
2720    };
2721    let mut loops = Vec::new();
2722    let mut k = 0;
2723    while k < RULING_SAMPLES {
2724        let i = (first_gap + k) % RULING_SAMPLES;
2725        if samples[i].is_none() {
2726            k += 1;
2727            continue;
2728        }
2729        let start = i;
2730        let mut run = Vec::new();
2731        while k < RULING_SAMPLES {
2732            let j = (first_gap + k) % RULING_SAMPLES;
2733            let Some(pair) = samples[j] else { break };
2734            run.push(pair);
2735            k += 1;
2736        }
2737        let end = (start + run.len() - 1) % RULING_SAMPLES;
2738        let head = branch_point(start, (start + RULING_SAMPLES - 1) % RULING_SAMPLES);
2739        let tail = branch_point(end, (end + 1) % RULING_SAMPLES);
2740        let mut pts = vec![head];
2741        pts.extend(run.iter().map(|p| p.0));
2742        pts.push(tail);
2743        pts.extend(run.iter().rev().map(|p| p.1));
2744        pts.push(head);
2745        loops.push(pts);
2746    }
2747    loops
2748}
2749
2750/// Cubic interpolants through the swept loops, with `params(p)` giving each
2751/// point's parameters on the two surfaces.
2752fn fit_ruling_loops(
2753    loops: &[Vec<Point3>],
2754    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
2755) -> Vec<IntersectionCurve> {
2756    let mut curves = Vec::new();
2757    for pts in loops {
2758        if pts.len() < 4 {
2759            continue;
2760        }
2761        let ipts: Vec<IntersectionPoint> = pts
2762            .iter()
2763            .map(|&p| {
2764                let (param1, param2) = params(p);
2765                IntersectionPoint {
2766                    point: p,
2767                    param1,
2768                    param2,
2769                }
2770            })
2771            .collect();
2772        let degree = 3.min(pts.len() - 1);
2773        if let Ok(curve) = interpolate(pts, degree) {
2774            curves.push(IntersectionCurve {
2775                curve,
2776                points: ipts,
2777            });
2778        }
2779    }
2780    curves
2781}
2782
2783/// Algebraic cone-cylinder intersection for PARALLEL (or antiparallel) axes.
2784///
2785/// When the axes are parallel, every plane perpendicular to them cuts the cone
2786/// in a circle of radius `rho = v * cos(half_angle)` about a FIXED centre and
2787/// the cylinder in a circle of radius `R` about a second FIXED centre, so the
2788/// axis separation `d` is constant in `v`. Two coplanar circles meet at
2789/// `u = phi0 +/- acos((d^2 + rho^2 - R^2) / (2*d*rho))`, giving two branches
2790/// parameterised exactly by the cone's own `v`. The branches exist only where
2791/// `rho` lies in `[|d - R|, d + R]`, which bounds the curve naturally.
2792///
2793/// This replaces the general grid-seeded marcher for the configuration, which
2794/// mis-handles it badly: seeds are accepted anywhere within half the surface
2795/// diagonal of the partner, the march-result dedup only consumes seeds the
2796/// traced polyline passes near, and the survivors are dozens of overlapping
2797/// partial traces of the same curve. Those fragments carry no usable in-face
2798/// span, so a cone corner-round crossed by a boss cylinder never splits (a
2799/// counterbore/countersink meeting a pad — the gridfinity lightweight base).
2800///
2801/// Returns `None` (defer to the caller's other paths) when the axes are not
2802/// parallel, or when they are coaxial — a coaxial pair degenerates to shared
2803/// circles, which [`exact_cone_cylinder`] emits exactly and phase FF calls
2804/// directly. Note that `intersect_analytic_analytic_bounded` does NOT consult
2805/// `exact_cone_cylinder`, so a coaxial pair reaching this path through that
2806/// caller falls through to the marcher; only the FF path gets the exact circles.
2807// Result-wrapped to match the other `try_algebraic_intersection` arms' shape.
2808#[allow(clippy::unnecessary_wraps)]
2809fn algebraic_parallel_cone_cylinder(
2810    cone: &ConicalSurface,
2811    cyl: &CylindricalSurface,
2812    v_range_cone: Option<(f64, f64)>,
2813    v_range_cyl: Option<(f64, f64)>,
2814) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2815    let axis = cone.axis();
2816    if axis.dot(cyl.axis()).abs() < 1.0 - 1e-10 {
2817        return Ok(None); // Skew or oblique: `ruling_cone_cylinder` traces it.
2818    }
2819
2820    let apex = cone.apex();
2821    let delta = cyl.origin() - apex;
2822    let along = delta.dot(axis);
2823    let perp = delta - axis * along;
2824    let d = perp.length();
2825    if d < 1e-9 {
2826        return Ok(None); // Coaxial — `exact_cone_cylinder` owns this.
2827    }
2828
2829    let (e1, e2) = (cone.x_axis(), cone.y_axis());
2830    let phi0 = perp.dot(e2).atan2(perp.dot(e1));
2831
2832    let (sin_t, cos_t) = cone.half_angle().sin_cos();
2833    if cos_t < 1e-12 || sin_t < 1e-12 {
2834        return Ok(None);
2835    }
2836    let r = cyl.radius();
2837
2838    // Branch existence: |d - R| <= rho <= d + R, with rho = v * cos(half_angle).
2839    let mut v_min = (d - r).abs() / cos_t;
2840    let mut v_max = (d + r) / cos_t;
2841    if v_max <= v_min {
2842        return Ok(Some(vec![]));
2843    }
2844
2845    // Narrow the sampled span to the faces' own extents so the fixed sample
2846    // budget resolves the in-face part of the curve rather than spreading over
2847    // a loop that mostly lies off both patches. A face's crossing can be a
2848    // fraction of a degree of the cone's sweep (the corner-round case above),
2849    // and an unnarrowed sampling puts fewer than one sample across it.
2850    let mut lo = v_min;
2851    let mut hi = v_max;
2852    // Clip EXACTLY to the hints, not to a padded window: an endpoint that lands
2853    // exactly on the face's own v-limit lies ON that boundary rim, so the
2854    // downstream pave machinery anchors it to the rim edge instead of leaving
2855    // the section dangling just past the face.
2856    if let Some((a, b)) = v_range_cone {
2857        let (a, b) = if a <= b { (a, b) } else { (b, a) };
2858        lo = lo.max(a);
2859        hi = hi.min(b);
2860    }
2861    if let Some((a, b)) = v_range_cyl {
2862        // The cylinder's v is a signed distance along its axis from its origin;
2863        // convert both ends to the cone's v via the shared axial direction.
2864        let flip = cyl.axis().dot(axis);
2865        let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
2866        let (a, b) = (to_cone_v(a), to_cone_v(b));
2867        let (a, b) = if a <= b { (a, b) } else { (b, a) };
2868        lo = lo.max(a);
2869        hi = hi.min(b);
2870    }
2871    v_min = lo.max(v_min);
2872    v_max = hi.min(v_max);
2873    if v_max - v_min <= 1e-12 {
2874        return Ok(Some(vec![]));
2875    }
2876
2877    let n_samples = 128;
2878    let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
2879    let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
2880    #[allow(clippy::cast_precision_loss)]
2881    for i in 0..=n_samples {
2882        let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
2883        let rho = v * cos_t;
2884        if rho < 1e-12 {
2885            // The apex. `cos_alpha` has rho in its denominator, so it is only
2886            // meaningful in the limit: it tends to 0 (alpha -> pi/2) when the
2887            // cylinder passes exactly through the apex (d == R), and diverges
2888            // otherwise — where the clamp would manufacture a spurious alpha of
2889            // 0 or pi. So keep the apex only in the d == R case, where it is a
2890            // genuine point of the intersection and the shared endpoint at
2891            // which the two branches meet.
2892            if (d - r).abs() < 1e-12 {
2893                let apex = cone.evaluate(phi0, v);
2894                plus.push(apex);
2895                minus.push(apex);
2896            }
2897            continue;
2898        }
2899        let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
2900        let alpha = cos_alpha.acos();
2901        plus.push(cone.evaluate(phi0 + alpha, v));
2902        minus.push(cone.evaluate(phi0 - alpha, v));
2903    }
2904
2905    let mut curves = Vec::new();
2906    for pts in [&plus, &minus] {
2907        // Fewer than four samples in range means this branch does not cross the
2908        // bounded region at all (the other branch may still).
2909        if pts.len() < 4 {
2910            continue;
2911        }
2912        let ipts: Vec<IntersectionPoint> = pts
2913            .iter()
2914            .map(|&p| IntersectionPoint {
2915                point: p,
2916                param1: cone.project_point(p),
2917                param2: cyl.project_point(p),
2918            })
2919            .collect();
2920        let degree = 3.min(pts.len() - 1);
2921        match interpolate(pts, degree) {
2922            Ok(curve) => curves.push(IntersectionCurve {
2923                curve,
2924                points: ipts,
2925            }),
2926            // Emitting only the branch that happened to fit would starve the
2927            // section chain of exactly the piece this path exists to supply —
2928            // the same silent half-answer the marcher's fragments produced.
2929            // Defer the whole pair to the caller's other paths instead.
2930            Err(_) => return Ok(None),
2931        }
2932    }
2933
2934    Ok(Some(curves))
2935}
2936
2937/// Algebraic sphere-sphere intersection.
2938///
2939/// Two spheres intersect in a circle lying in the radical plane.
2940/// The radical plane is perpendicular to the line connecting the centers,
2941/// at a distance d1 from center1 where:
2942///   d1 = (D² + R1² - R2²) / (2D)
2943/// and D is the distance between centers.
2944fn algebraic_sphere_sphere(
2945    s1: &SphericalSurface,
2946    s2: &SphericalSurface,
2947) -> Result<Vec<IntersectionCurve>, MathError> {
2948    let c1 = s1.center();
2949    let c2 = s2.center();
2950    let r1 = s1.radius();
2951    let r2 = s2.radius();
2952
2953    let delta = c2 - c1;
2954    let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
2955    let d = d_sq.sqrt();
2956
2957    if d < 1e-12 {
2958        // Concentric spheres: no intersection (unless same radius → degenerate).
2959        return Ok(vec![]);
2960    }
2961
2962    // Check separation conditions.
2963    if d > r1 + r2 + 1e-10 {
2964        return Ok(vec![]); // Too far apart
2965    }
2966    if d + r2.min(r1) + 1e-10 < r1.max(r2) {
2967        return Ok(vec![]); // One inside the other
2968    }
2969
2970    // Distance from c1 to the radical plane along the center line.
2971    let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
2972
2973    // Radius of the intersection circle.
2974    let r_circle_sq = r1 * r1 - d1 * d1;
2975    if r_circle_sq < 0.0 {
2976        // Tangent or no intersection (numerical noise).
2977        if r_circle_sq > -1e-10 {
2978            // Tangent: single point.
2979            let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
2980            let tangent_pt = Point3::new(
2981                c1.x() + axis.x() * d1,
2982                c1.y() + axis.y() * d1,
2983                c1.z() + axis.z() * d1,
2984            );
2985            let ipt = IntersectionPoint {
2986                point: tangent_pt,
2987                param1: (0.0, 0.0),
2988                param2: (0.0, 0.0),
2989            };
2990            // Single-point "curve" — not very useful but correct.
2991            return Ok(vec![IntersectionCurve {
2992                curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
2993                points: vec![ipt],
2994            }]);
2995        }
2996        return Ok(vec![]);
2997    }
2998
2999    let r_circle = r_circle_sq.sqrt();
3000    let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
3001    let center = Point3::new(
3002        c1.x() + axis.x() * d1,
3003        c1.y() + axis.y() * d1,
3004        c1.z() + axis.z() * d1,
3005    );
3006
3007    // Build a reference frame for the circle.
3008    let basis = Frame3::from_normal(center, axis)?;
3009    let u_dir = basis.x;
3010    let v_dir = basis.y;
3011
3012    // Sample the circle for the IntersectionCurve representation.
3013    let n_samples = 33; // Odd for symmetry
3014    let mut points = Vec::with_capacity(n_samples);
3015    let mut positions = Vec::with_capacity(n_samples);
3016    #[allow(clippy::cast_precision_loss)]
3017    for i in 0..n_samples {
3018        let theta = TAU * i as f64 / (n_samples - 1) as f64;
3019        let (sin_t, cos_t) = theta.sin_cos();
3020        let pt = Point3::new(
3021            center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
3022            center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
3023            center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
3024        );
3025        positions.push(pt);
3026        points.push(IntersectionPoint {
3027            point: pt,
3028            param1: (0.0, 0.0),
3029            param2: (0.0, 0.0),
3030        });
3031    }
3032
3033    let degree = 3.min(positions.len() - 1);
3034    let curve = interpolate(&positions, degree)?;
3035
3036    Ok(vec![IntersectionCurve { curve, points }])
3037}
3038
3039/// Newton correction: project a point back onto the intersection curve
3040/// of two analytic surfaces. Solves the 3×3 system:
3041///   δ · na = -da  (eliminate distance to surface A)
3042///   δ · nb = -db  (eliminate distance to surface B)
3043///   δ · t  = 0    (minimal correction, perpendicular to tangent)
3044#[allow(clippy::too_many_arguments)]
3045fn correct_to_intersection(
3046    a: &AnalyticSurface<'_>,
3047    b: &AnalyticSurface<'_>,
3048    surf_a: &dyn Fn(f64, f64) -> Point3,
3049    norm_a: &dyn Fn(f64, f64) -> Vec3,
3050    surf_b: &dyn Fn(f64, f64) -> Point3,
3051    norm_b: &dyn Fn(f64, f64) -> Vec3,
3052    point: Point3,
3053    u_range_a: (f64, f64),
3054    v_range_a: (f64, f64),
3055    u_range_b: (f64, f64),
3056    v_range_b: (f64, f64),
3057    max_iters: usize,
3058) -> Point3 {
3059    let mut p = point;
3060    for _ in 0..max_iters {
3061        let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
3062        let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
3063        let pa = surf_a(ua, va);
3064        let pb = surf_b(ub, vb);
3065        let na = norm_a(ua, va);
3066        let nb = norm_b(ub, vb);
3067        let pv = Vec3::new(p.x(), p.y(), p.z());
3068
3069        let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
3070        let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
3071
3072        if da.abs() < 1e-7 && db.abs() < 1e-7 {
3073            break;
3074        }
3075
3076        let t = na.cross(nb);
3077        let t_len = t.length();
3078        if t_len < 1e-10 {
3079            // Surfaces are tangent — fall back to midpoint.
3080            return Point3::new(
3081                (pa.x() + pb.x()) * 0.5,
3082                (pa.y() + pb.y()) * 0.5,
3083                (pa.z() + pb.z()) * 0.5,
3084            );
3085        }
3086        let t_hat = t * (1.0 / t_len);
3087
3088        // Solve [na; nb; t_hat] · δ = [-da, -db, 0] via Cramer's rule.
3089        let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
3090            - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
3091            + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
3092        if det.abs() < 1e-15 {
3093            return Point3::new(
3094                (pa.x() + pb.x()) * 0.5,
3095                (pa.y() + pb.y()) * 0.5,
3096                (pa.z() + pb.z()) * 0.5,
3097            );
3098        }
3099        let inv = 1.0 / det;
3100        // Cramer's rule: replace each column of A with rhs = (-da, -db, 0).
3101        let dx = inv
3102            * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
3103                + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
3104        let dy = inv
3105            * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
3106                - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
3107        let dz = inv
3108            * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
3109                + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
3110        let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
3111
3112        // Divergence guard: if the correction moves farther from both
3113        // surfaces, abandon Newton and return the best point so far.
3114        let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
3115        let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
3116        let pc_a = surf_a(uc, vc);
3117        let pc_b = surf_b(ud, vd);
3118        let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
3119        let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
3120            .dot(norm_a(uc, vc))
3121            .abs();
3122        let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
3123            .dot(norm_b(ud, vd))
3124            .abs();
3125        if da_new > da.abs() && db_new > db.abs() {
3126            return p;
3127        }
3128
3129        p = candidate;
3130    }
3131    p
3132}
3133
3134/// March along the intersection of two surfaces from a seed point.
3135///
3136/// Uses the cross product of surface normals as the tangent direction
3137/// and projects back onto both surfaces using analytical projection
3138/// (for cylinders/spheres) or grid search (fallback).
3139#[allow(clippy::too_many_arguments)]
3140fn march_analytic_intersection(
3141    a: &AnalyticSurface<'_>,
3142    b: &AnalyticSurface<'_>,
3143    surf_a: &dyn Fn(f64, f64) -> Point3,
3144    norm_a: &dyn Fn(f64, f64) -> Vec3,
3145    surf_b: &dyn Fn(f64, f64) -> Point3,
3146    norm_b: &dyn Fn(f64, f64) -> Vec3,
3147    seed: Point3,
3148    u_range_a: (f64, f64),
3149    v_range_a: (f64, f64),
3150    u_range_b: (f64, f64),
3151    v_range_b: (f64, f64),
3152    initial_step: f64,
3153    u_periodic_a: bool,
3154    u_periodic_b: bool,
3155) -> Vec<Point3> {
3156    let max_steps = 500;
3157    let h_min = 1e-6;
3158    let h_max = initial_step * 4.0;
3159    // Fixed closure threshold: the adaptive step `h` varies with curvature
3160    // and can shrink below the actual miss distance at the seed re-approach.
3161    // Use `initial_step * 5` to robustly detect closure on the first pass.
3162    let closure_dist = initial_step * 5.0;
3163    // Angular thresholds for curvature-adaptive stepping.
3164    let max_angle = 10.0_f64.to_radians();
3165    let min_angle = 2.0_f64.to_radians();
3166
3167    // March forward from seed, collecting points.
3168    let mut forward = Vec::new();
3169    // March backward from seed, collecting points (reversed at end).
3170    let mut backward = Vec::new();
3171
3172    for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
3173        let mut current = seed;
3174        let mut h = initial_step;
3175        let mut prev_tangent: Option<Vec3> = None;
3176
3177        for _ in 0..max_steps {
3178            let (ua, va) = project_analytic(a, current, u_range_a, v_range_a);
3179            let (ub, vb) = project_analytic(b, current, u_range_b, v_range_b);
3180
3181            let na = norm_a(ua, va);
3182            let nb = norm_b(ub, vb);
3183
3184            let tangent = na.cross(nb);
3185            let t_len = tangent.length();
3186            if t_len < 1e-10 {
3187                break;
3188            }
3189            let t_dir = tangent * (direction / t_len);
3190
3191            // Curvature-adaptive step: check angular deviation from previous tangent.
3192            if let Some(prev_t) = prev_tangent {
3193                let cos_angle = prev_t.dot(t_dir).clamp(-1.0, 1.0);
3194                let angle = cos_angle.acos();
3195                if angle > max_angle && h > h_min {
3196                    h = (h * 0.5).max(h_min);
3197                } else if angle < min_angle {
3198                    h = (h * 2.0).min(h_max);
3199                }
3200            }
3201            prev_tangent = Some(t_dir);
3202
3203            let next = Point3::new(
3204                h.mul_add(t_dir.x(), current.x()),
3205                h.mul_add(t_dir.y(), current.y()),
3206                h.mul_add(t_dir.z(), current.z()),
3207            );
3208
3209            let (ua2, va2) = project_analytic(a, next, u_range_a, v_range_a);
3210            let (ub2, vb2) = project_analytic(b, next, u_range_b, v_range_b);
3211
3212            let pa = surf_a(ua2, va2);
3213            let pb = surf_b(ub2, vb2);
3214            let mid = Point3::new(
3215                (pa.x() + pb.x()) * 0.5,
3216                (pa.y() + pb.y()) * 0.5,
3217                (pa.z() + pb.z()) * 0.5,
3218            );
3219            let out_a = (!u_periodic_a && (ua2 <= u_range_a.0 || ua2 >= u_range_a.1))
3220                || va2 <= v_range_a.0
3221                || va2 >= v_range_a.1;
3222            let out_b = (!u_periodic_b && (ub2 <= u_range_b.0 || ub2 >= u_range_b.1))
3223                || vb2 <= v_range_b.0
3224                || vb2 >= v_range_b.1;
3225
3226            if out_a || out_b {
3227                break;
3228            }
3229
3230            // Check for loop closure — if we've collected enough points and
3231            // the current point is close to the seed, the curve is closed.
3232            // Require ≥10 steps to avoid premature closure near the seed.
3233            let dist_to_seed = (mid - seed).length();
3234            if points.len() > 10 && dist_to_seed < closure_dist {
3235                points.push(seed);
3236                break;
3237            }
3238
3239            points.push(mid);
3240            current = mid;
3241        }
3242    }
3243
3244    // Assemble result: backward (reversed) + seed + forward
3245    backward.reverse();
3246    let mut result = backward;
3247    result.push(seed);
3248    result.append(&mut forward);
3249
3250    // Refine all points onto the intersection curve via Newton correction.
3251    for pt in &mut result {
3252        *pt = correct_to_intersection(
3253            a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b, v_range_b,
3254            5,
3255        );
3256    }
3257
3258    result
3259}
3260
3261/// Project a 3D point onto an analytic surface using the surface's
3262/// analytical projection method. Falls back to grid search for surface
3263/// types without analytical projection.
3264fn project_analytic(
3265    surface: &AnalyticSurface<'_>,
3266    point: Point3,
3267    u_range: (f64, f64),
3268    v_range: (f64, f64),
3269) -> (f64, f64) {
3270    match surface {
3271        AnalyticSurface::Cylinder(cyl) => {
3272            let (u, v) = cyl.project_point(point);
3273            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
3274        }
3275        AnalyticSurface::Sphere(sphere) => {
3276            let (u, v) = sphere.project_point(point);
3277            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
3278        }
3279        AnalyticSurface::Cone(cone) => {
3280            let (u, v) = cone.project_point(point);
3281            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
3282        }
3283        AnalyticSurface::Torus(torus) => {
3284            let (u, v) = torus.project_point(point);
3285            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
3286        }
3287    }
3288}
3289
3290/// Returns `true` if the surface's u-parameter is periodic (wraps around 2π).
3291/// All current `AnalyticSurface` variants have periodic u — this is trivially
3292/// true today but exists as a guard for future non-periodic analytic types.
3293fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
3294    matches!(
3295        surface,
3296        AnalyticSurface::Cylinder(_)
3297            | AnalyticSurface::Cone(_)
3298            | AnalyticSurface::Sphere(_)
3299            | AnalyticSurface::Torus(_)
3300    )
3301}
3302
3303/// Extract closures and parameter ranges for an analytic surface.
3304#[allow(clippy::type_complexity)]
3305fn surface_closures<'a>(
3306    surface: &'a AnalyticSurface<'a>,
3307) -> (
3308    Box<dyn Fn(f64, f64) -> Point3 + 'a>,
3309    Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
3310    (f64, f64),
3311    (f64, f64),
3312) {
3313    match surface {
3314        AnalyticSurface::Cylinder(cyl) => (
3315            Box::new(|u, v| cyl.evaluate(u, v)),
3316            Box::new(|u, v| cyl.normal(u, v)),
3317            (0.0, TAU),
3318            (-1.0, 1.0),
3319        ),
3320        AnalyticSurface::Cone(cone) => (
3321            Box::new(|u, v| cone.evaluate(u, v)),
3322            Box::new(|u, v| cone.normal(u, v)),
3323            (0.0, TAU),
3324            (0.01, 2.0),
3325        ),
3326        AnalyticSurface::Sphere(sphere) => (
3327            Box::new(|u, v| sphere.evaluate(u, v)),
3328            Box::new(|u, v| sphere.normal(u, v)),
3329            (0.0, TAU),
3330            (-FRAC_PI_2, FRAC_PI_2),
3331        ),
3332        AnalyticSurface::Torus(torus) => (
3333            Box::new(|u, v| torus.evaluate(u, v)),
3334            Box::new(|u, v| torus.normal(u, v)),
3335            (0.0, TAU),
3336            (0.0, TAU),
3337        ),
3338    }
3339}
3340
3341#[cfg(test)]
3342#[allow(clippy::unwrap_used, clippy::expect_used)]
3343mod tests {
3344    use super::*;
3345    use crate::tolerance::Tolerance;
3346
3347    /// Arcs of a cone's hyperbola (a plane parallel to the axis) and parabola
3348    /// (a plane parallel to a ruling) between two of their sampled points
3349    /// stay on both the plane and the cone everywhere, not just at samples.
3350    #[test]
3351    fn plane_cone_conic_arcs_lie_on_both_surfaces() {
3352        let half_angle = 1.1_f64;
3353        let cone = ConicalSurface::new(
3354            Point3::new(0.0, 0.0, 0.0),
3355            Vec3::new(0.0, 0.0, 1.0),
3356            half_angle,
3357        )
3358        .unwrap();
3359        let ruling = Vec3::new(half_angle.sin(), 0.0, half_angle.cos());
3360        for (normal, d) in [(Vec3::new(1.0, 0.0, 0.0), 0.5), (ruling, 1.0)] {
3361            let chains =
3362                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, d, 10.0)
3363                    .unwrap();
3364            let chain = chains
3365                .iter()
3366                .find_map(|c| match c {
3367                    ExactIntersectionCurve::Points(chain) => Some(chain),
3368                    _ => None,
3369                })
3370                .expect("a parabola or hyperbola section is sampled");
3371            let (from, to) = (chain[2], chain[chain.len() - 3]);
3372            let arc = plane_cone_conic_arc(&cone, normal, d, from, to)
3373                .unwrap()
3374                .expect("an exact arc");
3375            let (t0, t1) = arc.domain();
3376            assert!((arc.evaluate(t0) - from).length() < 1e-12);
3377            assert!((arc.evaluate(t1) - to).length() < 1e-12);
3378            for i in 0..=200 {
3379                let q = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0);
3380                let w = q - Point3::new(0.0, 0.0, 0.0);
3381                let off_plane = (normal.dot(w) - d).abs();
3382                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
3383                assert!(off_plane < 1e-9, "off the plane by {off_plane}");
3384                assert!(off_cone < 1e-9, "off the cone by {off_cone}");
3385            }
3386        }
3387    }
3388
3389    /// A plane a few 1e-10 short of parallel to a ruling cuts a vast ellipse
3390    /// that the parabola's closed form only approximates: the arc is either
3391    /// declined or on the cone, and an arc with coincident ends is declined.
3392    #[test]
3393    fn plane_cone_conic_arc_declines_a_near_parabolic_ellipse() {
3394        let half_angle = 1.1_f64;
3395        let cone = ConicalSurface::new(
3396            Point3::new(0.0, 0.0, 0.0),
3397            Vec3::new(0.0, 0.0, 1.0),
3398            half_angle,
3399        )
3400        .unwrap();
3401        for shortfall in [1e-10, 3e-10, 8e-10] {
3402            let tilt = half_angle - shortfall / (2.0 * half_angle).sin();
3403            let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
3404            let chains =
3405                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, 1.0, 10.0)
3406                    .unwrap();
3407            let Some(chain) = chains.iter().find_map(|c| match c {
3408                ExactIntersectionCurve::Points(chain) => Some(chain),
3409                _ => None,
3410            }) else {
3411                continue;
3412            };
3413            let (from, to) = (chain[2], chain[chain.len() - 3]);
3414            assert!(
3415                plane_cone_conic_arc(&cone, normal, 1.0, from, from)
3416                    .unwrap()
3417                    .is_none(),
3418                "coincident ends"
3419            );
3420            let Some(arc) = plane_cone_conic_arc(&cone, normal, 1.0, from, to).unwrap() else {
3421                continue;
3422            };
3423            let (t0, t1) = arc.domain();
3424            for i in 0..=200 {
3425                let w = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0)
3426                    - Point3::new(0.0, 0.0, 0.0);
3427                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
3428                assert!(off_cone < 1e-8, "{shortfall}: off the cone by {off_cone}");
3429            }
3430        }
3431    }
3432
3433    #[test]
3434    fn plane_cylinder_perpendicular() {
3435        let cyl =
3436            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
3437                .unwrap();
3438
3439        // Horizontal plane at z=3 -- produces a circle at height 3.
3440        let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
3441        assert!(!curves.is_empty(), "should find intersection curve");
3442        assert!(
3443            curves[0].points.len() > 10,
3444            "should have many sample points"
3445        );
3446
3447        let tol = Tolerance::loose();
3448        for pt in &curves[0].points {
3449            assert!(
3450                tol.approx_eq(pt.point.z(), 3.0),
3451                "z should be ~3.0, got {}",
3452                pt.point.z()
3453            );
3454            let r = pt.point.x().hypot(pt.point.y());
3455            assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
3456        }
3457    }
3458
3459    #[test]
3460    fn plane_sphere_equator() {
3461        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
3462
3463        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
3464        assert!(!curves.is_empty());
3465
3466        let tol = Tolerance::loose();
3467        for pt in &curves[0].points {
3468            assert!(
3469                tol.approx_eq(pt.point.z(), 0.0),
3470                "z should be ~0, got {}",
3471                pt.point.z()
3472            );
3473            let r = pt.point.x().hypot(pt.point.y());
3474            assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
3475        }
3476    }
3477
3478    #[test]
3479    fn plane_sphere_no_intersection() {
3480        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
3481
3482        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
3483        assert!(curves.is_empty());
3484    }
3485
3486    #[test]
3487    fn plane_cone_cross_section() {
3488        let cone = ConicalSurface::new(
3489            Point3::new(0.0, 0.0, 0.0),
3490            Vec3::new(0.0, 0.0, 1.0),
3491            std::f64::consts::FRAC_PI_4,
3492        )
3493        .unwrap();
3494
3495        let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
3496        assert!(!curves.is_empty(), "should find intersection with cone");
3497    }
3498
3499    /// The 1u gridfinity spacer lip fuse corner (#1570): the body's lip
3500    /// recess cone (45 deg, opening downward) meets the tool's lip cone
3501    /// (45 deg, opening upward) with axes offset 0.25mm in x and y. Equal
3502    /// half-angle tangents put the whole intersection on the radical plane,
3503    /// so the section is one exact ellipse; the marcher shredded this into
3504    /// ~64 closed micro-loops per pair.
3505    #[test]
3506    fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
3507        let c1 = ConicalSurface::new(
3508            Point3::new(
3509                -16.999_999_999_999_975,
3510                -16.999_999_999_999_975,
3511                5.849_999_999_999_951,
3512            ),
3513            Vec3::new(0.0, 0.0, -1.0),
3514            0.785_398_163_397_433_5,
3515        )
3516        .unwrap();
3517        let c2 = ConicalSurface::new(
3518            Point3::new(
3519                -16.750_000_000_000_036,
3520                -16.750_000_000_000_018,
3521                0.749_999_999_999_881,
3522            ),
3523            Vec3::new(0.0, 0.0, 1.0),
3524            0.785_398_163_397_467_6,
3525        )
3526        .unwrap();
3527
3528        let curves = exact_cone_cone(&c1, &c2)
3529            .unwrap()
3530            .expect("offset parallel equal-angle cones must take the radical-plane path");
3531        assert_eq!(curves.len(), 1, "expected exactly one section conic");
3532        assert!(
3533            matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
3534            "expected an ellipse section, got {:?}",
3535            curves[0]
3536        );
3537        let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
3538            return;
3539        };
3540
3541        // Every sample must lie on BOTH cones: distance to the axis equals
3542        // tan(half_angle) times the axial distance from the apex, on the
3543        // real nappe of each.
3544        for i in 0..16 {
3545            let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
3546            for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
3547                let rel = p - cone.apex();
3548                let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
3549                let axial = rel_v.dot(cone.axis());
3550                let radial = (rel_v - cone.axis() * axial).length();
3551                assert!(
3552                    axial > 0.0,
3553                    "{label}: sample on phantom nappe (axial {axial})"
3554                );
3555                let expect = cone.half_angle().tan() * axial;
3556                assert!(
3557                    (radial - expect).abs() < 1e-9,
3558                    "{label}: sample off surface by {}",
3559                    (radial - expect).abs()
3560                );
3561            }
3562        }
3563    }
3564
3565    /// Opposed cones whose real nappes occupy disjoint half-spaces share a
3566    /// radical-plane conic only on the phantom nappe — the exact path must
3567    /// report a definitive empty intersection, not defer to the marcher.
3568    #[test]
3569    fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
3570        let c1 = ConicalSurface::new(
3571            Point3::new(0.0, 0.0, 5.0),
3572            Vec3::new(0.0, 0.0, -1.0),
3573            std::f64::consts::FRAC_PI_4,
3574        )
3575        .unwrap();
3576        let c2 = ConicalSurface::new(
3577            Point3::new(0.25, 0.25, 20.0),
3578            Vec3::new(0.0, 0.0, 1.0),
3579            std::f64::consts::FRAC_PI_4,
3580        )
3581        .unwrap();
3582        let curves = exact_cone_cone(&c1, &c2)
3583            .unwrap()
3584            .expect("radical-plane path");
3585        assert!(curves.is_empty(), "disjoint nappes must yield no curves");
3586    }
3587
3588    /// Unequal half-angles keep a quadratic term in the pencil — no plane
3589    /// reduction exists, so the exact path must defer to the marcher.
3590    #[test]
3591    fn offset_parallel_cones_with_unequal_angles_defer() {
3592        let c1 = ConicalSurface::new(
3593            Point3::new(0.0, 0.0, 5.0),
3594            Vec3::new(0.0, 0.0, -1.0),
3595            std::f64::consts::FRAC_PI_4,
3596        )
3597        .unwrap();
3598        let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
3599            .unwrap();
3600        assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
3601    }
3602
3603    #[test]
3604    fn coaxial_cones_cross_at_single_circle() {
3605        // Two coaxial truncated cones (outer base r10->top r8, inner r9->r8
3606        // over height 10) cross where their radii match: z=10, r=8. The
3607        // intersection must be ONE clean circle, not the dozens of degenerate
3608        // micro-curves the general marcher produces at near-tangency.
3609        let outer = ConicalSurface::new(
3610            Point3::new(0.0, 0.0, 50.0),
3611            Vec3::new(0.0, 0.0, -1.0),
3612            5.0_f64.atan(),
3613        )
3614        .unwrap();
3615        let inner = ConicalSurface::new(
3616            Point3::new(0.0, 0.0, 90.0),
3617            Vec3::new(0.0, 0.0, -1.0),
3618            10.0_f64.atan(),
3619        )
3620        .unwrap();
3621
3622        let curves = intersect_analytic_analytic_bounded(
3623            AnalyticSurface::Cone(&outer),
3624            AnalyticSurface::Cone(&inner),
3625            32,
3626            None,
3627            None,
3628        )
3629        .unwrap();
3630
3631        assert_eq!(
3632            curves.len(),
3633            1,
3634            "coaxial cones crossing at one circle must yield exactly one curve, got {}",
3635            curves.len()
3636        );
3637        for p in &curves[0].points {
3638            let r = p.point.x().hypot(p.point.y());
3639            assert!(
3640                (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
3641                "intersection point off the expected z=10,r=8 circle: {:?}",
3642                p.point
3643            );
3644        }
3645    }
3646
3647    #[test]
3648    fn plane_torus_cross_section() {
3649        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
3650
3651        let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
3652        assert!(
3653            !curves.is_empty(),
3654            "should find intersection curves with torus"
3655        );
3656    }
3657
3658    /// Signed distance of a point to a z-axis torus centred at the origin:
3659    /// `sqrt((sqrt(x^2+y^2) - R)^2 + z^2) - r`.
3660    fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
3661        let rho = p.x().hypot(p.y());
3662        ((rho - major).hypot(p.z())) - minor
3663    }
3664
3665    /// The gridfinity lightweight base's failing corner, reduced: a cavity
3666    /// corner-round cone (apex below the floor, 45 deg, axis +z) crossed by a
3667    /// parallel-axis boss cylinder. The general marcher returned ~49 overlapping
3668    /// partial traces of one curve here; the algebraic path must return exactly
3669    /// the two branches, each ON both surfaces and inside the cone's v-hint.
3670    #[test]
3671    fn oblique_cone_cylinder_traces_curves_on_both() {
3672        use crate::traits::ParametricCurve;
3673        // A pointed cone opening down from (0, 0, 3), radius half the depth,
3674        // and a rod along y through (x0, ., 1): one loop through the wall
3675        // when the rod pokes out, two when every ruling meets the cone.
3676        let cone = ConicalSurface::new(
3677            Point3::new(0.0, 0.0, 3.0),
3678            Vec3::new(0.0, 0.0, -1.0),
3679            2.0_f64.atan(),
3680        )
3681        .unwrap();
3682        for (x0, loops) in [(0.5, 1), (0.0, 2)] {
3683            let cyl =
3684                CylindricalSurface::new(Point3::new(x0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
3685                    .unwrap();
3686            for cone_first in [true, false] {
3687                let (a, b) = if cone_first {
3688                    (
3689                        AnalyticSurface::Cone(&cone),
3690                        AnalyticSurface::Cylinder(&cyl),
3691                    )
3692                } else {
3693                    (
3694                        AnalyticSurface::Cylinder(&cyl),
3695                        AnalyticSurface::Cone(&cone),
3696                    )
3697                };
3698                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
3699                assert_eq!(curves.len(), loops, "x0 {x0}: loops");
3700                for c in &curves {
3701                    let (t0, t1) = c.curve.domain();
3702                    for k in 0..=64 {
3703                        let t = (t1 - t0).mul_add(f64::from(k) / 64.0, t0);
3704                        let p = ParametricCurve::evaluate(&c.curve, t);
3705                        // A cubic through the ruling samples, bent most at the
3706                        // loop's branch points.
3707                        let rod = (p.x() - x0).hypot(p.z() - 1.0);
3708                        assert!(
3709                            (rod - 0.6).abs() < 1e-4,
3710                            "x0 {x0}: off the rod by {}",
3711                            rod - 0.6
3712                        );
3713                        let cone_r = p.x().hypot(p.y());
3714                        assert!(
3715                            (cone_r - 0.5 * (3.0 - p.z())).abs() < 1e-4,
3716                            "x0 {x0}: off the cone at {p:?}"
3717                        );
3718                    }
3719                }
3720            }
3721        }
3722    }
3723
3724    #[test]
3725    fn a_rod_through_a_rings_tube_traces_four_loops() {
3726        use crate::traits::ParametricCurve;
3727        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
3728        // Along y through (0.5, ., 0.3): every ruling enters and leaves the
3729        // tube on either side of the hole, four roots, four loops.
3730        let rod =
3731            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.3), Vec3::new(0.0, 1.0, 0.0), 0.6)
3732                .unwrap();
3733        let curves = ruling_torus_cylinder(&ring, &rod, true).unwrap();
3734        assert_eq!(curves.len(), 4);
3735        for c in &curves {
3736            let (t0, t1) = c.curve.domain();
3737            for k in 0..=64 {
3738                let p =
3739                    ParametricCurve::evaluate(&c.curve, (t1 - t0).mul_add(f64::from(k) / 64.0, t0));
3740                let on_rod = (p.x() - 0.5).hypot(p.z() - 0.3) - 0.6;
3741                let on_ring = (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
3742                assert!(
3743                    on_rod.abs() < 1e-4 && on_ring.abs() < 1e-4,
3744                    "off by {on_rod}, {on_ring}"
3745                );
3746            }
3747        }
3748        // Higher, the rod's top rulings pass over the tube: the count varies.
3749        let high =
3750            CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
3751                .unwrap();
3752        assert!(ruling_torus_cylinder(&ring, &high, true).is_none());
3753        // Its top clears the tube only between two sampled rulings.
3754        let grazing =
3755            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.9001), Vec3::new(0.0, 1.0, 0.0), 0.6)
3756                .unwrap();
3757        assert!(ruling_torus_cylinder(&ring, &grazing, true).is_none());
3758        // A spindle torus's quartic also holds its inner lemon.
3759        let spindle = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap();
3760        let thin =
3761            CylindricalSurface::new(Point3::new(0.3, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 0.2)
3762                .unwrap();
3763        assert!(ruling_torus_cylinder(&spindle, &thin, true).is_none());
3764    }
3765
3766    #[test]
3767    fn oblique_cone_cylinder_defers_where_rulings_cannot_trace_it() {
3768        let t = 2.0_f64.atan();
3769        let cone =
3770            ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 0.0, -1.0), t).unwrap();
3771        // A rod through the apex meets the far nappe.
3772        let through_apex =
3773            CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
3774                .unwrap();
3775        assert!(ruling_cone_cylinder(&cone, &through_apex, true).is_none());
3776        // A rod along a generator meets each ruling once.
3777        let generator = Vec3::new(t.cos(), 0.0, -t.sin());
3778        let along = CylindricalSurface::new(Point3::new(0.0, 0.3, 0.0), generator, 0.2).unwrap();
3779        assert!(ruling_cone_cylinder(&cone, &along, true).is_none());
3780        // A pin's tip just through a tube's wall: the tube's rulings that
3781        // meet it span a window narrower than the sampling.
3782        let pin =
3783            ConicalSurface::new(Point3::new(20.5, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), t).unwrap();
3784        let tube =
3785            CylindricalSurface::new(Point3::new(0.0, 0.0, -10.0), Vec3::new(0.0, 0.0, 1.0), 20.0)
3786                .unwrap();
3787        assert!(ruling_cone_cylinder(&pin, &tube, true).is_none());
3788    }
3789
3790    #[test]
3791    fn parallel_cone_cylinder_gives_two_exact_branches() {
3792        use crate::traits::ParametricCurve;
3793        let cone = ConicalSurface::new(
3794            Point3::new(-5.45, -36.55, -4.85),
3795            Vec3::new(0.0, 0.0, 1.0),
3796            std::f64::consts::FRAC_PI_4,
3797        )
3798        .unwrap();
3799        let cyl = CylindricalSurface::new(
3800            Point3::new(-8.0, -34.0, -5.0),
3801            Vec3::new(0.0, 0.0, 1.0),
3802            4.45,
3803        )
3804        .unwrap();
3805        // The cone face spans z in [-3.8, -3.0]; v = (z - apex_z) / sin(45 deg).
3806        let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
3807        let curves = intersect_analytic_analytic_bounded(
3808            AnalyticSurface::Cone(&cone),
3809            AnalyticSurface::Cylinder(&cyl),
3810            32,
3811            Some(v_hint),
3812            Some((0.0, 2.5)),
3813        )
3814        .unwrap();
3815
3816        assert_eq!(curves.len(), 2, "expected exactly the two branches");
3817        for c in &curves {
3818            let (t0, t1) = c.curve.domain();
3819            for k in 0..=32 {
3820                let t = (t1 - t0).mul_add(f64::from(k) / 32.0, t0);
3821                let p = ParametricCurve::evaluate(&c.curve, t);
3822                // On the cylinder: radial distance from its axis is the radius.
3823                let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
3824                assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
3825                // On the cone: radial distance from its axis is z - apex_z.
3826                let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
3827                assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
3828                // Inside the cone face's own v-window (the hint is respected).
3829                assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
3830            }
3831        }
3832    }
3833
3834    /// A coaxial pair has no radical line; the algebraic path must defer rather
3835    /// than divide by a zero axis separation.
3836    #[test]
3837    fn coaxial_cone_cylinder_defers_to_other_paths() {
3838        let cone = ConicalSurface::new(
3839            Point3::new(0.0, 0.0, 0.0),
3840            Vec3::new(0.0, 0.0, 1.0),
3841            std::f64::consts::FRAC_PI_4,
3842        )
3843        .unwrap();
3844        let cyl =
3845            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
3846                .unwrap();
3847        assert!(
3848            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
3849                .unwrap()
3850                .is_none()
3851        );
3852    }
3853
3854    #[test]
3855    fn oblique_cone_cylinder_defers_to_other_paths() {
3856        let cone = ConicalSurface::new(
3857            Point3::new(0.0, 0.0, 0.0),
3858            Vec3::new(0.0, 0.0, 1.0),
3859            std::f64::consts::FRAC_PI_4,
3860        )
3861        .unwrap();
3862        let cyl =
3863            CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
3864                .unwrap();
3865        assert!(
3866            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
3867                .unwrap()
3868                .is_none()
3869        );
3870    }
3871
3872    #[test]
3873    fn plane_torus_lobe_closes_and_stays_on_surface() {
3874        use crate::traits::ParametricCurve;
3875        let (major, minor) = (10.0, 3.0);
3876        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
3877
3878        // The census cutting planes (y=-4, x=6) each cut the +x and -x tube lobes
3879        // in a CLOSED oval. The greedy marcher stops one grid step short of
3880        // closing; the wrap-close must make every fitted lobe close exactly.
3881        for (n, d) in [
3882            (Vec3::new(0.0, -1.0, 0.0), 4.0),  // y = -4
3883            (Vec3::new(-1.0, 0.0, 0.0), -6.0), // x = 6
3884            (Vec3::new(0.0, 0.0, 1.0), 0.0),   // z = 0 -> two concentric circles
3885        ] {
3886            let curves = intersect_plane_torus(&torus, n, d).unwrap();
3887            assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
3888            for c in &curves {
3889                let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
3890                let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
3891                assert!(
3892                    (p0 - p1).length() < 1e-7,
3893                    "lobe not closed: gap={} (n={n:?} d={d})",
3894                    (p0 - p1).length()
3895                );
3896                // Every fitted sample stays on the torus (shape-preserving).
3897                for k in 0..=64 {
3898                    let t = f64::from(k) / 64.0;
3899                    let p = ParametricCurve::evaluate(&c.curve, t);
3900                    assert!(
3901                        torus_implicit(p, major, minor).abs() < 1e-2,
3902                        "off-surface point {p:?} implicit={}",
3903                        torus_implicit(p, major, minor)
3904                    );
3905                }
3906            }
3907        }
3908    }
3909
3910    #[test]
3911    fn plane_torus_inner_tangent_figure_eight_stays_open() {
3912        use crate::traits::ParametricCurve;
3913        let (major, minor) = (10.0, 3.0);
3914        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
3915
3916        // A plane tangent to the inner equator (x = major - minor = 7) cuts a
3917        // self-touching figure-eight. The marcher traces it as a single chain
3918        // whose end lands on the opposite lobe — FAR from its start (gap is many
3919        // point-spacings). The wrap-close must NOT force-close this into a wrong
3920        // loop; it must stay OPEN so a self-touching curve is never sealed.
3921        let curves =
3922            intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
3923        assert!(!curves.is_empty(), "inner-tangent plane found no curves");
3924        let max_gap = curves
3925            .iter()
3926            .map(|c| {
3927                let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
3928                let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
3929                (p0 - p1).length()
3930            })
3931            .fold(0.0_f64, f64::max);
3932        assert!(
3933            max_gap > 1e-2,
3934            "figure-eight chain was wrongly force-closed (max end-gap={max_gap})"
3935        );
3936    }
3937
3938    #[test]
3939    fn line_torus_box_edge_crossing_is_exact() {
3940        // The census box edge x=6, y=-4 (z varying) crosses the torus (R=10,r=3)
3941        // at z = ±sqrt(r² − (rho−R)²), rho = hypot(6,4) ≈ 7.2111 → z ≈ ±1.1055.
3942        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
3943        let ts = intersect_line_torus(
3944            &torus,
3945            Point3::new(6.0, -4.0, -5.0),
3946            Vec3::new(0.0, 0.0, 1.0),
3947        );
3948        // Vertical line through (6,-4) meets the tube twice.
3949        assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
3950        let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
3951        let rho = 6.0_f64.hypot(4.0);
3952        let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
3953        assert!(
3954            (zs[0] - (-z_exp)).abs() < 1e-9,
3955            "z0={} exp={}",
3956            zs[0],
3957            -z_exp
3958        );
3959        assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
3960        // Each crossing lies on the torus.
3961        for &t in &ts {
3962            let p = Point3::new(6.0, -4.0, -5.0 + t);
3963            let rho = p.x().hypot(p.y());
3964            let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
3965            assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
3966        }
3967    }
3968
3969    #[test]
3970    fn line_torus_miss_and_tangent() {
3971        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
3972        // A vertical line at rho beyond the outer rim (x=20) misses entirely.
3973        let miss = intersect_line_torus(
3974            &torus,
3975            Point3::new(20.0, 0.0, 0.0),
3976            Vec3::new(0.0, 0.0, 1.0),
3977        );
3978        assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
3979        // The z-axis (rho=0) passes through the hole — no intersection.
3980        let axis =
3981            intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
3982        assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
3983    }
3984
3985    #[test]
3986    fn dispatch_via_analytic_surface() {
3987        let cyl =
3988            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
3989                .unwrap();
3990        let curves = intersect_plane_analytic(
3991            AnalyticSurface::Cylinder(&cyl),
3992            Vec3::new(0.0, 0.0, 1.0),
3993            0.0,
3994        )
3995        .unwrap();
3996        assert!(!curves.is_empty());
3997    }
3998
3999    #[test]
4000    fn perpendicular_cylinders_intersect() {
4001        let cyl_z =
4002            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
4003                .unwrap();
4004        let cyl_x =
4005            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
4006                .unwrap();
4007
4008        let curves = intersect_analytic_analytic(
4009            AnalyticSurface::Cylinder(&cyl_z),
4010            AnalyticSurface::Cylinder(&cyl_x),
4011            16,
4012        )
4013        .unwrap();
4014
4015        assert!(
4016            !curves.is_empty(),
4017            "perpendicular cylinders should intersect"
4018        );
4019
4020        for c in &curves {
4021            assert!(
4022                c.points.len() >= 2,
4023                "intersection curve should have >= 2 points, got {}",
4024                c.points.len()
4025            );
4026        }
4027    }
4028
4029    /// Neither cylinder's rulings all meet the other: the curve is one loop
4030    /// joined at its two branch points.
4031    #[test]
4032    fn partially_overlapping_cylinders_meet_in_one_closed_loop() {
4033        let cyl_z =
4034            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
4035                .unwrap();
4036        let cyl_x =
4037            CylindricalSurface::new(Point3::new(0.0, 1.2, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
4038                .unwrap();
4039        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
4040            .unwrap()
4041            .unwrap();
4042        assert_eq!(curves.len(), 1);
4043        let curve = &curves[0].curve;
4044        let (t0, t1) = curve.domain();
4045        assert!((curve.evaluate(t0) - curve.evaluate(t1)).length() < 1e-9);
4046        let off = |p: Point3| {
4047            let on_z = (p.x().hypot(p.y()) - 1.0).abs();
4048            let on_x = ((p.y() - 1.2).hypot(p.z()) - 1.0).abs();
4049            on_z.max(on_x)
4050        };
4051        let worst = (0..=400)
4052            .map(|k| off(curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0)))
4053            .fold(0.0, f64::max);
4054        assert!(worst < 2e-4, "curve leaves the cylinders by {worst}");
4055    }
4056
4057    /// Near tangency the thick cylinder's window of rulings (0.02 either side
4058    /// of a quarter turn) falls between its samples; the thin one's sweep
4059    /// finds the loop.
4060    #[test]
4061    fn near_tangent_cylinders_find_their_loop_on_the_thinner_sweep() {
4062        let cyl_z =
4063            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
4064                .unwrap();
4065        let cyl_x =
4066            CylindricalSurface::new(Point3::new(0.0, 1.1998, 0.0), Vec3::new(1.0, 0.0, 0.0), 0.2)
4067                .unwrap();
4068        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
4069            .unwrap()
4070            .expect("the thin cylinder's sweep finds the loop");
4071        assert_eq!(curves.len(), 1);
4072    }
4073
4074    #[test]
4075    fn sphere_cylinder_intersect() {
4076        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
4077        let cyl =
4078            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
4079                .unwrap();
4080
4081        let curves = intersect_analytic_analytic(
4082            AnalyticSurface::Sphere(&sphere),
4083            AnalyticSurface::Cylinder(&cyl),
4084            16,
4085        )
4086        .unwrap();
4087
4088        // A sphere of radius 2 and a cylinder of radius 1, both centered
4089        // at the origin, should intersect (the cylinder passes through
4090        // the sphere).
4091        assert!(!curves.is_empty(), "sphere and cylinder should intersect");
4092    }
4093
4094    #[test]
4095    fn exact_sphere_cylinder_coaxial_two_circles() {
4096        // Sphere r=6 at origin, coaxial cylinder r=3 along z: two latitude
4097        // circles at z = ±sqrt(36-9) = ±sqrt(27), each of radius 3.
4098        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
4099        let cyl =
4100            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
4101                .unwrap();
4102        let circles = exact_sphere_cylinder(&sphere, &cyl)
4103            .unwrap()
4104            .expect("coaxial case returns Some");
4105        assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
4106        let mut zs: Vec<f64> = circles
4107            .iter()
4108            .filter_map(|c| match c {
4109                ExactIntersectionCurve::Circle(circle) => {
4110                    assert!(
4111                        (circle.radius() - 3.0).abs() < 1e-9,
4112                        "rim radius == cyl radius"
4113                    );
4114                    Some(circle.center().z())
4115                }
4116                _ => None,
4117            })
4118            .collect();
4119        assert_eq!(zs.len(), 2, "both sections must be exact circles");
4120        zs.sort_by(f64::total_cmp);
4121        let z = 27.0_f64.sqrt();
4122        assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
4123    }
4124
4125    #[test]
4126    fn exact_sphere_cylinder_non_coaxial_defers() {
4127        // Cylinder axis offset from the sphere center → quartic curve, deferred.
4128        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
4129        let cyl =
4130            CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
4131                .unwrap();
4132        assert!(
4133            exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
4134            "non-coaxial sphere/cylinder defers to the marcher"
4135        );
4136    }
4137
4138    /// The circles among exact section curves.
4139    fn circles_of(curves: &[ExactIntersectionCurve]) -> Vec<&Circle3D> {
4140        curves
4141            .iter()
4142            .filter_map(|c| match c {
4143                ExactIntersectionCurve::Circle(circle) => Some(circle),
4144                _ => None,
4145            })
4146            .collect()
4147    }
4148
4149    /// Worst distance of a circle's points from a torus and from a second
4150    /// surface given by its own distance function.
4151    fn worst_off(
4152        circles: &[&Circle3D],
4153        torus: &ToroidalSurface,
4154        other: impl Fn(Point3) -> f64,
4155    ) -> f64 {
4156        let mut worst = 0.0_f64;
4157        for circle in circles {
4158            for k in 0..16 {
4159                let p = circle.evaluate(TAU * f64::from(k) / 16.0);
4160                let q = p - torus.center();
4161                let along = q.dot(torus.z_axis());
4162                let rho = (q - torus.z_axis() * along).length();
4163                let off = ((rho - torus.major_radius()).hypot(along) - torus.minor_radius()).abs();
4164                worst = worst.max(off).max(other(p).abs());
4165            }
4166        }
4167        worst
4168    }
4169
4170    #[test]
4171    fn exact_sphere_torus_meets_a_ball_on_the_axis_in_circles() {
4172        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
4173        for height in [0.0, 1.0] {
4174            let centre = Point3::new(0.0, 0.0, height);
4175            let sphere = SphericalSurface::new(centre, 3.0).unwrap();
4176            let curves = exact_sphere_torus(&sphere, &torus).unwrap().unwrap();
4177            let circles = circles_of(&curves);
4178            assert_eq!((curves.len(), circles.len()), (2, 2), "height {height}");
4179            let worst = worst_off(&circles, &torus, |p| (p - centre).length() - 3.0);
4180            assert!(worst < 1e-9, "height {height}: {worst}");
4181        }
4182    }
4183
4184    #[test]
4185    fn exact_sphere_torus_misses_touches_and_defers() {
4186        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
4187        let ball = |x: f64, r: f64| SphericalSurface::new(Point3::new(x, 0.0, 0.0), r).unwrap();
4188        assert!(
4189            exact_sphere_torus(&ball(0.0, 1.0), &torus)
4190                .unwrap()
4191                .unwrap()
4192                .is_empty(),
4193            "a small ball in the hole misses"
4194        );
4195        assert!(
4196            exact_sphere_torus(&ball(0.0, 2.5), &torus)
4197                .unwrap()
4198                .is_none(),
4199            "a ball touching the inner equator defers"
4200        );
4201        assert!(
4202            exact_sphere_torus(&ball(1.0, 3.0), &torus)
4203                .unwrap()
4204                .is_none(),
4205            "a ball off the axis defers"
4206        );
4207        let spindle = ToroidalSurface::with_axis_and_ref_dir(
4208            Point3::new(0.0, 0.0, 0.0),
4209            1.0,
4210            2.0,
4211            Vec3::new(0.0, 0.0, 1.0),
4212            Vec3::new(1.0, 0.0, 0.0),
4213        )
4214        .unwrap();
4215        assert!(
4216            exact_sphere_torus(&ball(0.0, 2.5), &spindle)
4217                .unwrap()
4218                .is_none()
4219        );
4220    }
4221
4222    #[test]
4223    fn exact_cylinder_torus_meets_a_coaxial_rod_in_circles() {
4224        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
4225        let z = Vec3::new(0.0, 0.0, 1.0);
4226        let rod = |r: f64| CylindricalSurface::new(Point3::new(0.0, 0.0, -5.0), z, r).unwrap();
4227        let curves = exact_cylinder_torus(&rod(4.2), &torus).unwrap().unwrap();
4228        let circles = circles_of(&curves);
4229        assert_eq!((curves.len(), circles.len()), (2, 2));
4230        let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - 4.2);
4231        assert!(worst < 1e-9, "{worst}");
4232        assert!(
4233            exact_cylinder_torus(&rod(2.0), &torus)
4234                .unwrap()
4235                .unwrap()
4236                .is_empty(),
4237            "a rod clear in the hole misses"
4238        );
4239        assert!(
4240            exact_cylinder_torus(&rod(5.5), &torus).unwrap().is_none(),
4241            "a wall touching the outer equator defers"
4242        );
4243        let tilted =
4244            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 1.0), 4.2)
4245                .unwrap();
4246        let offset = CylindricalSurface::new(Point3::new(0.5, 0.0, 0.0), z, 4.2).unwrap();
4247        assert!(exact_cylinder_torus(&tilted, &torus).unwrap().is_none());
4248        assert!(exact_cylinder_torus(&offset, &torus).unwrap().is_none());
4249        let spindle = ToroidalSurface::with_axis_and_ref_dir(
4250            Point3::new(0.0, 0.0, 0.0),
4251            1.0,
4252            2.0,
4253            z,
4254            Vec3::new(1.0, 0.0, 0.0),
4255        )
4256        .unwrap();
4257        assert!(
4258            exact_cylinder_torus(&rod(0.5), &spindle).unwrap().is_none(),
4259            "a spindle torus's inner lemon also meets the rod"
4260        );
4261    }
4262
4263    /// Loops of an off-axis sphere-cylinder pair: `(count, worst distance
4264    /// from either surface)`.
4265    fn off_axis_loops(cylinder_origin: Point3, cylinder_radius: f64) -> (usize, f64) {
4266        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
4267        let cyl =
4268            CylindricalSurface::new(cylinder_origin, Vec3::new(0.0, 0.0, 1.0), cylinder_radius)
4269                .unwrap();
4270        let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
4271            .unwrap()
4272            .unwrap();
4273        let mut worst: f64 = 0.0;
4274        for c in &curves {
4275            for ip in &c.points {
4276                let on_sphere = sphere.evaluate(ip.param1.0, ip.param1.1);
4277                let on_cylinder = cyl.evaluate(ip.param2.0, ip.param2.1);
4278                worst = worst
4279                    .max((on_sphere - ip.point).length())
4280                    .max((on_cylinder - ip.point).length());
4281            }
4282            let (t0, t1) = c.curve.domain();
4283            assert!((c.curve.evaluate(t0) - c.curve.evaluate(t1)).length() < 1e-9);
4284            for k in 0..=400 {
4285                let p = c.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
4286                let on_sphere = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 2.0).abs();
4287                let on_cylinder = ((p.x() - cylinder_origin.x())
4288                    .hypot(p.y() - cylinder_origin.y())
4289                    - cylinder_radius)
4290                    .abs();
4291                worst = worst.max(on_sphere).max(on_cylinder);
4292            }
4293        }
4294        (curves.len(), worst)
4295    }
4296
4297    /// A drill off the ball's axis passes through it: an entry and an exit
4298    /// loop.
4299    #[test]
4300    fn off_axis_drill_through_a_sphere_meets_it_in_two_loops() {
4301        let (count, worst) = off_axis_loops(Point3::new(0.5, 0.0, 0.0), 0.2);
4302        assert_eq!(count, 2);
4303        assert!(worst < 1e-5, "loops leave the surfaces by {worst}");
4304    }
4305
4306    /// A cylinder over the ball's side: one loop joined at its branch points.
4307    #[test]
4308    fn cylinder_over_a_spheres_side_meets_it_in_one_loop() {
4309        let (count, worst) = off_axis_loops(Point3::new(1.8, 0.0, 0.0), 0.5);
4310        assert_eq!(count, 1);
4311        assert!(worst < 5e-4, "loop leaves the surfaces by {worst}");
4312    }
4313
4314    #[test]
4315    fn disjoint_cylinders_no_intersection() {
4316        let cyl_a =
4317            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
4318                .unwrap();
4319        let cyl_b =
4320            CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
4321                .unwrap();
4322
4323        let curves = intersect_analytic_analytic(
4324            AnalyticSurface::Cylinder(&cyl_a),
4325            AnalyticSurface::Cylinder(&cyl_b),
4326            16,
4327        )
4328        .unwrap();
4329
4330        assert!(curves.is_empty(), "disjoint cylinders should not intersect");
4331    }
4332
4333    // ── Oblique plane × cone conic (ellipse / parabola / hyperbola) ──────
4334
4335    /// Collect 3D points from a returned exact curve, sampling analytic forms.
4336    fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
4337        use crate::traits::ParametricCurve;
4338        match curve {
4339            ExactIntersectionCurve::Circle(c) => (0..=64)
4340                .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
4341                .collect(),
4342            ExactIntersectionCurve::Ellipse(e) => (0..=64)
4343                .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
4344                .collect(),
4345            ExactIntersectionCurve::Points(pts) => pts.clone(),
4346        }
4347    }
4348
4349    /// Assert every returned point lies on the plane and the cone surface, on
4350    /// the real (`v >= 0`) nappe, and within a sane axial bound.
4351    fn assert_on_plane_and_cone(
4352        curves: &[ExactIntersectionCurve],
4353        cone: &ConicalSurface,
4354        n: Vec3,
4355        d: f64,
4356        z_bound: (f64, f64),
4357    ) {
4358        assert!(!curves.is_empty(), "expected at least one section curve");
4359        let mut total = 0;
4360        for curve in curves {
4361            for p in collect_points(curve) {
4362                total += 1;
4363                let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
4364                assert!(
4365                    plane_err < 1e-9,
4366                    "point off plane by {plane_err:.2e}: {p:?}"
4367                );
4368                let (u, v) = cone.project_point(p);
4369                let q = cone.evaluate(u, v);
4370                let cone_err =
4371                    ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
4372                        .sqrt();
4373                assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
4374                assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
4375                assert!(
4376                    p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
4377                    "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
4378                    p.z()
4379                );
4380            }
4381        }
4382        assert!(total >= 8, "too few section points ({total})");
4383    }
4384
4385    #[test]
4386    fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
4387        // 45°-half-angle cone (axis +z). A plane tilted only ~16.7° off horizontal
4388        // has plane-axis angle ≈ 73° > 45° (the cone's half-opening from axis) →
4389        // ellipse. Must come back as an exact Ellipse, fully on both surfaces.
4390        let cone = ConicalSurface::new(
4391            Point3::new(0.0, 0.0, 0.0),
4392            Vec3::new(0.0, 0.0, 1.0),
4393            std::f64::consts::FRAC_PI_4,
4394        )
4395        .unwrap();
4396        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
4397        // Plane through (0,0,5): d = n·(0,0,5).
4398        let d = n.z() * 5.0;
4399        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
4400        assert!(
4401            curves
4402                .iter()
4403                .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
4404            "oblique steep plane × cone must yield an exact Ellipse"
4405        );
4406        // The ellipse straddles z=5; with the 0.3 tilt the z-extent stays modest.
4407        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
4408    }
4409
4410    #[test]
4411    fn oblique_plane_cone_wrong_nappe_is_empty() {
4412        // Same ellipse-regime plane as above, but offset to the FAR side of the
4413        // apex (z=-5). The +z cone's real (v≥0) nappe is not met — only the
4414        // phantom v<0 nappe — so the result must be EMPTY, not a phantom ellipse.
4415        let cone = ConicalSurface::new(
4416            Point3::new(0.0, 0.0, 0.0),
4417            Vec3::new(0.0, 0.0, 1.0),
4418            std::f64::consts::FRAC_PI_4,
4419        )
4420        .unwrap();
4421        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
4422        let d = n.z() * -5.0;
4423        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
4424        assert!(
4425            curves.is_empty(),
4426            "plane on the phantom-nappe side must yield no real curve, got {}",
4427            curves.len()
4428        );
4429    }
4430
4431    #[test]
4432    fn oblique_plane_cone_parabola_on_both_single_branch() {
4433        // Plane normal at exactly 45° to the axis (= the cone half-opening) → the
4434        // plane is parallel to a generator → parabola. One unbounded branch.
4435        let cone = ConicalSurface::new(
4436            Point3::new(0.0, 0.0, 0.0),
4437            Vec3::new(0.0, 0.0, 1.0),
4438            std::f64::consts::FRAC_PI_4,
4439        )
4440        .unwrap();
4441        let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
4442        let d = n.x() * 3.0 + n.z() * 3.0; // through (3,0,3)
4443        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
4444        assert_eq!(
4445            curves.len(),
4446            1,
4447            "a parabola is a single branch, got {}",
4448            curves.len()
4449        );
4450        // Bounded by r_max = 32·|e|; |e| here is O(few), so allow a wide z window.
4451        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
4452    }
4453
4454    #[test]
4455    fn oblique_plane_cone_hyperbola_real_nappe_only() {
4456        // Faithful scooplabel lip-foot geometry: a 45° cone with axis −z and
4457        // apex at (−59,−59,15.85) (a bin corner), cut by the upper ramp tread
4458        // plane n=(0,0.99518,0.09802), d=−58.36056. The plane is nearly parallel
4459        // to the axis (cos≈0.098) → plane-axis angle ≈ 5.6° < 45° → hyperbola.
4460        // The downward real nappe is hit by exactly one branch; the phantom
4461        // upward nappe (and the asymptote runaway) must NOT appear, and the arc
4462        // must stay near the apex (the plane is ~1.2 mm from it).
4463        let cone = ConicalSurface::new(
4464            Point3::new(-59.0, -59.0, 15.85),
4465            Vec3::new(0.0, 0.0, -1.0),
4466            std::f64::consts::FRAC_PI_4,
4467        )
4468        .unwrap();
4469        let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
4470        let d = -58.360_56;
4471        let cos_theta = n.dot(cone.axis()).abs();
4472        assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
4473        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
4474        // Real downward nappe only: never above the apex (z=15.85). The vertex is
4475        // ~1.2 mm from the apex, so the bounded arc stays within a few mm of it.
4476        assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
4477        // Every returned curve is sampled Points (no false Circle/Ellipse).
4478        for c in &curves {
4479            assert!(
4480                matches!(c, ExactIntersectionCurve::Points(_)),
4481                "hyperbola must be sampled Points, not a closed conic"
4482            );
4483        }
4484    }
4485}