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::aabb::Aabb3;
11use crate::curves::{Circle3D, Ellipse3D, Hyperbola3D, Line3D, Parabola3D};
12use crate::frame::Frame3;
13use crate::nurbs::curve::NurbsCurve;
14use crate::nurbs::fitting::interpolate;
15use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
16use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
17use crate::tolerance::Tolerance;
18use crate::vec::{Point3, Vec3};
19
20/// Exact curve type resulting from plane-analytic surface intersection.
21#[derive(Debug, Clone)]
22pub enum ExactIntersectionCurve {
23    /// A circle (plane perpendicular to axis of cylinder/cone/sphere).
24    Circle(Circle3D),
25    /// An ellipse (plane oblique to cylinder/cone axis).
26    Ellipse(Ellipse3D),
27    /// Fallback to sampled point chain (torus, degenerate cases).
28    Points(Vec<Point3>),
29}
30
31/// A plane's section of an analytic surface, from [`exact_plane_section`].
32#[derive(Debug, Clone)]
33#[non_exhaustive]
34pub enum PlaneSection {
35    /// A circle.
36    Circle(Circle3D),
37    /// An ellipse.
38    Ellipse(Ellipse3D),
39    /// A straight section: a cylinder's ruling, running both ways from the
40    /// line's origin, or with `ray` a cone's ruling, running from the apex at
41    /// the line's origin along its direction only.
42    Line {
43        /// The ruling's line.
44        line: Line3D,
45        /// Whether the section runs one way only, from the line's origin.
46        ray: bool,
47    },
48    /// The one point where the plane touches the surface.
49    Point(Point3),
50    /// A sampled chain of points along the section.
51    Points(Vec<Point3>),
52    /// A cone's parabola.
53    Parabola(Parabola3D),
54    /// The branch of a cone's hyperbola on the cone's one nappe, which the
55    /// hyperbola's `u_axis` points to from its centre.
56    Hyperbola(Hyperbola3D),
57}
58
59impl From<ExactIntersectionCurve> for PlaneSection {
60    fn from(curve: ExactIntersectionCurve) -> Self {
61        match curve {
62            ExactIntersectionCurve::Circle(circle) => Self::Circle(circle),
63            ExactIntersectionCurve::Ellipse(ellipse) => Self::Ellipse(ellipse),
64            ExactIntersectionCurve::Points(points) => Self::Points(points),
65        }
66    }
67}
68
69/// A plane's exact section of an analytic surface.
70///
71/// It includes the sections [`exact_plane_analytic`] has no curve for: the
72/// rulings a plane along a cylinder's axis or through a cone's apex cuts,
73/// and the point where a plane touches a sphere or meets a cone at its apex
74/// alone. A cone's parabola and hyperbola come back as curves, which
75/// [`exact_plane_analytic`] samples into points, except in a band about the
76/// parabola where neither form keeps its digits.
77///
78/// The plane is `dot(normal, p) = d`, with `normal` of unit length.
79///
80/// # Errors
81///
82/// Returns an error if a section's curve cannot be built.
83pub fn exact_plane_section(
84    surface: AnalyticSurface<'_>,
85    normal: Vec3,
86    d: f64,
87) -> Result<Vec<PlaneSection>, MathError> {
88    match surface {
89        AnalyticSurface::Cylinder(cyl) if normal.dot(cyl.axis()).abs() < 1e-10 => {
90            return plane_cylinder_rulings(cyl, normal, d);
91        }
92        AnalyticSurface::Cone(cone) if plane_holds_apex(cone, normal, d) => {
93            return plane_cone_apex_rulings(cone, normal);
94        }
95        AnalyticSurface::Cone(cone) => {
96            if let Some(open) = plane_cone_open_section(cone, normal, d)? {
97                return Ok(open);
98            }
99        }
100        AnalyticSurface::Sphere(sphere) => {
101            let h = dot_np(normal, sphere.center()) - d;
102            let r = sphere.radius();
103            if (r - h.abs()).abs() <= TOUCH * r {
104                return Ok(vec![PlaneSection::Point(Point3::new(
105                    h.mul_add(-normal.x(), sphere.center().x()),
106                    h.mul_add(-normal.y(), sphere.center().y()),
107                    h.mul_add(-normal.z(), sphere.center().z()),
108                ))]);
109            }
110        }
111        AnalyticSurface::Cylinder(_) | AnalyticSurface::Torus(_) => {}
112    }
113    Ok(exact_plane_analytic(surface, normal, d)?
114        .into_iter()
115        .map(PlaneSection::from)
116        .collect())
117}
118
119/// How far a cone section's `e² − 1` (its eccentricity squared, less one)
120/// may sit from zero for the section to be read as a parabola.
121const PARABOLIC: f64 = 1e-12;
122
123/// Where a cone's hyperbola starts, in `e² − 1`: its centre lies the
124/// plane's offset over the conic coefficient away, and nearer zero its
125/// vertex loses digits.
126const HYPERBOLIC: f64 = 1e-6;
127
128/// A plane's parabola or hyperbola section of a cone, on the cone's one
129/// nappe, worked in the frame of [`exact_plane_cone`]. `None` for a circle
130/// or an ellipse, in the band between [`PARABOLIC`] and [`HYPERBOLIC`], and
131/// for a curve whose points do not hold to the cone (a cone so narrow or so
132/// flat that the formulas lose their digits), all of which go to the
133/// sampled section.
134#[allow(clippy::many_single_char_names)]
135fn plane_cone_open_section(
136    cone: &ConicalSurface,
137    normal: Vec3,
138    d: f64,
139) -> Result<Option<Vec<PlaneSection>>, MathError> {
140    let axis = cone.axis();
141    let c = normal.dot(axis);
142    let p2 = c.mul_add(-c, 1.0).max(0.0);
143    let p = p2.sqrt();
144    let rise = cone.half_angle().sin();
145    let k = rise * rise;
146    let a_coeff = p2 - k;
147    let eccentric = a_coeff / k;
148    let m = axis - normal * c;
149    let m_len = m.length();
150    if m_len < 1e-12 || eccentric < -PARABOLIC || (eccentric > PARABOLIC && eccentric <= HYPERBOLIC)
151    {
152        return Ok(None);
153    }
154    let e1 = m * (1.0 / m_len);
155    let e2 = normal.cross(e1);
156    let apex = cone.apex();
157    let e = d - dot_np(normal, apex);
158    let origin = apex + normal * e;
159    // A point `s` along `e1` from `origin` lies `e·c + s·p` up the axis from
160    // the apex, which the real nappe keeps non-negative.
161    let real = |s: f64| e.mul_add(c, s * p) >= 0.0;
162    // On the one nappe a point's height up the axis is `rise` times its
163    // distance from the apex.
164    let holds = |q: Point3| {
165        let w = q - apex;
166        let reach = w.length();
167        reach.is_finite() && (w.dot(axis) - rise * reach).abs() <= 1e-9 * (1.0 + reach)
168    };
169    if eccentric <= PARABOLIC {
170        // k t² = 2ecp s + e²(c² − k): the vertex at t = 0, opening along e1
171        // with the sign of ecp, `1 / 4f = k / 2|ecp|`.
172        let ecp = e * c * p;
173        let vertex_s = -e * (c * c - k) / (2.0 * c * p);
174        let focal = ecp.abs() / (2.0 * k);
175        if !(vertex_s.is_finite() && focal > 0.0 && focal.is_finite()) {
176            return Ok(None);
177        }
178        if !real(vertex_s) {
179            return Ok(Some(Vec::new()));
180        }
181        let parabola = Parabola3D::with_axes(origin + e1 * vertex_s, e1 * ecp.signum(), e2, focal)?;
182        if ![0.0, focal, -focal]
183            .iter()
184            .all(|&t| holds(parabola.evaluate(t)))
185        {
186            return Ok(None);
187        }
188        return Ok(Some(vec![PlaneSection::Parabola(parabola)]));
189    }
190    // A(s − s_c)² − k t² = e²k(1 − k)/A: the branches' vertices lie a real
191    // semi-axis either side of the centre, one on each nappe.
192    let centre_s = -e * c * p / a_coeff;
193    let rhs = e * e * k * (1.0 - k) / a_coeff;
194    let (real_axis, imaginary_axis) = ((rhs / a_coeff).sqrt(), (rhs / k).sqrt());
195    if !(real_axis > 0.0 && imaginary_axis > 0.0 && centre_s.is_finite()) {
196        return Ok(None);
197    }
198    let toward = if real(centre_s + real_axis) { e1 } else { -e1 };
199    let hyperbola = Hyperbola3D::with_axes(
200        origin + e1 * centre_s,
201        real_axis,
202        imaginary_axis,
203        toward,
204        e2,
205    )?;
206    if ![0.0, 1.0, -1.0]
207        .iter()
208        .all(|&t| holds(hyperbola.evaluate(t)))
209    {
210        return Ok(None);
211    }
212    Ok(Some(vec![PlaneSection::Hyperbola(hyperbola)]))
213}
214
215/// Rounding band, relative, within which a plane counts as touching a
216/// surface or passing through a cone's apex.
217const TOUCH: f64 = 4.0 * f64::EPSILON;
218
219/// The rulings a plane along a cylinder's axis cuts from it: two lines, the
220/// one it touches along, or none.
221fn plane_cylinder_rulings(
222    cyl: &CylindricalSurface,
223    normal: Vec3,
224    d: f64,
225) -> Result<Vec<PlaneSection>, MathError> {
226    // n·P(u, 0) = n·O + r·(a cos u + b sin u): the plane holds the ruling at
227    // u where cos(u − φ) = (d − n·O) / (r·√(a² + b²)).
228    let (a, b) = (normal.dot(cyl.x_axis()), normal.dot(cyl.y_axis()));
229    let amp = a.hypot(b);
230    if amp < 1e-12 {
231        return Ok(vec![]);
232    }
233    let ratio = (d - dot_np(normal, cyl.origin())) / (cyl.radius() * amp);
234    if ratio.abs() > 1.0 + TOUCH {
235        return Ok(vec![]);
236    }
237    let phi = b.atan2(a);
238    let spread = ratio.clamp(-1.0, 1.0).acos();
239    let at = if ratio.abs() >= 1.0 - TOUCH {
240        vec![phi + spread]
241    } else {
242        vec![phi + spread, phi - spread]
243    };
244    at.into_iter()
245        .map(|u| {
246            Ok(PlaneSection::Line {
247                line: Line3D::new(cyl.evaluate(u, 0.0), cyl.axis())?,
248                ray: false,
249            })
250        })
251        .collect()
252}
253
254/// Whether a plane passes through a cone's apex, but for rounding.
255fn plane_holds_apex(cone: &ConicalSurface, normal: Vec3, d: f64) -> bool {
256    let apex = cone.apex() - Point3::new(0.0, 0.0, 0.0);
257    (normal.dot(apex) - d).abs() <= TOUCH * (1.0 + apex.length() + d.abs())
258}
259
260/// The rulings a plane through a cone's apex cuts from its nappe, as rays
261/// from the apex: two, the one it touches along, or none, when the plane
262/// meets the cone at the apex alone.
263fn plane_cone_apex_rulings(
264    cone: &ConicalSurface,
265    normal: Vec3,
266) -> Result<Vec<PlaneSection>, MathError> {
267    // g(u) = cos a·(cos u·X + sin u·Y) + sin a·axis, so n·g(u) = 0 reads
268    // A cos u + B sin u = −C.
269    let (sin_a, cos_a) = cone.half_angle().sin_cos();
270    let a = cos_a * normal.dot(cone.x_axis());
271    let b = cos_a * normal.dot(cone.y_axis());
272    let c = sin_a * normal.dot(cone.axis());
273    let amp = a.hypot(b);
274    let apex = cone.apex();
275    if amp < 1e-12 * c.abs().max(1.0) {
276        return Ok(vec![PlaneSection::Point(apex)]);
277    }
278    let ratio = -c / amp;
279    if ratio.abs() > 1.0 + TOUCH {
280        return Ok(vec![PlaneSection::Point(apex)]);
281    }
282    let phi = b.atan2(a);
283    let spread = ratio.clamp(-1.0, 1.0).acos();
284    let at = if ratio.abs() >= 1.0 - TOUCH {
285        vec![phi + spread]
286    } else {
287        vec![phi + spread, phi - spread]
288    };
289    at.into_iter()
290        .map(|u| {
291            Ok(PlaneSection::Line {
292                line: Line3D::new(apex, cone.evaluate(u, 1.0) - apex)?,
293                ray: true,
294            })
295        })
296        .collect()
297}
298
299/// Compute exact intersection curves between a plane and an analytic surface.
300///
301/// Returns exact `Circle3D` or `Ellipse3D` where possible, falling back to
302/// sampled points for complex cases (torus).
303///
304/// A plane along a cylinder's axis or through a cone's apex, whose sections
305/// are straight, and a plane touching a sphere get no curve here;
306/// [`exact_plane_section`] returns those sections.
307///
308/// The plane is defined by `dot(normal, p) = d`.
309///
310/// # Errors
311///
312/// Returns an error if the intersection computation fails.
313pub fn exact_plane_analytic(
314    surface: AnalyticSurface<'_>,
315    plane_normal: Vec3,
316    plane_d: f64,
317) -> Result<Vec<ExactIntersectionCurve>, MathError> {
318    exact_plane_analytic_reaching(surface, plane_normal, plane_d, 0.0)
319}
320
321/// [`exact_plane_analytic`] with a cone's sampled hyperbola or parabola
322/// carried at least `reach` from the apex, so it spans whatever faces the
323/// caller will trim it to.
324///
325/// # Errors
326///
327/// Returns an error if the intersection computation fails.
328pub fn exact_plane_analytic_reaching(
329    surface: AnalyticSurface<'_>,
330    plane_normal: Vec3,
331    plane_d: f64,
332    reach: f64,
333) -> Result<Vec<ExactIntersectionCurve>, MathError> {
334    match surface {
335        AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
336        AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
337        AnalyticSurface::Cone(cone) if plane_holds_apex(cone, plane_normal, plane_d) => Ok(vec![]),
338        AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d, reach),
339        AnalyticSurface::Torus(torus) => {
340            if let Some(circles) = exact_plane_torus(torus, plane_normal, plane_d)? {
341                return Ok(circles);
342            }
343            if let Some(loops) = plane_torus_winding_loops(torus, plane_normal, plane_d, 128) {
344                return Ok(loops
345                    .into_iter()
346                    .map(ExactIntersectionCurve::Points)
347                    .collect());
348            }
349            // Other torus sections are degree-4 — fall back to sampling.
350            let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
351            Ok(chains
352                .into_iter()
353                .map(ExactIntersectionCurve::Points)
354                .collect())
355        }
356    }
357}
358
359/// The plane-torus sections that are circles:
360///
361/// - a plane across the axis at height `h` from the centre, `|h| < r`: the
362///   two circles of radius `R ± sqrt(r² − h²)` about the axis;
363/// - a plane through the axis: the two tube cross-sections of radius `r`,
364///   `R` either side of the axis.
365///
366/// A plane across the axis tangent to the tube's top or bottom touches it
367/// along the one circle of radius `R`, ring or spindle.
368///
369/// `Some` of no curves for a plane across the axis that misses the tube;
370/// `None` for any other plane, and for a section across the axis whose inner
371/// circle would reach the axis.
372fn exact_plane_torus(
373    torus: &ToroidalSurface,
374    normal: Vec3,
375    d: f64,
376) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
377    let len = normal.length();
378    let n = normal.normalize()?;
379    let d = d / len;
380    let axis = torus.z_axis();
381    let center = torus.center();
382    let (big, small) = (torus.major_radius(), torus.minor_radius());
383    let height = d - dot_np(n, center);
384    let along = n.dot(axis);
385    if along.abs() > 1.0 - 1e-10 {
386        if height.abs() >= small - 1e-10 * small {
387            if height.abs() > small + 1e-10 * small {
388                return Ok(Some(Vec::new()));
389            }
390            // Tangent to the tube's top or bottom: the plane touches the
391            // torus along the one circle of its own radius. That circle lies
392            // on the torus within the plane's distance from the tube's top,
393            // so it stands for the section while that distance is within the
394            // linear tolerance, whatever the scale. A tilted plane's section
395            // is no circle.
396            if big <= 1e-10 * small
397                || axis.cross(n).length() > 1e-12
398                || (small - height.abs()).abs() > crate::tolerance::Tolerance::default().linear
399            {
400                return Ok(None);
401            }
402            let middle = center + n * height;
403            return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
404                middle, n, big,
405            )?)]));
406        }
407        let reach = small.mul_add(small, -(height * height)).sqrt();
408        if big - reach <= 1e-10 * big {
409            return Ok(None);
410        }
411        let middle = center + n * height;
412        return Ok(Some(vec![
413            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big + reach)?),
414            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big - reach)?),
415        ]));
416    }
417    if along.abs() < 1e-10 && height.abs() < 1e-10 * (big + small) {
418        let out = axis.cross(n).normalize()?;
419        return Ok(Some(vec![
420            ExactIntersectionCurve::Circle(Circle3D::new(center + out * big, n, small)?),
421            ExactIntersectionCurve::Circle(Circle3D::new(center - out * big, n, small)?),
422        ]));
423    }
424    Ok(None)
425}
426
427/// Exact plane-cylinder intersection.
428///
429/// - Plane perpendicular to axis → `Circle3D`
430/// - Plane oblique to axis → `Ellipse3D`
431/// - Plane parallel to axis → `Points` fallback (0 or 2 lines)
432fn exact_plane_cylinder(
433    cyl: &CylindricalSurface,
434    normal: Vec3,
435    d: f64,
436) -> Result<Vec<ExactIntersectionCurve>, MathError> {
437    let axis = cyl.axis();
438    let cos_theta = normal.dot(axis).abs();
439    let r = cyl.radius();
440
441    if cos_theta < 1e-10 {
442        // A plane along the axis cuts straight rulings, which
443        // `exact_plane_section` returns.
444        return Ok(vec![]);
445    }
446
447    // Find where axis intersects the plane: axis_point + t*axis, dot(normal, P) = d
448    // t = (d - dot(normal, origin)) / dot(normal, axis)
449    let n_dot_axis = normal.dot(axis);
450    let n_dot_origin = dot_np(normal, cyl.origin());
451    let t = (d - n_dot_origin) / n_dot_axis;
452    let center_on_axis = Point3::new(
453        cyl.origin().x() + t * axis.x(),
454        cyl.origin().y() + t * axis.y(),
455        cyl.origin().z() + t * axis.z(),
456    );
457
458    if cos_theta > 1.0 - 1e-10 {
459        // Plane perpendicular to axis → Circle
460        let circle = Circle3D::new(center_on_axis, normal, r)?;
461        Ok(vec![ExactIntersectionCurve::Circle(circle)])
462    } else {
463        // Oblique plane → Ellipse
464        // Semi-minor = r (the cylinder radius, unchanged)
465        // Semi-major = r / cos(θ) where θ = angle between plane normal and axis
466        let semi_minor = r;
467        let semi_major = r / cos_theta;
468
469        // The major axis direction lies in the intersection of the plane
470        // with the plane containing the axis and the plane normal.
471        // It's the projection of the axis onto the cutting plane, normalized.
472        let axis_proj = Vec3::new(
473            axis.x() - n_dot_axis * normal.x(),
474            axis.y() - n_dot_axis * normal.y(),
475            axis.z() - n_dot_axis * normal.z(),
476        );
477        let u_axis = axis_proj.normalize()?;
478        let v_axis = normal.cross(u_axis);
479
480        let ellipse = Ellipse3D::with_axes(
481            center_on_axis,
482            normal,
483            semi_major,
484            semi_minor,
485            u_axis,
486            v_axis,
487        )?;
488        Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
489    }
490}
491
492/// Exact plane-sphere intersection.
493///
494/// Always produces a `Circle3D` (or empty if no intersection).
495fn exact_plane_sphere(
496    sphere: &SphericalSurface,
497    normal: Vec3,
498    d: f64,
499) -> Result<Vec<ExactIntersectionCurve>, MathError> {
500    let h = dot_np(normal, sphere.center()) - d;
501    let r = sphere.radius();
502
503    // A plane touching the sphere meets it at a point, which
504    // `exact_plane_section` returns.
505    if r - h.abs() <= TOUCH * r {
506        return Ok(vec![]);
507    }
508
509    let circle_r = (r.mul_add(r, -(h * h))).sqrt();
510    let circle_center = Point3::new(
511        h.mul_add(-normal.x(), sphere.center().x()),
512        h.mul_add(-normal.y(), sphere.center().y()),
513        h.mul_add(-normal.z(), sphere.center().z()),
514    );
515
516    let circle = Circle3D::new(circle_center, normal, circle_r)?;
517    Ok(vec![ExactIntersectionCurve::Circle(circle)])
518}
519
520/// Exact sphere-sphere intersection: the circle on the two spheres' radical
521/// plane, its normal pointing from the first centre to the second. `None`
522/// for one sphere twice (the same surface, no curve).
523///
524/// The circle is built from the smaller sphere, whose radius bounds it, and
525/// from the centres' offset alone, so neither the operands' order nor where
526/// the pair sits in space decides whether a small circle survives.
527///
528/// # Errors
529///
530/// Returns an error if the circle cannot be built.
531pub fn exact_sphere_sphere(
532    s1: &SphericalSurface,
533    s2: &SphericalSurface,
534) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
535    let delta = s2.center() - s1.center();
536    let d = delta.length();
537    let (r1, r2) = (s1.radius(), s2.radius());
538    let scale = r1.max(r2);
539    if d <= 1e-12 * scale {
540        // Concentric spheres of different radii never meet.
541        return Ok(((r1 - r2).abs() > 1e-12 * scale).then(Vec::new));
542    }
543    let normal = delta * (1.0 / d);
544    // From the smaller sphere's centre toward the larger's, the radical plane
545    // lies `along` away.
546    let (centre, toward, r_small, r_big) = if r1 <= r2 {
547        (s1.center(), normal, r1, r2)
548    } else {
549        (s2.center(), -normal, r2, r1)
550    };
551    let along = d.mul_add(d, r_small.mul_add(r_small, -(r_big * r_big))) / (2.0 * d);
552    if along.abs() > r_small - 1e-10 * scale.max(1.0) {
553        return Ok(Some(Vec::new()));
554    }
555    let radius = r_small.mul_add(r_small, -(along * along)).sqrt();
556    let circle = Circle3D::new(centre + toward * along, normal, radius)?;
557    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
558}
559
560/// Exact plane-cone intersection.
561///
562/// The conic type is set by the cone's half-opening angle from the axis
563/// (`γ = π/2 − half_angle`) versus the plane-axis angle `ψ`:
564/// - Plane perpendicular to axis (`ψ = π/2`) → `Circle3D`
565/// - `ψ > γ` (ellipse) → closed-form `Ellipse3D`
566/// - `ψ ≤ γ` (parabola/hyperbola) → bounded single-branch `Points` (one chain
567///   per branch — a hyperbola's two nappes never share a chain)
568fn exact_plane_cone(
569    cone: &ConicalSurface,
570    normal: Vec3,
571    d: f64,
572    reach: f64,
573) -> Result<Vec<ExactIntersectionCurve>, MathError> {
574    let axis = cone.axis();
575    let cos_theta = normal.dot(axis).abs();
576    let half_angle = cone.half_angle();
577
578    if cos_theta > 1.0 - 1e-10 {
579        // Plane perpendicular to axis → Circle
580        // Find where axis meets the plane
581        let n_dot_axis = normal.dot(axis);
582        let n_dot_apex = dot_np(normal, cone.apex());
583        let t = (d - n_dot_apex) / n_dot_axis;
584
585        // t is the signed distance from apex to plane along the axis.
586        // The real cone is a single nappe; the perpendicular-plane section is a
587        // circle whose radius follows from the axial offset |t|.
588        // |t| ≈ 0 means the plane passes through the apex → degenerate point.
589        if t.abs() < 1e-10 {
590            return Ok(vec![]);
591        }
592
593        let center = Point3::new(
594            cone.apex().x() + t * axis.x(),
595            cone.apex().y() + t * axis.y(),
596            cone.apex().z() + t * axis.z(),
597        );
598        // half_angle is the angle from the radial plane to the surface.
599        // Axial distance t = v * sin(half_angle), so v = t / sin(half_angle).
600        // Radius at v = v * cos(half_angle) = t * cos(half_angle) / sin(half_angle).
601        let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
602        if circle_r < 1e-15 {
603            return Ok(vec![]);
604        }
605
606        let circle = Circle3D::new(center, normal, circle_r)?;
607        return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
608    }
609
610    // Oblique plane. Classify the conic in the plane-aligned frame.
611    //
612    // Decompose the (unit) axis as a = c·n + p·e1, where c = n·a, e1 is the unit
613    // in-plane projection of the axis, and p = |projection| = sqrt(1−c²). Write a
614    // point Q on the plane as Q = apex + e·n + s·e1 + t·e2 (e = d − n·apex,
615    // e2 = n×e1). The cone equation (w·a)² = cos²γ·(w·w) with k = cos²γ =
616    // sin²(half_angle) reduces to (no s·t cross term, since e1/e2 align with the
617    // conic axes):
618    //     (p²−k)·s² + 2ecp·s + e²(c²−k) = k·t²
619    // The s² coefficient A = p²−k = sin²θ − sin²(half_angle) sets the type:
620    // A < 0 → ellipse, A = 0 → parabola, A > 0 → hyperbola.
621    let c = normal.dot(axis);
622    let p2 = (1.0 - c * c).max(0.0);
623    let p = p2.sqrt();
624    let k = half_angle.sin().powi(2);
625    let a_coeff = p2 - k;
626
627    // Build the plane-aligned frame e1 (in-plane axis projection), e2 = n×e1.
628    let m = Vec3::new(
629        axis.x() - c * normal.x(),
630        axis.y() - c * normal.y(),
631        axis.z() - c * normal.z(),
632    );
633    let m_len = m.length();
634    if m_len < 1e-12 {
635        // Axis parallel to normal — handled by the perpendicular branch above;
636        // fall back to sampling for safety.
637        let chains = sample_plane_cone(cone, normal, d, reach)?;
638        return Ok(chains
639            .into_iter()
640            .map(ExactIntersectionCurve::Points)
641            .collect());
642    }
643    let e1 = m * (1.0 / m_len);
644    let e2 = normal.cross(e1);
645    let apex = cone.apex();
646    let e = d - dot_np(normal, apex);
647
648    // Ellipse → closed form. A = p²−k < 0 with a margin to keep the
649    // near-parabolic regime on the robust sampled path.
650    if a_coeff < -1e-9 {
651        let abs_a = -a_coeff; // = k − p² > 0
652        // Real-nappe guard: in the ellipse regime n·g(u) keeps constant sign(c),
653        // so v = e/(n·g) ≥ 0 only when e and c share a sign. When e·c < 0 the
654        // plane is offset to the far side of the apex from the cone's opening —
655        // the section lies entirely on the phantom nappe, so there is no real
656        // curve (RHS below is positive regardless of sign, so it can't catch this).
657        if e * c < 0.0 {
658            return Ok(vec![]);
659        }
660        // |A|(s − s_c)² + k·t² = RHS, with s_c = ecp/|A| and
661        // RHS = e²·k·(1−k)/|A| (always > 0 for a real ellipse).
662        let s_c = e * c * p / abs_a;
663        let rhs = e * e * k * (1.0 - k) / abs_a;
664        if rhs <= 0.0 {
665            return Ok(vec![]);
666        }
667        let semi_s = (rhs / abs_a).sqrt(); // extent along e1
668        let semi_t = (rhs / k).sqrt(); // extent along e2
669        if semi_s < 1e-12 || semi_t < 1e-12 {
670            return Ok(vec![]);
671        }
672        let center = apex + normal * e + e1 * s_c;
673        let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
674            (semi_s, semi_t, e1, e2)
675        } else {
676            (semi_t, semi_s, e2, e1)
677        };
678        let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
679        return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
680    }
681
682    // Parabola / hyperbola (and the near-parabolic ellipse margin): the section
683    // is unbounded, so emit bounded, branch-separated sample chains.
684    let chains = sample_plane_cone(cone, normal, d, reach)?;
685    Ok(chains
686        .into_iter()
687        .map(ExactIntersectionCurve::Points)
688        .collect())
689}
690
691/// The exact arc from `from` to `to` of a plane's parabola or hyperbola
692/// section of a cone, both ends on one branch of it, as a rational quadratic
693/// NURBS.
694///
695/// A hyperbola `x = a cosh φ, y = b sinh φ` (in the plane frame of
696/// `exact_plane_cone`) is cut into pieces of at most one unit of `φ`, each
697/// a conic Bézier: its middle point is where the end tangents meet and its
698/// middle weight is the cosh of half the piece's span. A parabola is one
699/// polynomial quadratic. `None` for an elliptic or circular section, a plane
700/// through the apex, or ends off one branch of the section.
701///
702/// # Errors
703///
704/// Returns an error if the plane normal is zero or the curve cannot be built.
705#[allow(clippy::many_single_char_names)]
706pub fn plane_cone_conic_arc(
707    cone: &ConicalSurface,
708    normal: Vec3,
709    d: f64,
710    from: Point3,
711    to: Point3,
712) -> Result<Option<NurbsCurve>, MathError> {
713    let len = normal.length();
714    if len < 1e-15 {
715        return Err(MathError::ZeroVector);
716    }
717    let (normal, d) = (normal * (1.0 / len), d / len);
718    let axis = cone.axis();
719    let c = normal.dot(axis);
720    let p2 = (1.0 - c * c).max(0.0);
721    let p = p2.sqrt();
722    let k = cone.half_angle().sin().powi(2);
723    let a_coeff = p2 - k;
724    let m = Vec3::new(
725        axis.x() - c * normal.x(),
726        axis.y() - c * normal.y(),
727        axis.z() - c * normal.z(),
728    );
729    let m_len = m.length();
730    if m_len < 1e-12 || a_coeff < -1e-9 {
731        return Ok(None);
732    }
733    let e1 = m * (1.0 / m_len);
734    let e2 = normal.cross(e1);
735    let apex = cone.apex();
736    let e = d - dot_np(normal, apex);
737    let origin = apex + normal * e;
738    let plane_st = |q: Point3| {
739        let w = q - origin;
740        (w.dot(e1), w.dot(e2))
741    };
742    let ((s0, t0), (s1, t1)) = (plane_st(from), plane_st(to));
743    let scale = s0.abs().max(t0.abs()).max(s1.abs()).max(t1.abs()).max(1.0);
744    if e.abs() < 1e-9 * scale || (from - to).length() <= 1e-9 * scale {
745        return Ok(None);
746    }
747    let point = |s: f64, t: f64| origin + e1 * s + e2 * t;
748    let on_curve = |q: Point3, r: Point3| (q - r).length() <= 1e-6 * scale;
749    let (control, weights) = if a_coeff.abs() <= 1e-9 {
750        // (p² − k) s² vanishes: 2ecp·s + e²(c² − k) = k·t², s = α t² + β.
751        let lin = 2.0 * e * c * p;
752        if lin.abs() < 1e-12 * scale {
753            return Ok(None);
754        }
755        let (alpha, beta) = (k / lin, -e * e * (c * c - k) / lin);
756        if !on_curve(point(alpha * t0 * t0 + beta, t0), from)
757            || !on_curve(point(alpha * t1 * t1 + beta, t1), to)
758        {
759            return Ok(None);
760        }
761        let mid = point(alpha * t0 * t1 + beta, 0.5 * (t0 + t1));
762        (vec![from, mid, to], vec![1.0; 3])
763    } else {
764        // A (s − s_c)² − k t² = R with R = e² k (1 − k) / A.
765        let s_c = -e * c * p / a_coeff;
766        let r = e * e * k * (1.0 - k) / a_coeff;
767        if r <= 0.0 {
768            return Ok(None);
769        }
770        let (a, b) = ((r / a_coeff).sqrt(), (r / k).sqrt());
771        let (x0, x1) = (s0 - s_c, s1 - s_c);
772        if x0 * x1 <= 0.0 {
773            return Ok(None);
774        }
775        let side = x0.signum();
776        let hyperbola = |phi: f64| point(s_c + side * a * phi.cosh(), b * phi.sinh());
777        let (phi0, phi1) = ((t0 / b).asinh(), (t1 / b).asinh());
778        if !on_curve(hyperbola(phi0), from) || !on_curve(hyperbola(phi1), to) {
779            return Ok(None);
780        }
781        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
782        let pieces = ((phi1 - phi0).abs().ceil() as usize).max(1);
783        let mut control = vec![from];
784        let mut weights = vec![1.0];
785        for i in 0..pieces {
786            #[allow(clippy::cast_precision_loss)]
787            let (fa, fb) = (i as f64 / pieces as f64, (i + 1) as f64 / pieces as f64);
788            let (pa, pb) = (phi0 + (phi1 - phi0) * fa, phi0 + (phi1 - phi0) * fb);
789            let (mid, half) = (0.5 * (pa + pb), 0.5 * (pb - pa));
790            let w = half.cosh();
791            control.push(point(s_c + side * a * mid.cosh() / w, b * mid.sinh() / w));
792            weights.push(w);
793            control.push(if i + 1 == pieces { to } else { hyperbola(pb) });
794            weights.push(1.0);
795        }
796        (control, weights)
797    };
798    let pieces = (control.len() - 1) / 2;
799    let mut knots = vec![0.0; 3];
800    for i in 1..pieces {
801        #[allow(clippy::cast_precision_loss)]
802        knots.extend([i as f64; 2]);
803    }
804    #[allow(clippy::cast_precision_loss)]
805    knots.extend([pieces as f64; 3]);
806    let curve = NurbsCurve::new(2, knots, control, weights)?;
807    // The closed forms drop terms that vanish only on the exact conic (a
808    // barely elliptic section read as a parabola), so the arc must meet the
809    // cone between its ends too: a point at radius ρ and height h off the
810    // apex lies |ρ sin α − |h| cos α| from it.
811    let (sin_a, cos_a) = cone.half_angle().sin_cos();
812    let off_cone = |q: Point3| {
813        let w = q - apex;
814        let h = w.dot(axis);
815        (w - axis * h)
816            .length()
817            .mul_add(sin_a, -(h.abs() * cos_a))
818            .abs()
819    };
820    for i in 0..pieces {
821        for f in [0.25, 0.5, 0.75] {
822            #[allow(clippy::cast_precision_loss)]
823            if off_cone(curve.evaluate(i as f64 + f)) > 1e-9 * scale {
824                return Ok(None);
825            }
826        }
827    }
828    Ok(Some(curve))
829}
830
831/// Reference to an analytic surface for intersection dispatch.
832#[derive(Clone, Copy)]
833pub enum AnalyticSurface<'a> {
834    /// Cylindrical surface reference.
835    Cylinder(&'a CylindricalSurface),
836    /// Conical surface reference.
837    Cone(&'a ConicalSurface),
838    /// Spherical surface reference.
839    Sphere(&'a SphericalSurface),
840    /// Toroidal surface reference.
841    Torus(&'a ToroidalSurface),
842}
843
844/// Compute `n . p` treating a `Point3` as a position vector.
845fn dot_np(n: Vec3, p: Point3) -> f64 {
846    n.dot(Vec3::new(p.x(), p.y(), p.z()))
847}
848
849/// Intersect a plane with an analytic surface.
850///
851/// The plane is defined by `dot(normal, p) = d`.
852///
853/// # Errors
854///
855/// Returns an error if the intersection computation fails.
856pub fn intersect_plane_analytic(
857    surface: AnalyticSurface<'_>,
858    normal: Vec3,
859    d: f64,
860) -> Result<Vec<IntersectionCurve>, MathError> {
861    match surface {
862        AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
863        AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
864        AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
865        AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
866    }
867}
868
869/// Sample points on the plane-analytic intersection without NURBS curve fitting.
870///
871/// Returns chains of ordered 3D sample points. Each chain is one connected
872/// component of the intersection curve. This is much faster than
873/// `intersect_plane_analytic` when only sample points are needed (e.g. for
874/// boolean intersection segment generation).
875///
876/// # Errors
877///
878/// Returns an error if the intersection computation fails.
879pub fn sample_plane_analytic(
880    surface: AnalyticSurface<'_>,
881    normal: Vec3,
882    d: f64,
883) -> Result<Vec<Vec<Point3>>, MathError> {
884    match surface {
885        AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
886        AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d, 0.0),
887        AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
888        AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
889    }
890}
891
892/// Sample the plane-cylinder intersection as ordered 3D points.
893#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
894fn sample_plane_cylinder(
895    cyl: &CylindricalSurface,
896    normal: Vec3,
897    d: f64,
898) -> Result<Vec<Vec<Point3>>, MathError> {
899    let n_samples = 64_usize;
900    let mut points = Vec::with_capacity(n_samples + 1);
901
902    for i in 0..=n_samples {
903        let u = TAU * (i as f64) / (n_samples as f64);
904        let base = cyl.evaluate(u, 0.0);
905        let n_dot_axis = normal.dot(cyl.axis());
906        let n_dot_base = dot_np(normal, base);
907
908        if n_dot_axis.abs() < 1e-12 {
909            if (n_dot_base - d).abs() < 1e-6 {
910                points.push(base);
911            }
912        } else {
913            let v = (d - n_dot_base) / n_dot_axis;
914            if v.abs() <= 100.0 {
915                points.push(cyl.evaluate(u, v));
916            }
917        }
918    }
919
920    if points.len() < 2 {
921        Ok(vec![])
922    } else {
923        Ok(vec![points])
924    }
925}
926
927/// Sample the plane-sphere intersection as ordered 3D points.
928#[allow(clippy::cast_precision_loss)]
929fn sample_plane_sphere(
930    sphere: &SphericalSurface,
931    normal: Vec3,
932    d: f64,
933) -> Result<Vec<Vec<Point3>>, MathError> {
934    let h = dot_np(normal, sphere.center()) - d;
935    let r = sphere.radius();
936
937    if h.abs() > r - 1e-10 {
938        return Ok(vec![]);
939    }
940
941    let circle_r = (r.mul_add(r, -(h * h))).sqrt();
942    let circle_center = Point3::new(
943        h.mul_add(-normal.x(), sphere.center().x()),
944        h.mul_add(-normal.y(), sphere.center().y()),
945        h.mul_add(-normal.z(), sphere.center().z()),
946    );
947
948    let basis = Frame3::from_normal(circle_center, normal)?;
949    let u_dir = basis.x;
950    let v_dir = basis.y;
951
952    let n_samples = 64_usize;
953    let mut points = Vec::with_capacity(n_samples + 1);
954
955    for i in 0..=n_samples {
956        let theta = TAU * (i as f64) / (n_samples as f64);
957        let (sin_t, cos_t) = theta.sin_cos();
958        points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
959    }
960
961    Ok(vec![points])
962}
963
964/// Sample the plane-cone intersection as ordered 3D points.
965///
966/// The cone is the single real nappe `v >= 0` of `P(u,v) = apex + v·g(u)`.
967/// Along each generator `g(u)` the plane `n·P = d` is linear in `v`, so
968/// `v = (d − n·apex) / (n·g(u))`. We keep only `v >= 0` (the phantom `v < 0`
969/// nappe is geometrically absent) and `v` below a finite bound (near an
970/// asymptote `n·g(u) → 0` so `v → ∞` — those points run off the surface and
971/// must be excluded). The angular samples that survive form one contiguous arc
972/// (ellipse) or two (parabola/hyperbola, one per branch); each contiguous run
973/// is returned as a separate ordered chain so the consumer never stitches two
974/// disjoint branches into one curve.
975#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
976fn sample_plane_cone(
977    cone: &ConicalSurface,
978    normal: Vec3,
979    d: f64,
980    reach: f64,
981) -> Result<Vec<Vec<Point3>>, MathError> {
982    let apex = cone.apex();
983    let n_dot_apex = dot_np(normal, apex);
984    let e = d - n_dot_apex;
985
986    // Per-generator solve: along g(u) the plane is linear in v, v = e / (n·g(u)).
987    // Sample u densely; keep only the real nappe (v >= 0) and skip near-asymptote
988    // generators (n·g(u) ≈ 0 → v → ∞).
989    let n_samples = 512_usize;
990    let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
991    let mut v_min = f64::INFINITY;
992    for i in 0..n_samples {
993        let u = TAU * (i as f64) / (n_samples as f64);
994        let g = cone.evaluate(u, 1.0) - apex;
995        let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
996        if n_dot_g.abs() < 1e-12 {
997            vs.push(None);
998            continue;
999        }
1000        let v = e / n_dot_g;
1001        if v >= -1e-12 {
1002            let v = v.max(0.0);
1003            v_min = v_min.min(v);
1004            vs.push(Some(v));
1005        } else {
1006            vs.push(None);
1007        }
1008    }
1009
1010    if !v_min.is_finite() {
1011        return Ok(Vec::new());
1012    }
1013
1014    // Bound the arc around the conic vertex (closest approach to the apex, at
1015    // v_min). An ellipse is naturally bounded; a parabola/hyperbola is not, so
1016    // cap the cone radius at a generous multiple of the vertex radius. This is
1017    // scale-invariant and centred on where any finite cone face's overlap lies;
1018    // the downstream consumer trims the fitted curve to the actual face AABB, so
1019    // over-coverage is harmless. The floor handles a vertex at the apex (v_min≈0).
1020    // A caller that knows its faces asks for their reach: an open hyperbola
1021    // (a vertex close to the axis) crosses a rim far past eight vertex radii.
1022    let v_max = (8.0 * v_min).max(v_min + 4.0).max(reach);
1023
1024    // Per-sample v within the cap; the raw values stay in `vs` for the
1025    // boundary solve below.
1026    let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
1027
1028    let point_at = |u: f64, v: f64| -> Point3 {
1029        let g = cone.evaluate(u, 1.0) - apex;
1030        apex + g * v
1031    };
1032    #[allow(clippy::cast_precision_loss)]
1033    let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
1034    let n_dot_g_at = |u: f64| -> f64 {
1035        let g = cone.evaluate(u, 1.0) - apex;
1036        normal.dot(Vec3::new(g.x(), g.y(), g.z()))
1037    };
1038
1039    if kept.iter().all(Option::is_some) {
1040        // Closed loop (ellipse regime): emit all points and repeat the first.
1041        let mut pts: Vec<Point3> = kept
1042            .iter()
1043            .enumerate()
1044            .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
1045            .collect();
1046        if let Some(&first) = pts.first() {
1047            pts.push(first);
1048        }
1049        return Ok(vec![pts]);
1050    }
1051
1052    // A hyperbola/parabola tail diverges as 1/(n·g), so between the last kept
1053    // sample and its dropped neighbour v can leap far past `v_max` in one
1054    // uniform-u pitch — and any finite face window inside that leap is lost
1055    // (a taper cone grazed 0.05 by a prism plane lost its entire 0.5-tall
1056    // section to exactly this aliasing). Extend each run end to the exact
1057    // `v_max` boundary: bisect u for `n·g(u) = e/v_max` inside the dropped
1058    // pitch (n·g is monotone there — its extrema sit at the conic vertex,
1059    // far from any asymptote), then fill the tail with uniform-u samples.
1060    let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
1061        let Some(v_end) = kept[i_end] else {
1062            return Vec::new();
1063        };
1064        let u_end = u_of(i_end);
1065        #[allow(clippy::cast_precision_loss)]
1066        let pitch = TAU / (n_samples as f64);
1067        let u_next = if forward {
1068            u_end + pitch
1069        } else {
1070            u_end - pitch
1071        };
1072        let target = e / v_max;
1073        let h_end = n_dot_g_at(u_end) - target;
1074        let h_next = n_dot_g_at(u_next) - target;
1075        if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
1076            return Vec::new();
1077        }
1078        let (mut lo, mut hi) = (u_end, u_next);
1079        for _ in 0..60 {
1080            let mid = f64::midpoint(lo, hi);
1081            if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
1082                lo = mid;
1083            } else {
1084                hi = mid;
1085            }
1086        }
1087        let u_star = f64::midpoint(lo, hi);
1088        let tail_n = 8_usize;
1089        (1..=tail_n)
1090            .filter_map(|k| {
1091                #[allow(clippy::cast_precision_loss)]
1092                let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
1093                let ng = n_dot_g_at(u);
1094                if ng.abs() < 1e-12 {
1095                    return None;
1096                }
1097                let v = e / ng;
1098                (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
1099            })
1100            .collect()
1101    };
1102
1103    // Split into contiguous runs of kept samples, treating the array as
1104    // circular (rotate past a gap) so a branch straddling u=0 stays whole.
1105    let gap = kept.iter().position(Option::is_none).unwrap_or(0);
1106    let mut chains: Vec<Vec<Point3>> = Vec::new();
1107    let mut run: Vec<usize> = Vec::new();
1108    let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
1109        if run.len() >= 2 {
1110            let first = run[0];
1111            let last = run[run.len() - 1];
1112            let mut pts: Vec<Point3> = tail(first, false, &kept);
1113            pts.reverse();
1114            pts.extend(
1115                run.iter()
1116                    .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
1117            );
1118            pts.extend(tail(last, true, &kept));
1119            chains.push(pts);
1120        }
1121        run.clear();
1122    };
1123    for k in 0..n_samples {
1124        let idx = (gap + k) % n_samples;
1125        if kept[idx].is_some() {
1126            run.push(idx);
1127        } else {
1128            flush(&mut run, &mut chains);
1129        }
1130    }
1131    flush(&mut run, &mut chains);
1132    Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
1133}
1134
1135/// Sample the plane-torus intersection as ordered 3D points.
1136///
1137/// Uses the same closed-form loops as `intersect_plane_torus`
1138/// but skips NURBS curve fitting (the callers here only need the points).
1139#[allow(clippy::unnecessary_wraps)] // sibling match-arms and `?` callers need `Result`
1140fn sample_plane_torus(
1141    torus: &ToroidalSurface,
1142    normal: Vec3,
1143    d: f64,
1144) -> Result<Vec<Vec<Point3>>, MathError> {
1145    Ok(plane_torus_loops(torus, normal, d, 128)
1146        .into_iter()
1147        .map(|run| run.into_iter().map(|p| p.point).collect())
1148        .collect())
1149}
1150
1151/// Intersect a plane with a cylindrical surface.
1152///
1153/// For each `u` in `[0, 2pi)`, the cylinder point is linear in `v`,
1154/// so the plane equation `dot(normal, P(u,v)) = d` is linear in `v`
1155/// and can be solved directly.
1156///
1157/// # Errors
1158///
1159/// Returns an error if curve fitting fails.
1160#[allow(clippy::cast_precision_loss)]
1161pub fn intersect_plane_cylinder(
1162    cyl: &CylindricalSurface,
1163    normal: Vec3,
1164    d: f64,
1165) -> Result<Vec<IntersectionCurve>, MathError> {
1166    let n_samples = 64_usize;
1167    let mut points_3d = Vec::new();
1168    let mut ipoints = Vec::new();
1169
1170    for i in 0..=n_samples {
1171        let u = TAU * (i as f64) / (n_samples as f64);
1172        // P(u, v) = origin + r*(cos(u)*x + sin(u)*y) + v*axis
1173        // dot(normal, P) = d  =>  dot(normal, base(u)) + v * dot(normal, axis) = d
1174        let base = cyl.evaluate(u, 0.0);
1175        let n_dot_axis = normal.dot(cyl.axis());
1176        let n_dot_base = dot_np(normal, base);
1177
1178        if n_dot_axis.abs() < 1e-12 {
1179            // Plane parallel to axis -- check if base is on plane.
1180            if (n_dot_base - d).abs() < 1e-6 {
1181                let pt = base;
1182                points_3d.push(pt);
1183                ipoints.push(IntersectionPoint {
1184                    point: pt,
1185                    param1: (u, 0.0),
1186                    param2: (0.0, 0.0),
1187                });
1188            }
1189        } else {
1190            let v = (d - n_dot_base) / n_dot_axis;
1191            // Only keep points within a reasonable v range.
1192            if v.abs() <= 100.0 {
1193                let pt = cyl.evaluate(u, v);
1194                points_3d.push(pt);
1195                ipoints.push(IntersectionPoint {
1196                    point: pt,
1197                    param1: (u, v),
1198                    param2: (0.0, 0.0),
1199                });
1200            }
1201        }
1202    }
1203
1204    build_curves_from_points(&points_3d, ipoints)
1205}
1206
1207/// Intersect a plane with a spherical surface.
1208///
1209/// The intersection of a plane with a sphere is a circle (or empty/point).
1210/// Computes the circle center, radius, and samples points on it.
1211///
1212/// # Errors
1213///
1214/// Returns an error if curve fitting fails.
1215#[allow(clippy::cast_precision_loss)]
1216pub fn intersect_plane_sphere(
1217    sphere: &SphericalSurface,
1218    normal: Vec3,
1219    d: f64,
1220) -> Result<Vec<IntersectionCurve>, MathError> {
1221    let h = dot_np(normal, sphere.center()) - d;
1222    let r = sphere.radius();
1223
1224    // No intersection if plane is too far from center.
1225    if h.abs() > r - 1e-10 {
1226        return Ok(vec![]);
1227    }
1228
1229    let circle_r = (r.mul_add(r, -(h * h))).sqrt();
1230    let circle_center = Point3::new(
1231        h.mul_add(-normal.x(), sphere.center().x()),
1232        h.mul_add(-normal.y(), sphere.center().y()),
1233        h.mul_add(-normal.z(), sphere.center().z()),
1234    );
1235
1236    // Build a local frame on the plane.
1237    let basis = Frame3::from_normal(circle_center, normal)?;
1238    let u_dir = basis.x;
1239    let v_dir = basis.y;
1240
1241    let n_samples = 64_usize;
1242    let mut points_3d = Vec::new();
1243    let mut ipoints = Vec::new();
1244
1245    for i in 0..=n_samples {
1246        let theta = TAU * (i as f64) / (n_samples as f64);
1247        let (sin_t, cos_t) = theta.sin_cos();
1248        let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
1249        points_3d.push(pt);
1250        ipoints.push(IntersectionPoint {
1251            point: pt,
1252            param1: (theta, 0.0),
1253            param2: (0.0, 0.0),
1254        });
1255    }
1256
1257    build_curves_from_points(&points_3d, ipoints)
1258}
1259
1260/// Intersect a plane with a conical surface.
1261///
1262/// Like a cylinder, the cone is linear along each generatrix, so the plane
1263/// equation is linear in `v` for each fixed `u`.
1264///
1265/// # Errors
1266///
1267/// Returns an error if curve fitting fails.
1268#[allow(clippy::cast_precision_loss)]
1269pub fn intersect_plane_cone(
1270    cone: &ConicalSurface,
1271    normal: Vec3,
1272    d: f64,
1273) -> Result<Vec<IntersectionCurve>, MathError> {
1274    let n_samples = 64_usize;
1275    let mut points_3d = Vec::new();
1276    let mut ipoints = Vec::new();
1277
1278    for i in 0..n_samples {
1279        let u = TAU * (i as f64) / (n_samples as f64);
1280        // P(u, v) = apex + v * dir(u)
1281        // dot(normal, apex) + v * dot(normal, dir(u)) = d
1282        let apex = cone.apex();
1283        let n_dot_apex = dot_np(normal, apex);
1284        // dir(u) = P(u,1) - apex
1285        let p1 = cone.evaluate(u, 1.0);
1286        let dir = p1 - apex;
1287        let n_dot_dir = normal.dot(dir);
1288
1289        if n_dot_dir.abs() < 1e-12 {
1290            continue;
1291        }
1292
1293        let v = (d - n_dot_apex) / n_dot_dir;
1294        // Allow negative v — the cone surface extends in both directions from the apex.
1295        if v.abs() > 1e-10 && v.abs() < 100.0 {
1296            let pt = cone.evaluate(u, v);
1297            points_3d.push(pt);
1298            ipoints.push(IntersectionPoint {
1299                point: pt,
1300                param1: (u, v),
1301                param2: (0.0, 0.0),
1302            });
1303        }
1304    }
1305
1306    build_curves_from_points(&points_3d, ipoints)
1307}
1308
1309/// Intersect a plane with a toroidal surface.
1310///
1311/// The section is a degree-4 curve, but for each `v` the `u` values solve in
1312/// closed form (see `plane_torus_loops`), so it is sampled by a v-scan
1313/// and each loop is fitted to a NURBS curve.
1314///
1315/// # Errors
1316///
1317/// Never returns an error today (curve-fit failures drop the affected loop);
1318/// the `Result` is kept for signature parity with the other plane-analytic
1319/// intersectors.
1320#[allow(clippy::unnecessary_wraps)]
1321pub fn intersect_plane_torus(
1322    torus: &ToroidalSurface,
1323    normal: Vec3,
1324    d: f64,
1325) -> Result<Vec<IntersectionCurve>, MathError> {
1326    // The section satisfies a per-v closed form (see `plane_torus_loops`),
1327    // so scan v and solve u directly instead of a 2D sign-change grid with
1328    // Newton refinement: O(n) rather than O(n²), and every point is exact.
1329    let mut curves = Vec::new();
1330    for ipts in plane_torus_loops(torus, normal, d, 128) {
1331        let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
1332        if let Ok(curve) = interpolate(&pts, 3.min(pts.len() - 1)) {
1333            curves.push(IntersectionCurve {
1334                curve,
1335                points: ipts,
1336            });
1337        }
1338    }
1339
1340    Ok(curves)
1341}
1342
1343/// The fewest and most steps along each branch of a loop a plane cuts from
1344/// a torus between its two turns.
1345const PLANE_TORUS_LOOP_SAMPLES: (f64, f64) = (24.0, 512.0);
1346
1347/// The loops a plane cuts from a torus, each as points on the torus in
1348/// order, closed by repeating its first point.
1349///
1350/// In the torus's own frame let `a = n·X`, `b = n·Y`, `c = n·Z`,
1351/// `s = hypot(a, b)`, `phi = atan2(b, a)`. Substituting the torus
1352/// parameterization into `n·P = d` gives
1353///   `(R + r·cos v)·s·cos(u − phi) + r·c·sin v = d − n·center`,
1354/// so at each tube angle `v` where `|rhs(v)| <= 1`, with
1355/// `rhs(v) = (d − n·center − r·c·sin v) / (s·(R + r·cos v))`, the section's
1356/// two branches are `u = phi ± acos(rhs(v))`. Each run of `v` where the
1357/// section exists is one loop: out along one branch to where the run ends
1358/// and the branches meet, and back along the other. A section present at
1359/// every `v` is two loops winding the tube, one per branch. Every point
1360/// comes from the closed form, so the loops need no chaining.
1361///
1362/// Where the branches touch inside a run (a plane tangent to the tube's
1363/// inner side, at a saddle) the section crosses itself: each branch passes
1364/// through that node, and each loop there starts and ends on it.
1365///
1366/// When `s ≈ 0` the plane is perpendicular to the axis and the section is up
1367/// to two full circles at the `v` values solving `r·c·sin v = d − n·center`,
1368/// sampled by scanning `u`.
1369#[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
1370fn plane_torus_loops(
1371    torus: &ToroidalSurface,
1372    normal: Vec3,
1373    d: f64,
1374    n_v: usize,
1375) -> Vec<Vec<IntersectionPoint>> {
1376    let big_r = torus.major_radius();
1377    let small_r = torus.minor_radius();
1378    let a = normal.dot(torus.x_axis());
1379    let b = normal.dot(torus.y_axis());
1380    let c = normal.dot(torus.z_axis());
1381    let s = a.hypot(b);
1382    let phi = b.atan2(a);
1383    let d_local = d - dot_np(normal, torus.center());
1384    let point = |u: f64, v: f64| IntersectionPoint {
1385        point: torus.evaluate(u, v),
1386        param1: (u, v.rem_euclid(TAU)),
1387        param2: (0.0, 0.0),
1388    };
1389    let closed = |mut run: Vec<IntersectionPoint>| {
1390        run.push(run[0]);
1391        run
1392    };
1393
1394    // Plane perpendicular to the axis: the section is up to two full circles.
1395    if s < 1e-12 {
1396        if c.abs() < 1e-12 {
1397            return Vec::new();
1398        }
1399        let sin_v = d_local / (small_r * c);
1400        if sin_v.abs() > 1.0 + 1e-9 {
1401            return Vec::new();
1402        }
1403        let v0 = sin_v.clamp(-1.0, 1.0).asin();
1404        let v1 = std::f64::consts::PI - v0;
1405        let mut vs = vec![v0];
1406        // Skip the mirror circle when the plane is tangent: at the tube's top
1407        // v0 == v1, and at its bottom they differ by a whole turn.
1408        let apart = (v1 - v0).rem_euclid(TAU);
1409        if apart.min(TAU - apart) > 1e-9 {
1410            vs.push(v1);
1411        }
1412        return vs
1413            .into_iter()
1414            .map(|v| {
1415                closed(
1416                    (0..n_v)
1417                        .map(|i| point(TAU * (i as f64) / (n_v as f64), v))
1418                        .collect(),
1419                )
1420            })
1421            .collect();
1422    }
1423
1424    // The scan is offset by half a step so it never lands on a node where
1425    // the branches touch (the inner-tangent figure-eight at v = π).
1426    let step = TAU / (n_v as f64);
1427    let v_off = step * 0.5;
1428    // R + r·cos v > 0 on a ring torus.
1429    let rhs_at = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.mul_add(v.cos(), big_r));
1430    let branch = |v: f64, sign: f64| point(sign.mul_add(rhs_at(v).clamp(-1.0, 1.0).acos(), phi), v);
1431    let inside = |v: f64| rhs_at(v).abs() <= 1.0;
1432    // The largest |rhs| between two samples, and where.
1433    let peak = |lo: f64, hi: f64| {
1434        let golden = 0.5 * (5.0_f64.sqrt() - 1.0);
1435        let (mut lo, mut hi) = (lo, hi);
1436        for _ in 0..80 {
1437            let (m1, m2) = (hi - golden * (hi - lo), lo + golden * (hi - lo));
1438            if rhs_at(m1).abs() > rhs_at(m2).abs() {
1439                hi = m2;
1440            } else {
1441                lo = m1;
1442            }
1443        }
1444        let v = f64::midpoint(lo, hi);
1445        (v, rhs_at(v).abs())
1446    };
1447    // A gap in the section narrower than a step (a plane just past tangent
1448    // to the tube's inner side) can fall between two samples inside it:
1449    // its peak joins the scan as a sample outside.
1450    let mut scan: Vec<f64> = Vec::with_capacity(n_v + 2);
1451    for i in 0..n_v {
1452        let v = (i as f64).mul_add(step, v_off);
1453        scan.push(v);
1454        if inside(v) && inside(v + step) {
1455            let (at, top) = peak(v, v + step);
1456            if top > 1.0 + 1e-12 {
1457                scan.push(at);
1458            }
1459        }
1460    }
1461    let n = scan.len();
1462    // Sample `i` of the scan, its `v` carried a turn on for each pass round.
1463    #[allow(clippy::cast_possible_wrap)]
1464    let scan_v = |i: isize| {
1465        let len = n as isize;
1466        scan[i.rem_euclid(len) as usize] + TAU * (i.div_euclid(len) as f64)
1467    };
1468    // Where |rhs| reaches 1 between two samples inside the section, without
1469    // passing it: the branches touch there.
1470    let touch_at = |lo: f64, hi: f64| {
1471        let (v, top) = peak(lo, hi);
1472        ((top - 1.0).abs() < 1e-12).then_some(v)
1473    };
1474    // Both branches meet at the node, where `acos` is 0 or π.
1475    let node = |v: f64| {
1476        let u = if rhs_at(v) > 0.0 {
1477            phi
1478        } else {
1479            phi + std::f64::consts::PI
1480        };
1481        point(u, v)
1482    };
1483    // Where the section's run ends between an inside and an outside sample.
1484    let turn = |v_in: f64, v_out: f64| {
1485        let (mut lo, mut hi) = (v_in, v_out);
1486        for _ in 0..60 {
1487            let mid = f64::midpoint(lo, hi);
1488            if inside(mid) {
1489                lo = mid;
1490            } else {
1491                hi = mid;
1492            }
1493        }
1494        lo
1495    };
1496    let in_scan: Vec<bool> = scan.iter().map(|&v| inside(v)).collect();
1497    #[allow(clippy::cast_possible_wrap)]
1498    if in_scan.iter().all(|&x| x) {
1499        let at_node = (0..n as isize).find_map(|i| touch_at(scan_v(i), scan_v(i + 1)));
1500        return [1.0, -1.0]
1501            .into_iter()
1502            .map(|sign| match at_node {
1503                Some(v_node) => {
1504                    let mut run = vec![node(v_node)];
1505                    run.extend((1..n_v).map(|i| branch((i as f64).mul_add(step, v_node), sign)));
1506                    closed(run)
1507                }
1508                None => closed(scan.iter().map(|&v| branch(v, sign)).collect()),
1509            })
1510            .collect();
1511    }
1512    let Some(first) = (0..n).find(|&i| in_scan[i] && !in_scan[(i + n - 1) % n]) else {
1513        return Vec::new();
1514    };
1515    let mut loops = Vec::new();
1516    let mut k = 0;
1517    while k < n {
1518        let i = (first + k) % n;
1519        if !in_scan[i] {
1520            k += 1;
1521            continue;
1522        }
1523        // The run from scan sample `i`, its `v` unwrapped past a turn.
1524        let len = (0..n - k).take_while(|&j| in_scan[(i + j) % n]).count();
1525        #[allow(clippy::cast_possible_wrap)]
1526        let run_v = |j: isize| scan_v(i as isize + j);
1527        #[allow(clippy::cast_possible_wrap)]
1528        let last = len as isize - 1;
1529        let (t_lo, t_hi) = (
1530            turn(run_v(0), run_v(-1)),
1531            turn(run_v(last), run_v(last + 1)),
1532        );
1533        let at_node = (0..last).find_map(|j| touch_at(run_v(j), run_v(j + 1)));
1534        // `u` moves like the square root of the distance in `v` to a turn, so
1535        // the loop is sampled at `v = t_lo + (t_hi - t_lo) (1 - cos θ) / 2`
1536        // for even steps of `θ`: `v` then moves like `θ²` at each turn and the
1537        // points fall at near-even steps along the curve, turns included. A
1538        // loop that sweeps far round the axis on a short run of `v` (a plane
1539        // through the centre, tilted a little) takes a step per half scan
1540        // step of `u` its branches sweep.
1541        let (u_lo, u_hi) = (0..=last)
1542            .map(run_v)
1543            .chain([t_lo, t_hi])
1544            .map(|v| rhs_at(v).clamp(-1.0, 1.0).acos())
1545            .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), u| {
1546                (lo.min(u), hi.max(u))
1547            });
1548        let m = (len as f64)
1549            .max((n_v as f64) * (u_hi - u_lo) / std::f64::consts::PI)
1550            .max(PLANE_TORUS_LOOP_SAMPLES.0)
1551            .min(PLANE_TORUS_LOOP_SAMPLES.1)
1552            .ceil();
1553        let at = |k: f64| {
1554            let f = 0.5 * (1.0 - (std::f64::consts::PI * k / m).cos());
1555            (t_hi - t_lo).mul_add(f, t_lo)
1556        };
1557        let steps = m as usize;
1558        if let Some(v_node) = at_node {
1559            // Out along one branch from the node to a turn and back along the
1560            // other, once each side of the node.
1561            for (from, to) in [(v_node, t_lo), (v_node, t_hi)] {
1562                let along = |k: usize| {
1563                    let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1564                    (to - from).mul_add(f, from)
1565                };
1566                let mut pts = vec![node(v_node)];
1567                pts.extend((1..=steps).map(|k| branch(along(k), 1.0)));
1568                pts.extend((1..steps).rev().map(|k| branch(along(k), -1.0)));
1569                loops.push(closed(pts));
1570            }
1571        } else {
1572            let mut pts: Vec<IntersectionPoint> =
1573                (0..=steps).map(|k| branch(at(k as f64), 1.0)).collect();
1574            pts.extend((1..steps).rev().map(|k| branch(at(k as f64), -1.0)));
1575            loops.push(closed(pts));
1576        }
1577        k += len;
1578    }
1579    loops
1580}
1581
1582/// The two sections of a plane that crosses every tube cross-section of a
1583/// torus twice (one parallel to the axis within `R − r` of it, or tilted a
1584/// little from that): both branches `u = phi ± acos(rhs(v))` of
1585/// [`plane_torus_loops`] are then defined for every `v`, so each closes
1586/// into a loop that winds once around the tube. Sampled at `n_v` steps from
1587/// `v = 0`, the outer equator, so every such loop on a torus starts on one
1588/// latitude, as the tube cross-sections of a plane through the axis do.
1589/// `None` when a branch lapses somewhere or the two come close to meeting.
1590#[allow(clippy::cast_precision_loss)]
1591fn plane_torus_winding_loops(
1592    torus: &ToroidalSurface,
1593    normal: Vec3,
1594    d: f64,
1595    n_v: usize,
1596) -> Option<Vec<Vec<Point3>>> {
1597    let big_r = torus.major_radius();
1598    let small_r = torus.minor_radius();
1599    let a = normal.dot(torus.x_axis());
1600    let b = normal.dot(torus.y_axis());
1601    let c = normal.dot(torus.z_axis());
1602    let s = a.hypot(b);
1603    if s < 1e-12 * normal.length() || small_r >= big_r {
1604        return None;
1605    }
1606    let phi = b.atan2(a);
1607    let d_local = d - dot_np(normal, torus.center());
1608    let rhs = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.mul_add(v.cos(), big_r));
1609    let dense = 8 * n_v;
1610    if (0..dense).any(|i| rhs(TAU * i as f64 / dense as f64).abs() > 1.0 - 1e-3) {
1611        return None;
1612    }
1613    let mut loops = [Vec::with_capacity(n_v + 1), Vec::with_capacity(n_v + 1)];
1614    for i in 0..n_v {
1615        let v = TAU * i as f64 / n_v as f64;
1616        let delta = rhs(v).acos();
1617        loops[0].push(torus.evaluate(phi + delta, v));
1618        loops[1].push(torus.evaluate(phi - delta, v));
1619    }
1620    Some(
1621        loops
1622            .into_iter()
1623            .map(|mut run| {
1624                run.push(run[0]);
1625                run
1626            })
1627            .collect(),
1628    )
1629}
1630
1631/// Real intersection parameters `t` of the line `origin + t·dir` with a torus.
1632///
1633/// A line meets a torus in up to four points (degree-4). Substituting the line
1634/// into the torus implicit `(a² + b² + c² + R² − r²)² = 4R²(a² + b²)` — where
1635/// `(a, b, c)` are the line point's coordinates in the torus frame — gives a
1636/// quartic in `t`, solved here for its real roots, each refined by Newton steps
1637/// on the tube it lies nearer (on a spindle torus, the near tube or the one
1638/// swung across the axis). `dir` need not be unit length; `t` is in units of
1639/// `dir`. Returns the roots sorted ascending (0–4 of them).
1640///
1641/// Used by the boolean section trimmer to find where a plane×torus oval exits a
1642/// box face's straight boundary edge — the exact crossing shared by the two
1643/// adjacent faces, which is what makes the notch watertight.
1644#[must_use]
1645pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1646    let c = torus.center();
1647    let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1648    let big_r = torus.major_radius();
1649    let small_r = torus.minor_radius();
1650
1651    // Line point in torus frame: a(t)=a0+a1 t, b(t)=b0+b1 t, c(t)=c0+c1 t.
1652    let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1653    let (a0, a1) = (xa.dot(o), xa.dot(dir));
1654    let (b0, b1) = (ya.dot(o), ya.dot(dir));
1655    let (c0, c1) = (za.dot(o), za.dot(dir));
1656
1657    // G(t) = a² + b² + c² + R² − r²  (quadratic: g2 t² + g1 t + g0)
1658    let g2 = a1.mul_add(a1, b1.mul_add(b1, c1 * c1));
1659    let g1 = 2.0 * a1.mul_add(a0, b1.mul_add(b0, c1 * c0));
1660    let g0 = a0.mul_add(
1661        a0,
1662        b0.mul_add(b0, c0.mul_add(c0, big_r.mul_add(big_r, -small_r * small_r))),
1663    );
1664
1665    // H(t) = 4R² (a² + b²)  (quadratic: h2 t² + h1 t + h0)
1666    let four_rr = 4.0 * big_r * big_r;
1667    let h2 = four_rr * a1.mul_add(a1, b1 * b1);
1668    let h1 = four_rr * (2.0 * a1.mul_add(a0, b1 * b0));
1669    let h0 = four_rr * a0.mul_add(a0, b0 * b0);
1670
1671    // Quartic G² − H = 0:  e4 t⁴ + e3 t³ + e2 t² + e1 t + e0.
1672    let e4 = g2 * g2;
1673    let e3 = 2.0 * g2 * g1;
1674    let e2 = g1.mul_add(g1, 2.0 * g2 * g0) - h2;
1675    let e1 = 2.0f64.mul_add(g1 * g0, -h1);
1676    let e0 = g0.mul_add(g0, -h0);
1677
1678    let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1679    // The quartic also holds a spindle torus's tube swung across the axis
1680    // (`G = -sqrt(H)`), whose roots pair up with the tube's own a few hundredths
1681    // apart when `R` is small: the solver leaves them loose, and polishing one
1682    // against the near tube carries it beside the other root. Each root is
1683    // polished on the tube it lies nearer.
1684    let tube = |t: f64, across: bool| -> f64 {
1685        let p = origin + dir * t;
1686        let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1687        let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1688        let centre = if across { -big_r } else { big_r };
1689        (a.hypot(b) - centre).hypot(cc) - small_r
1690    };
1691    for t in &mut roots {
1692        let across = big_r < small_r && tube(*t, true).abs() < tube(*t, false).abs();
1693        for _ in 0..8 {
1694            let eps = 1e-7;
1695            let f = tube(*t, across);
1696            let df = (tube(*t + eps, across) - tube(*t - eps, across)) / (2.0 * eps);
1697            if df.abs() <= 1e-12 {
1698                break;
1699            }
1700            let step = f / df;
1701            *t -= step;
1702            if step.abs() < 1e-14 * (1.0 + t.abs()) {
1703                break;
1704            }
1705        }
1706    }
1707    roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1708    roots.dedup_by(|a, b| (*a - *b).abs() < 1e-9 * (1.0 + b.abs()));
1709    roots
1710}
1711
1712/// Real roots of `c4 x⁴ + c3 x³ + c2 x² + c1 x + c0` via Durand–Kerner, falling
1713/// back to the lower-degree solvers when the leading coefficients vanish.
1714fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
1715    // Degenerate leading coefficient → lower degree.
1716    if c4.abs() < 1e-14 {
1717        return real_roots_cubic(c3, c2, c1, c0);
1718    }
1719    // Monic: x⁴ + a x³ + b x² + c x + d.
1720    let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
1721    let eval = |z: Complex| -> Complex {
1722        // Horner.
1723        let mut acc = Complex::new(1.0, 0.0);
1724        acc = acc * z + Complex::new(a, 0.0);
1725        acc = acc * z + Complex::new(b, 0.0);
1726        acc = acc * z + Complex::new(c, 0.0);
1727        acc * z + Complex::new(d, 0.0)
1728    };
1729    // Durand–Kerner: four roots seeded on a circle, iterated to convergence.
1730    let seed = Complex::new(0.4, 0.9);
1731    let mut r = [
1732        Complex::new(1.0, 0.0),
1733        seed,
1734        seed * seed,
1735        seed * seed * seed,
1736    ];
1737    for _ in 0..100 {
1738        let mut max_step = 0.0_f64;
1739        for i in 0..4 {
1740            let mut denom = Complex::new(1.0, 0.0);
1741            for j in 0..4 {
1742                if i != j {
1743                    denom = denom * (r[i] - r[j]);
1744                }
1745            }
1746            if denom.norm() < 1e-300 {
1747                continue;
1748            }
1749            let step = eval(r[i]) / denom;
1750            r[i] = r[i] - step;
1751            max_step = max_step.max(step.norm());
1752        }
1753        if max_step < 1e-14 {
1754            break;
1755        }
1756    }
1757    // Keep roots with negligible imaginary part AND a small REAL-polynomial
1758    // residual — Durand–Kerner stops after a fixed iteration cap whether or not
1759    // it converged, so a non-converged iterate could otherwise be returned as a
1760    // spurious root. Evaluate the monic quartic at each candidate (real part) and
1761    // keep only |p(x)| below a magnitude-scaled tolerance; de-dup near-equal
1762    // roots (a double root converges to two near-identical iterates).
1763    let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
1764    let mut out: Vec<f64> = Vec::new();
1765    for z in r {
1766        if z.im.abs() >= 1e-7 {
1767            continue;
1768        }
1769        let x = z.re;
1770        // Residual tolerance scales with the polynomial's coefficient magnitude
1771        // and |x|^4 so large-coefficient quartics are not over-rejected.
1772        let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
1773        if p_real(x).abs() > 1e-6 * scale {
1774            continue;
1775        }
1776        if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
1777            continue;
1778        }
1779        out.push(x);
1780    }
1781    out
1782}
1783
1784/// Real roots of `a x³ + b x² + c x + d` (Cardano), with quadratic fallback.
1785fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
1786    if a.abs() < 1e-14 {
1787        return real_roots_quadratic(b, c, d);
1788    }
1789    // Depressed cubic t³ + p t + q via x = t − b/(3a).
1790    let (b, c, d) = (b / a, c / a, d / a);
1791    let p = c - b * b / 3.0;
1792    let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
1793    let shift = -b / 3.0;
1794    let disc = q * q / 4.0 + p * p * p / 27.0;
1795    if disc > 1e-14 {
1796        let sq = disc.sqrt();
1797        let u = (-q / 2.0 + sq).cbrt();
1798        let v = (-q / 2.0 - sq).cbrt();
1799        vec![u + v + shift]
1800    } else if disc < -1e-14 {
1801        // Three real roots (trigonometric).
1802        let m = 2.0 * (-p / 3.0).sqrt();
1803        let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
1804        (0..3)
1805            .map(|k| {
1806                m.mul_add(
1807                    (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
1808                    shift,
1809                )
1810            })
1811            .collect()
1812    } else {
1813        // Repeated roots.
1814        let u = (-q / 2.0).cbrt();
1815        vec![2.0 * u + shift, -u + shift]
1816    }
1817}
1818
1819/// Real roots of `a x² + b x + c`, with linear fallback.
1820fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
1821    if a.abs() < 1e-14 {
1822        if b.abs() < 1e-14 {
1823            return Vec::new();
1824        }
1825        return vec![-c / b];
1826    }
1827    let disc = b * b - 4.0 * a * c;
1828    if disc < 0.0 {
1829        Vec::new()
1830    } else {
1831        let sq = disc.sqrt();
1832        vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
1833    }
1834}
1835
1836/// Minimal complex number for the quartic root finder.
1837#[derive(Clone, Copy)]
1838struct Complex {
1839    re: f64,
1840    im: f64,
1841}
1842
1843impl Complex {
1844    const fn new(re: f64, im: f64) -> Self {
1845        Self { re, im }
1846    }
1847    fn norm(self) -> f64 {
1848        self.re.hypot(self.im)
1849    }
1850}
1851
1852impl std::ops::Add for Complex {
1853    type Output = Self;
1854    fn add(self, o: Self) -> Self {
1855        Self::new(self.re + o.re, self.im + o.im)
1856    }
1857}
1858
1859impl std::ops::Sub for Complex {
1860    type Output = Self;
1861    fn sub(self, o: Self) -> Self {
1862        Self::new(self.re - o.re, self.im - o.im)
1863    }
1864}
1865
1866impl std::ops::Mul for Complex {
1867    type Output = Self;
1868    fn mul(self, o: Self) -> Self {
1869        Self::new(
1870            self.re.mul_add(o.re, -(self.im * o.im)),
1871            self.re.mul_add(o.im, self.im * o.re),
1872        )
1873    }
1874}
1875
1876impl std::ops::Div for Complex {
1877    type Output = Self;
1878    fn div(self, o: Self) -> Self {
1879        let den = o.re.mul_add(o.re, o.im * o.im);
1880        Self::new(
1881            self.re.mul_add(o.re, self.im * o.im) / den,
1882            self.im.mul_add(o.re, -(self.re * o.im)) / den,
1883        )
1884    }
1885}
1886
1887/// Build intersection curves from a collection of ordered 3D points.
1888///
1889/// If there are enough points, fits a NURBS curve through them.
1890fn build_curves_from_points(
1891    points_3d: &[Point3],
1892    ipoints: Vec<IntersectionPoint>,
1893) -> Result<Vec<IntersectionCurve>, MathError> {
1894    if points_3d.len() < 2 {
1895        return Ok(vec![]);
1896    }
1897
1898    let degree = 3.min(points_3d.len() - 1);
1899    let curve = interpolate(points_3d, degree)?;
1900    Ok(vec![IntersectionCurve {
1901        curve,
1902        points: ipoints,
1903    }])
1904}
1905
1906// -- Analytic-Analytic Intersection -------------------------------------------
1907
1908/// Intersect two analytic surfaces using a general marching approach.
1909///
1910/// Seeds intersection points by sampling both parameter spaces on a grid,
1911/// then marches along the intersection curve using the cross product of
1912/// the two surface normals as the tangent direction.
1913///
1914/// # Errors
1915///
1916/// Returns an error if curve fitting fails.
1917#[allow(
1918    clippy::cast_precision_loss,
1919    clippy::too_many_lines,
1920    clippy::similar_names,
1921    clippy::unnecessary_wraps,
1922    clippy::type_complexity
1923)]
1924pub fn intersect_analytic_analytic(
1925    a: AnalyticSurface<'_>,
1926    b: AnalyticSurface<'_>,
1927    grid_res: usize,
1928) -> Result<Vec<IntersectionCurve>, MathError> {
1929    intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
1930}
1931
1932/// Intersect two analytic surfaces with optional v-range overrides.
1933///
1934/// When `v_range_hint_a` or `v_range_hint_b` is `Some((min, max))`, the
1935/// marching algorithm searches that v-range instead of the hardcoded default.
1936/// This is essential for cylinders and cones whose default v-range is small
1937/// (-1..1 or 0.01..2) but whose actual face may extend much further.
1938///
1939/// # Errors
1940///
1941/// Returns `MathError` if algebraic intersection fails or marching diverges.
1942pub fn intersect_analytic_analytic_bounded(
1943    a: AnalyticSurface<'_>,
1944    b: AnalyticSurface<'_>,
1945    grid_res: usize,
1946    v_range_hint_a: Option<(f64, f64)>,
1947    v_range_hint_b: Option<(f64, f64)>,
1948) -> Result<Vec<IntersectionCurve>, MathError> {
1949    intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, None)
1950}
1951
1952/// [`intersect_analytic_analytic_bounded`] with its general marcher confined
1953/// to `region`.
1954///
1955/// The marcher starts only from seeds that converge into the region (with a
1956/// margin of about two grid cells) and stops where a curve leaves it. Pairs
1957/// solved in closed form are returned whole, as by the unconfined call. Two
1958/// bounded faces meet only inside both their boxes, so their overlap is a
1959/// sound region for a face pair.
1960///
1961/// # Errors
1962///
1963/// Returns `MathError` if algebraic intersection fails or marching diverges.
1964pub fn intersect_analytic_analytic_in_region(
1965    a: AnalyticSurface<'_>,
1966    b: AnalyticSurface<'_>,
1967    grid_res: usize,
1968    v_range_hint_a: Option<(f64, f64)>,
1969    v_range_hint_b: Option<(f64, f64)>,
1970    region: Aabb3,
1971) -> Result<Vec<IntersectionCurve>, MathError> {
1972    intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, Some(region))
1973}
1974
1975fn intersect_analytic_analytic_impl(
1976    a: AnalyticSurface<'_>,
1977    b: AnalyticSurface<'_>,
1978    grid_res: usize,
1979    v_range_hint_a: Option<(f64, f64)>,
1980    v_range_hint_b: Option<(f64, f64)>,
1981    region: Option<Aabb3>,
1982) -> Result<Vec<IntersectionCurve>, MathError> {
1983    // Try algebraic specialization for known surface pairs before falling
1984    // back to the general marching approach.
1985    if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
1986        return Ok(result);
1987    }
1988
1989    let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
1990    let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
1991    let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
1992    let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
1993
1994    // Compute characteristic surface dimensions for adaptive parameters.
1995    let diag_a = {
1996        let p00 = surf_a(u_range_a.0, v_range_a.0);
1997        let p11 = surf_a(u_range_a.1, v_range_a.1);
1998        (p00 - p11).length()
1999    };
2000    let diag_b = {
2001        let p00 = surf_b(u_range_b.0, v_range_b.0);
2002        let p11 = surf_b(u_range_b.1, v_range_b.1);
2003        (p00 - p11).length()
2004    };
2005    let char_size = diag_a.min(diag_b).max(0.1);
2006
2007    // Sample surface A on a grid. For each grid point, project it
2008    // analytically onto surface B to find the closest point, then check
2009    // if the distance is below threshold (indicating near-intersection).
2010    #[allow(clippy::type_complexity)]
2011    let mut seeds: Vec<(Point3, (f64, f64), (f64, f64))> = Vec::new();
2012    // Coarse threshold scales with the surface size — the distance from
2013    // a grid point on A to its projection on B can be large even near
2014    // the intersection (e.g., sphere R=2 and cylinder R=1 → gap ≈ 1).
2015    let seed_threshold = diag_a.max(diag_b).max(1.0) * 0.5;
2016    let mut min_dist = f64::INFINITY;
2017
2018    #[allow(clippy::cast_precision_loss)]
2019    for ia in 0..grid_res {
2020        for ja in 0..grid_res {
2021            let ua =
2022                u_range_a.0 + (u_range_a.1 - u_range_a.0) * (ia as f64 + 0.5) / (grid_res as f64);
2023            let va =
2024                v_range_a.0 + (v_range_a.1 - v_range_a.0) * (ja as f64 + 0.5) / (grid_res as f64);
2025
2026            let pa = surf_a(ua, va);
2027
2028            // Analytically project onto surface B.
2029            let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2030            let pb = surf_b(ub, vb);
2031            let dist = (pa - pb).length();
2032            min_dist = min_dist.min(dist);
2033
2034            if dist < seed_threshold {
2035                // Use the coarse seed directly. The marching algorithm
2036                // corrects positions at each step via projection, so seeds
2037                // don't need to be on the exact intersection — they just
2038                // need to be close enough for the marcher to converge.
2039                let mid = Point3::new(
2040                    (pa.x() + pb.x()) * 0.5,
2041                    (pa.y() + pb.y()) * 0.5,
2042                    (pa.z() + pb.z()) * 0.5,
2043                );
2044                seeds.push((mid, (ua, va), (ub, vb)));
2045            }
2046        }
2047    }
2048
2049    // Cheap rejection: the grid samples surface A; the closest sample's
2050    // distance to B lower-bounds how near the two bounded patches come. A
2051    // transversal crossing puts a sample within ~one grid cell of it
2052    // (distance on the order of a cell), so if even the nearest sample is
2053    // several cells away the patches cannot cross — skip the expensive
2054    // marching and return empty. Result-preserving: non-crossing pairs
2055    // already march to nothing, just slowly (this is the gridfinity lip's
2056    // ~80 inner-wall × outer-wall pairs that dominate pavefiller time).
2057    let reject_dist = (char_size / grid_res as f64) * 3.0;
2058    if min_dist > reject_dist {
2059        return Ok(vec![]);
2060    }
2061
2062    if seeds.is_empty() {
2063        return Ok(vec![]);
2064    }
2065
2066    // Aggressively deduplicate seeds — we only need 1-2 per intersection
2067    // branch. Scale dedup radius to ~2% of characteristic surface size
2068    // (at least 10× the march step size) to avoid redundant marches.
2069    let march_step = (char_size * 0.02).clamp(0.005, 0.5);
2070    let dedup_radius = march_step * 10.0;
2071    let mut unique_seeds = Vec::new();
2072    for seed in &seeds {
2073        let dominated = unique_seeds
2074            .iter()
2075            .any(|s: &(Point3, (f64, f64), (f64, f64))| (s.0 - seed.0).length() < dedup_radius);
2076        if !dominated {
2077            unique_seeds.push(*seed);
2078        }
2079    }
2080
2081    // A seed is only near the intersection; settle it onto the curve before
2082    // asking whether it lies in the region, so a coarse grid point beside a
2083    // short in-region span still starts its march, and march from there, so
2084    // the march does not begin outside the region and stop at once.
2085    let region = region.map(|r| r.expanded(2.0 * char_size / grid_res as f64));
2086    if let Some(r) = region {
2087        for seed in &mut unique_seeds {
2088            let mut p = seed.0;
2089            for _ in 0..8 {
2090                let (ua, va) = project_analytic(&a, p, u_range_a, v_range_a);
2091                let pa = surf_a(ua, va);
2092                let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2093                let pb = surf_b(ub, vb);
2094                p = Point3::new(
2095                    (pa.x() + pb.x()) * 0.5,
2096                    (pa.y() + pb.y()) * 0.5,
2097                    (pa.z() + pb.z()) * 0.5,
2098                );
2099                if (pa - pb).length() < 1e-9 {
2100                    break;
2101                }
2102            }
2103            seed.0 = p;
2104        }
2105        unique_seeds.retain(|seed| r.contains_point(seed.0));
2106    }
2107
2108    // March from each seed.
2109    let mut curves = Vec::new();
2110    let mut used_seeds = vec![false; unique_seeds.len()];
2111
2112    for si in 0..unique_seeds.len() {
2113        if used_seeds[si] {
2114            continue;
2115        }
2116        used_seeds[si] = true;
2117
2118        let march_result = march_analytic_intersection(
2119            &a,
2120            &b,
2121            surf_a.as_ref(),
2122            norm_a.as_ref(),
2123            surf_b.as_ref(),
2124            norm_b.as_ref(),
2125            unique_seeds[si].0,
2126            u_range_a,
2127            v_range_a,
2128            u_range_b,
2129            v_range_b,
2130            march_step,
2131            is_u_periodic(&a),
2132            is_u_periodic(&b),
2133            region,
2134        );
2135
2136        if march_result.len() >= 2 {
2137            for (sj, other) in unique_seeds.iter().enumerate() {
2138                if !used_seeds[sj]
2139                    && march_result
2140                        .iter()
2141                        .any(|p| (*p - other.0).length() < dedup_radius)
2142                {
2143                    used_seeds[sj] = true;
2144                }
2145            }
2146
2147            let ipts: Vec<IntersectionPoint> = march_result
2148                .iter()
2149                .map(|&pt| IntersectionPoint {
2150                    point: pt,
2151                    param1: (0.0, 0.0),
2152                    param2: (0.0, 0.0),
2153                })
2154                .collect();
2155
2156            let degree = 3.min(march_result.len() - 1);
2157            if let Ok(curve) = interpolate(&march_result, degree) {
2158                curves.push(IntersectionCurve {
2159                    curve,
2160                    points: ipts,
2161                });
2162            }
2163        }
2164    }
2165
2166    Ok(curves)
2167}
2168
2169/// Try algebraic (closed-form or semi-algebraic) intersection for known
2170/// surface pairs before falling back to general marching.
2171///
2172/// Returns `Some(curves)` if a specialized method exists, `None` otherwise.
2173///
2174/// Currently handles:
2175/// - **Sphere-sphere**: intersection is a circle (plane through the two centers)
2176/// - **Coaxial cylinders**: same axis → circle(s) or empty
2177/// - **Sphere-cylinder**: reduce to quadratic in one parameter
2178/// - **Cone-cylinder**: parallel axes in the cone's own `v`, other axes
2179///   along the cylinder's rulings
2180/// - **Cone-sphere**: off the cone's axis, along the cone's generators
2181/// - **Torus-cylinder**: along the cylinder's rulings
2182#[allow(clippy::too_many_lines)]
2183fn try_algebraic_intersection(
2184    a: &AnalyticSurface<'_>,
2185    b: &AnalyticSurface<'_>,
2186    v_range_a: Option<(f64, f64)>,
2187    v_range_b: Option<(f64, f64)>,
2188) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2189    match (a, b) {
2190        (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => Ok(
2191            algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)?
2192                .or_else(|| ruling_cone_cylinder(cone, cyl, true)),
2193        ),
2194        (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => Ok(
2195            algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)?
2196                .or_else(|| ruling_cone_cylinder(cone, cyl, false)),
2197        ),
2198        (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
2199            algebraic_sphere_sphere(s1, s2).map(Some)
2200        }
2201        (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
2202            let axis_dot = c1.axis().dot(c2.axis()).abs();
2203            if axis_dot > 1.0 - 1e-10 {
2204                // Axes are parallel — check if they're the same line.
2205                let delta = c2.origin() - c1.origin();
2206                let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2207                let along = delta_vec.dot(c1.axis());
2208                let perp = (delta_vec - c1.axis() * along).length();
2209                if perp < 1e-8 {
2210                    // Coaxial: same axis, different radii → no intersection
2211                    // (unless equal radius → degenerate overlap, skip)
2212                    if (c1.radius() - c2.radius()).abs() < 1e-8 {
2213                        return Ok(None); // Overlapping — let marcher handle
2214                    }
2215                    return Ok(Some(vec![])); // Coaxial, different radii
2216                }
2217                if let Some(rulings) = parallel_cylinders(c1, c2, v_range_a, v_range_b)? {
2218                    return Ok(Some(rulings));
2219                }
2220            }
2221            // Non-coaxial: algebraic quadratic in v.
2222            algebraic_cylinder_cylinder(c1, c2)
2223        }
2224        // Sphere-cylinder (both orderings).
2225        (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c)) => {
2226            algebraic_sphere_cylinder(s, c, true)
2227        }
2228        (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
2229            algebraic_sphere_cylinder(s, c, false)
2230        }
2231        (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => algebraic_cone_cone(c1, c2),
2232        (AnalyticSurface::Cone(cone), AnalyticSurface::Sphere(sphere)) => {
2233            Ok(ruling_cone_sphere(cone, sphere, true))
2234        }
2235        (AnalyticSurface::Sphere(sphere), AnalyticSurface::Cone(cone)) => {
2236            Ok(ruling_cone_sphere(cone, sphere, false))
2237        }
2238        (AnalyticSurface::Torus(t), AnalyticSurface::Cylinder(c)) => {
2239            if let Some(exacts) = exact_cylinder_torus(c, t)? {
2240                return exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p)))
2241                    .map(Some);
2242            }
2243            Ok(parallel_axis_torus_cylinder(t, c, true)
2244                .or_else(|| ruling_torus_cylinder(t, c, true)))
2245        }
2246        (AnalyticSurface::Cylinder(c), AnalyticSurface::Torus(t)) => {
2247            if let Some(exacts) = exact_cylinder_torus(c, t)? {
2248                return exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p)))
2249                    .map(Some);
2250            }
2251            Ok(parallel_axis_torus_cylinder(t, c, false)
2252                .or_else(|| ruling_torus_cylinder(t, c, false)))
2253        }
2254        (AnalyticSurface::Sphere(s), AnalyticSurface::Torus(t)) => exact_sphere_torus(s, t)?
2255            .map(|exacts| exact_circle_curves(exacts, |p| (s.project_point(p), t.project_point(p))))
2256            .transpose(),
2257        (AnalyticSurface::Torus(t), AnalyticSurface::Sphere(s)) => exact_sphere_torus(s, t)?
2258            .map(|exacts| exact_circle_curves(exacts, |p| (t.project_point(p), s.project_point(p))))
2259            .transpose(),
2260        (AnalyticSurface::Torus(t1), AnalyticSurface::Torus(t2)) => exact_torus_torus(t1, t2)?
2261            .map(|exacts| {
2262                exact_circle_curves(exacts, |p| (t1.project_point(p), t2.project_point(p)))
2263            })
2264            .transpose(),
2265        _ => Ok(None),
2266    }
2267}
2268
2269/// A torus and a cylinder whose axes are parallel but distinct (a drill
2270/// through a ring parallel to its axis), traced along the cylinder's
2271/// rulings. A ruling stays at one distance `ρ` from the torus axis, so it
2272/// meets the tube where `(ρ − R)² + z² = r²`: a quadratic in its axial
2273/// parameter. `None` for any other pair (tilted or coaxial axes) and when
2274/// the sampling misses a window narrower than itself.
2275fn parallel_axis_torus_cylinder(
2276    torus: &ToroidalSurface,
2277    cyl: &CylindricalSurface,
2278    torus_first: bool,
2279) -> Option<Vec<IntersectionCurve>> {
2280    let axis = torus.z_axis();
2281    let along = cyl.axis().dot(axis);
2282    if along.abs() < 1.0 - 1e-10 {
2283        return None;
2284    }
2285    let offset = cyl.origin() - torus.center();
2286    if (offset - axis * offset.dot(axis)).length() < Tolerance::new().linear {
2287        return None;
2288    }
2289    let (major, minor) = (torus.major_radius(), torus.minor_radius());
2290    let roots = |u: f64| {
2291        let q = cyl.evaluate(u, 0.0) - torus.center();
2292        let height = q.dot(axis);
2293        let rho = (q - axis * height).length();
2294        let reach = minor * minor - (rho - major) * (rho - major);
2295        ruling_quadratic(1.0, 2.0 * along.signum() * height, height * height - reach)
2296    };
2297    let samples = ruling_samples(cyl, &roots);
2298    let loops = if samples.iter().all(Option::is_some) {
2299        closed_ruling_loops(cyl, &roots, &samples)
2300    } else {
2301        partial_ruling_loops(cyl, &roots, &samples)
2302    };
2303    if loops.is_empty() {
2304        return None;
2305    }
2306    Some(fit_ruling_loops(&loops, |p| {
2307        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
2308    }))
2309}
2310
2311/// Where two circles in a half-plane through an axis cross, as `(rho, z)`
2312/// pairs (distance from the axis, height along it): each sweeps a circle
2313/// about the axis. Two crossings closer than the linear tolerance are the
2314/// one point where the circles touch, side by side or one inside the
2315/// other. `None` (defer to the marcher) when the circles coincide or a
2316/// crossing lands on or past the axis; `Some` of none when they miss.
2317fn meridian_crossings(
2318    first: (f64, f64, f64),
2319    second: (f64, f64, f64),
2320    scale: f64,
2321) -> Option<Vec<(f64, f64)>> {
2322    let ((x1, z1, r1), (x2, z2, r2)) = (first, second);
2323    let (dx, dz) = (x2 - x1, z2 - z1);
2324    let dist = dx.hypot(dz);
2325    let slack = 1e-9 * scale;
2326    if dist < slack {
2327        return None;
2328    }
2329    let rounding = 8.0 * f64::EPSILON * (x1.abs() + x2.abs() + z1.abs() + z2.abs() + r1 + r2);
2330    if dist > r1 + r2 + rounding || dist < (r1 - r2).abs() - rounding {
2331        return Some(Vec::new());
2332    }
2333    let along = r2.mul_add(-r2, r1.mul_add(r1, dist * dist)) / (2.0 * dist);
2334    let across = r1.mul_add(r1, -(along * along)).max(0.0).sqrt();
2335    let (ux, uz) = (dx / dist, dz / dist);
2336    let sides: &[f64] = if 2.0 * across <= Tolerance::new().linear {
2337        &[0.0]
2338    } else {
2339        &[1.0, -1.0]
2340    };
2341    let mut crossings = Vec::with_capacity(sides.len());
2342    for side in sides {
2343        let rho = x1 + along * ux - side * across * uz;
2344        if rho <= slack {
2345            return None;
2346        }
2347        crossings.push((rho, z1 + along * uz + side * across * ux));
2348    }
2349    Some(crossings)
2350}
2351
2352/// Exact circles as intersection curves, each sampled at 33 points that
2353/// carry both surfaces' parameters, and a lone touching point as a curve
2354/// that stays on it.
2355fn exact_circle_curves(
2356    exacts: Vec<ExactIntersectionCurve>,
2357    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
2358) -> Result<Vec<IntersectionCurve>, MathError> {
2359    let mut curves = Vec::with_capacity(exacts.len());
2360    for exact in exacts {
2361        match exact {
2362            ExactIntersectionCurve::Circle(circle) => {
2363                let points = (0..=32)
2364                    .map(|i| {
2365                        let point = circle.evaluate(TAU * f64::from(i) / 32.0);
2366                        let (param1, param2) = params(point);
2367                        IntersectionPoint {
2368                            point,
2369                            param1,
2370                            param2,
2371                        }
2372                    })
2373                    .collect();
2374                let r = circle.radius();
2375                let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
2376                curves.push(IntersectionCurve { curve, points });
2377            }
2378            // A lone point is where the surfaces touch.
2379            ExactIntersectionCurve::Points(points) if points.len() == 1 => {
2380                let point = points[0];
2381                let (param1, param2) = params(point);
2382                curves.push(IntersectionCurve {
2383                    curve: interpolate(&[point, point], 1)?,
2384                    points: vec![IntersectionPoint {
2385                        point,
2386                        param1,
2387                        param2,
2388                    }],
2389                });
2390            }
2391            ExactIntersectionCurve::Ellipse(_) | ExactIntersectionCurve::Points(_) => {}
2392        }
2393    }
2394    Ok(curves)
2395}
2396
2397/// Circles about an axis through `base`, at the given `(rho, z)` crossings.
2398fn circles_about_axis(
2399    base: Point3,
2400    axis: Vec3,
2401    crossings: &[(f64, f64)],
2402) -> Result<Vec<ExactIntersectionCurve>, MathError> {
2403    crossings
2404        .iter()
2405        .map(|&(rho, z)| {
2406            Circle3D::new(base + axis * z, axis, rho).map(ExactIntersectionCurve::Circle)
2407        })
2408        .collect()
2409}
2410
2411/// Exact intersection of two tori sharing an axis: their tube cross-sections
2412/// in a half-plane through the axis cross in up to two points, and each sweeps
2413/// a circle about the axis.
2414///
2415/// Cross-sections that touch meet at one point, sweeping one circle. `None`
2416/// (defer to the marcher) unless the axes lie on one line, or when the
2417/// cross-sections coincide.
2418///
2419/// # Errors
2420///
2421/// Returns an error if a section circle cannot be built.
2422pub fn exact_torus_torus(
2423    first: &ToroidalSurface,
2424    second: &ToroidalSurface,
2425) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2426    let axis = first.z_axis();
2427    let scale = first.major_radius() + second.major_radius();
2428    let offset = second.center() - first.center();
2429    // A spindle torus's tube also crosses the far side of the axis.
2430    if first.minor_radius() >= first.major_radius()
2431        || second.minor_radius() >= second.major_radius()
2432        || axis.cross(second.z_axis()).length() > 1e-9
2433        || offset.cross(axis).length() > 1e-9 * scale
2434    {
2435        return Ok(None);
2436    }
2437    let Some(crossings) = meridian_crossings(
2438        (first.major_radius(), 0.0, first.minor_radius()),
2439        (
2440            second.major_radius(),
2441            offset.dot(axis),
2442            second.minor_radius(),
2443        ),
2444        scale,
2445    ) else {
2446        return Ok(None);
2447    };
2448    circles_about_axis(first.center(), axis, &crossings).map(Some)
2449}
2450
2451/// Exact intersection of a torus with a cylinder sharing its axis.
2452///
2453/// The wall line and the tube's cross-section in a half-plane through the
2454/// axis cross in up to two points, each sweeping a circle about the axis. A
2455/// wall touching the tube's outer equator, ring or spindle, or a ring torus's
2456/// inner equator meets it along the one circle at the torus's centre.
2457///
2458/// `None` (defer to the marcher) unless the axes lie on one line, or when
2459/// the wall reaches the part of a spindle torus's tube across the axis.
2460///
2461/// # Errors
2462///
2463/// Returns an error if a section circle cannot be built.
2464pub fn exact_cylinder_torus(
2465    cylinder: &CylindricalSurface,
2466    torus: &ToroidalSurface,
2467) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2468    let axis = torus.z_axis();
2469    let scale = torus.major_radius() + cylinder.radius();
2470    let offset = cylinder.origin() - torus.center();
2471    let linear = crate::tolerance::Tolerance::default().linear;
2472    if axis.cross(cylinder.axis()).length() > 1e-9
2473        || offset.cross(axis).length() > 1e-9 * scale
2474        || cylinder.radius() + torus.major_radius() <= torus.minor_radius() + linear
2475    {
2476        return Ok(None);
2477    }
2478    let gap = cylinder.radius() - torus.major_radius();
2479    let small = torus.minor_radius();
2480    // The equator circle lies on the torus within the wall's distance from
2481    // the tube, so it stands for the section while that distance is within
2482    // the linear tolerance, whatever the scale.
2483    if (gap.abs() - small).abs() <= linear {
2484        return circles_about_axis(torus.center(), axis, &[(cylinder.radius(), 0.0)]).map(Some);
2485    }
2486    if gap.abs() > small {
2487        return Ok(Some(Vec::new()));
2488    }
2489    let height = small.mul_add(small, -(gap * gap)).sqrt();
2490    circles_about_axis(
2491        torus.center(),
2492        axis,
2493        &[(cylinder.radius(), height), (cylinder.radius(), -height)],
2494    )
2495    .map(Some)
2496}
2497
2498/// Exact intersection of a torus with a sphere centred on its axis.
2499///
2500/// The sphere's great circle and the tube's cross-section in a half-plane
2501/// through the axis cross in up to two points, and each sweeps a circle
2502/// about the axis; where they touch (a ball sitting in the ring's hole or
2503/// on its rim) they meet along one circle. A sphere off the axis that
2504/// touches a ring torus at one point gives that point.
2505///
2506/// `None` (defer to the marcher) for a spindle torus, and for a sphere off
2507/// the axis that does not touch the torus at one point.
2508///
2509/// # Errors
2510///
2511/// Returns an error if a section circle cannot be built.
2512pub fn exact_sphere_torus(
2513    sphere: &SphericalSurface,
2514    torus: &ToroidalSurface,
2515) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2516    let axis = torus.z_axis();
2517    let scale = torus.major_radius() + sphere.radius();
2518    let offset = sphere.center() - torus.center();
2519    // A spindle torus's tube also crosses the far side of the axis.
2520    if torus.minor_radius() >= torus.major_radius() {
2521        return Ok(None);
2522    }
2523    if offset.cross(axis).length() > 1e-9 * scale {
2524        return Ok(
2525            off_axis_touch(sphere, torus).map(|p| vec![ExactIntersectionCurve::Points(vec![p])])
2526        );
2527    }
2528    let Some(crossings) = meridian_crossings(
2529        (0.0, offset.dot(axis), sphere.radius()),
2530        (torus.major_radius(), 0.0, torus.minor_radius()),
2531        scale,
2532    ) else {
2533        return Ok(None);
2534    };
2535    circles_about_axis(torus.center(), axis, &crossings).map(Some)
2536}
2537
2538/// Where a sphere off a ring torus's axis touches it at one point: from
2539/// outside the tube, from inside it, or holding the whole ring. The touch
2540/// sits over the core circle's point nearest the sphere's centre, at
2541/// `d_near`, or farthest from it, at `d_far`, and the sphere's radius is
2542/// then `d_near − r`, `r − d_near` or `d_far + r`. Each is the centre's
2543/// least or greatest distance to the torus, so the point is all the two
2544/// share. `None` unless the radius matches one to rounding.
2545fn off_axis_touch(sphere: &SphericalSurface, torus: &ToroidalSurface) -> Option<Point3> {
2546    let axis = torus.z_axis();
2547    let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
2548    let offset = sphere.center() - torus.center();
2549    let radial = offset - axis * offset.dot(axis);
2550    let out = radial * (1.0 / radial.length());
2551    let near = torus.center() + out * big;
2552    let far = torus.center() - out * big;
2553    let (to_near, to_far) = (sphere.center() - near, sphere.center() - far);
2554    let (d_near, d_far) = (to_near.length(), to_far.length());
2555    let slack = 64.0 * f64::EPSILON * (big + small + radius + offset.length());
2556    // A ball centred on the core circle meets the tube along a whole
2557    // meridian, not at a point.
2558    if d_near > slack
2559        && ((d_near - small - radius).abs() <= slack || (small - d_near - radius).abs() <= slack)
2560    {
2561        return Some(near + to_near * (small / d_near));
2562    }
2563    ((d_far + small - radius).abs() <= slack).then(|| far - to_far * (small / d_far))
2564}
2565
2566/// Exact coaxial cone-cone intersection: returns the shared circle.
2567///
2568/// Two cones that share an axis are concentric circles at every axial
2569/// station, so they meet only where their radii are equal. Each cone's
2570/// radius is linear in the axial coordinate `t` (measured along the shared
2571/// axis from cone 1's apex): `r1 = m1·t` and `r2 = m2·σ·(t − d2)`, where
2572/// `m_i = cot(half_angle_i)`, `σ = sign(axis2·axis1)`, and `d2` is cone 2's
2573/// apex position in that coordinate. Equating gives a single crossing `t*`
2574/// → one circle (the shared rim). The general marcher mishandles this case:
2575/// at the radii-crossing the surfaces are nearly tangent, so a grid-seeded
2576/// march fragments the clean circle into dozens of degenerate micro-curves.
2577///
2578/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
2579/// the cones do not meet (parallel radius lines or a crossing on the wrong
2580/// nappe), and `None` for the identical-cone overlap or a degenerate
2581/// (near-flat) cone — both of which fall through to the general path.
2582/// Parallel-but-offset axes with equal half-angle tangents reduce to a
2583/// radical-plane conic (`offset_parallel_cone_cone`); other offset
2584/// configurations defer to the marcher with `None`.
2585///
2586/// # Errors
2587///
2588/// Returns [`MathError`] if the shared-rim `Circle3D` cannot be constructed
2589/// (e.g. a non-finite center or radius from a malformed cone).
2590pub fn exact_cone_cone(
2591    c1: &ConicalSurface,
2592    c2: &ConicalSurface,
2593) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2594    let axis = c1.axis();
2595    let axis2 = c2.axis();
2596
2597    // Coaxial check: parallel axes and the second apex lies on the first axis.
2598    if axis.dot(axis2).abs() < 1.0 - 1e-10 {
2599        return Ok(None); // Non-coaxial: quartic curve, let the marcher handle.
2600    }
2601    let apex1 = c1.apex();
2602    let apex2 = c2.apex();
2603    let delta = apex2 - apex1;
2604    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2605    let along = delta_v.dot(axis);
2606    if (delta_v - axis * along).length() > 1e-8 {
2607        return offset_parallel_cone_cone(c1, c2);
2608    }
2609
2610    let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
2611    if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
2612        return Ok(None); // Degenerate (near-flat) cone.
2613    }
2614    let m1 = c1.half_angle().cos() / s1;
2615    let m2 = c2.half_angle().cos() / s2;
2616    let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
2617    let d2 = along; // apex2 position along `axis`, measured from apex1.
2618
2619    let denom = m1 - m2 * sigma;
2620    if denom.abs() < 1e-12 {
2621        // Parallel radius lines: identical cones (coincident apex, same opening)
2622        // overlap — defer to the general/same-domain path; otherwise no meeting.
2623        if sigma > 0.0 && d2.abs() < 1e-9 {
2624            return Ok(None);
2625        }
2626        return Ok(Some(vec![]));
2627    }
2628
2629    let t_star = (-m2 * sigma * d2) / denom;
2630    let radius = m1 * t_star;
2631    if radius < 1e-12 {
2632        return Ok(Some(vec![])); // Crossing on the wrong nappe / no real circle.
2633    }
2634
2635    let center = Point3::new(
2636        apex1.x() + axis.x() * t_star,
2637        apex1.y() + axis.y() * t_star,
2638        apex1.z() + axis.z() * t_star,
2639    );
2640    let circle = Circle3D::new(center, axis, radius)?;
2641    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
2642}
2643
2644/// Parallel-axis (or anti-parallel), offset-apex cones with equal half-angle
2645/// tangents: subtracting the two quadric equations cancels both the radial
2646/// and the axial quadratic terms (their coefficients depend only on
2647/// `tan²(half_angle)`), so every intersection point lies on a plane — the
2648/// degenerate member of the quadric pencil — and plane ∩ cone is an exact
2649/// conic. The gridfinity spacer lip fuse hits this exactly: opposed 45°
2650/// corner cones offset 0.25mm, which the marcher shreds into ~64 closed
2651/// micro-loops per pair (#1570). Unequal angles keep a genuine quadratic
2652/// term, and an unbounded section (hyperbola/parabola) has no closed-form
2653/// win over the marcher — both defer with `None`.
2654fn offset_parallel_cone_cone(
2655    c1: &ConicalSurface,
2656    c2: &ConicalSurface,
2657) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2658    if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
2659        return Ok(None); // Degenerate (near-flat) cone, as in the coaxial path.
2660    }
2661    let t1 = c1.half_angle().tan();
2662    let t2 = c2.half_angle().tan();
2663    if !t1.is_finite() || !t2.is_finite() {
2664        return Ok(None);
2665    }
2666    if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
2667        return Ok(None);
2668    }
2669
2670    let w = c1.axis();
2671    let apex1 = c1.apex();
2672    let apex2 = c2.apex();
2673    let delta = apex2 - apex1;
2674    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2675    let s = delta_v.dot(w);
2676    let tm = 0.5 * (t1 + t2);
2677    let k = 1.0 + tm * tm;
2678
2679    // In the apex1 frame each cone is |P|² − k(P·w)² = 0 (shifted by δ for
2680    // cone 2; the axis SIGN drops out since only (P·w)² appears). Their
2681    // difference: P·(2δ − 2ksw) = |δ|² − ks².
2682    let n = (delta_v - w * (k * s)) * 2.0;
2683    let n_len = n.length();
2684    if n_len < 1e-12 {
2685        return Ok(None);
2686    }
2687    let n_hat = n * (1.0 / n_len);
2688    let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
2689
2690    // `exact_plane_cone` already rejects sections on cone 1's phantom nappe;
2691    // cone 2's nappe must be checked here. A conic on the shared quadric
2692    // pencil cannot cross between nappes except exactly through apex 2, so
2693    // sampled quarter-points either all pass or all fail; a mixed verdict
2694    // means an apex-touching degeneracy — defer to the marcher.
2695    let axis2 = c2.axis();
2696    let scale = 1.0 + delta_v.length();
2697    let mut out = Vec::new();
2698    for curve in exact_plane_cone(c1, n_hat, d, 0.0)? {
2699        let samples: Vec<Point3> = match &curve {
2700            ExactIntersectionCurve::Circle(c) => (0..4)
2701                .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
2702                .collect(),
2703            ExactIntersectionCurve::Ellipse(e) => (0..4)
2704                .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
2705                .collect(),
2706            ExactIntersectionCurve::Points(_) => return Ok(None),
2707        };
2708        let on_real_nappe = |p: &Point3| {
2709            let rel = *p - apex2;
2710            Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
2711        };
2712        let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
2713        match hits {
2714            0 => {}
2715            4 => out.push(curve),
2716            _ => return Ok(None),
2717        }
2718    }
2719    Ok(Some(out))
2720}
2721
2722/// Exact coaxial cone-cylinder intersection: returns the shared circle.
2723///
2724/// A cone and a cylinder sharing an axis are concentric circles at every
2725/// axial station, so they meet only where the cone's radius equals the
2726/// cylinder's. The cone radius is linear in the axial coordinate `t` from its
2727/// apex (`r = m·t`, `m = cot(half_angle)`), the cylinder radius is the
2728/// constant `R`, so `m·t = R` gives a single crossing `t*` → one circle. This
2729/// is the gridfinity lip's top knife edge (inner tapered corner = cone, outer
2730/// corner = cylinder, concentric, radii matching at `Z_PEAK`); the general
2731/// marcher fragments that near-tangent contact into dozens of degenerate
2732/// micro-curves.
2733///
2734/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
2735/// the crossing degenerates to the apex, and `None` (defer to the marcher)
2736/// when the surfaces are not coaxial or the cone is near-flat / near-axial.
2737///
2738/// # Errors
2739///
2740/// Returns [`MathError`] if the shared `Circle3D` cannot be constructed.
2741pub fn exact_cone_cylinder(
2742    cone: &ConicalSurface,
2743    cyl: &CylindricalSurface,
2744) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2745    let axis = cone.axis();
2746    let cyl_axis = cyl.axis();
2747
2748    // Coaxial check: parallel axes and the cone apex on the cylinder's axis.
2749    if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
2750        return Ok(None);
2751    }
2752    let apex = cone.apex();
2753    let delta = apex - cyl.origin();
2754    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2755    let along = delta_v.dot(cyl_axis);
2756    if (delta_v - cyl_axis * along).length() > 1e-8 {
2757        return Ok(None);
2758    }
2759
2760    let s = cone.half_angle().sin();
2761    if s.abs() < 1e-12 {
2762        return Ok(None); // near-flat cone.
2763    }
2764    let m = cone.half_angle().cos() / s; // dr/dt along the cone axis.
2765    if m.abs() < 1e-12 {
2766        return Ok(None); // near-axial cone: radius ~constant.
2767    }
2768
2769    let t_star = cyl.radius() / m; // where the cone radius m·t equals R.
2770    if t_star.abs() < 1e-12 {
2771        return Ok(Some(vec![])); // crossing at the apex — no real circle.
2772    }
2773    let center = Point3::new(
2774        apex.x() + axis.x() * t_star,
2775        apex.y() + axis.y() * t_star,
2776        apex.z() + axis.z() * t_star,
2777    );
2778    let circle = Circle3D::new(center, axis, cyl.radius())?;
2779    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
2780}
2781
2782/// The exact rational quadratic NURBS of the full ellipse `centre +
2783/// a·cos(t)·u + b·sin(t)·v` (a circle when `a == b`), starting at
2784/// `centre + a·u`: four quarter arcs, each with its corner weighted by
2785/// cos 45°.
2786fn conic_loop(centre: Point3, u: Vec3, v: Vec3, a: f64, b: f64) -> Result<NurbsCurve, MathError> {
2787    let w = std::f64::consts::FRAC_1_SQRT_2;
2788    let corners: [(f64, f64); 9] = [
2789        (1.0, 0.0),
2790        (1.0, 1.0),
2791        (0.0, 1.0),
2792        (-1.0, 1.0),
2793        (-1.0, 0.0),
2794        (-1.0, -1.0),
2795        (0.0, -1.0),
2796        (1.0, -1.0),
2797        (1.0, 0.0),
2798    ];
2799    let points = corners
2800        .iter()
2801        .map(|&(x, y)| centre + u * (a * x) + v * (b * y))
2802        .collect();
2803    let weights = vec![1.0, w, 1.0, w, 1.0, w, 1.0, w, 1.0];
2804    let knots = vec![
2805        0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
2806    ];
2807    NurbsCurve::new(2, knots, points, weights)
2808}
2809
2810/// Two cylinders of one radius whose axes cross meet in two ellipses, one
2811/// in each plane through the crossing that bisects the axes: a point lies
2812/// as far from both axes where its offsets along them are equal or
2813/// opposite. Both ellipses have their minor axis, of the radius, along the
2814/// axes' common normal, and meet at its two ends. They come back as two
2815/// closed loops, as the first cylinder's rulings pair them: the halves of
2816/// both ellipses on one side of the crossing along its axis, then on the
2817/// other, each exact, rational, and cornered where its halves meet. One
2818/// loop starts at each end of the common normal.
2819///
2820/// `None` unless the radii match and the axes cross to rounding: axes that
2821/// miss by `δ` part the curves at the crossings by about `√(δ·r)`.
2822fn crossing_equal_cylinders(
2823    c1: &CylindricalSurface,
2824    c2: &CylindricalSurface,
2825) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2826    let (d1, d2, r) = (c1.axis(), c2.axis(), c1.radius());
2827    if (c2.radius() - r).abs() > 8.0 * f64::EPSILON * r {
2828        return Ok(None);
2829    }
2830    // An ellipse's semi-major axis is `2r / |d1 ∓ d2|`. Rounding the axes
2831    // turns its major axis by about `ε / |d1 ∓ d2|`, which moves its far
2832    // vertices by `2rε / |d1 ∓ d2|²`; axes nearer parallel than keeps that
2833    // well inside the tolerance are left to the rulings.
2834    let bisectors = [d1 - d2, d1 + d2];
2835    let tol = Tolerance::new().linear;
2836    if bisectors
2837        .iter()
2838        .any(|b| 2.0 * r * f64::EPSILON > 1e-3 * tol * b.dot(*b))
2839    {
2840        return Ok(None);
2841    }
2842    let across = d1.cross(d2);
2843    let sin = across.length();
2844    let normal = across * (1.0 / sin);
2845    let w = c1.origin() - c2.origin();
2846    let cos = d1.dot(d2);
2847    let along = cos.mul_add(d2.dot(w), -d1.dot(w)) / (sin * sin);
2848    let centre = c1.origin() + d1 * along;
2849    // The miss is read at the crossing's own scale: origins far along
2850    // their axes leave it more rounding than that, and are left to the
2851    // rulings too.
2852    let scale = r.max((centre - Point3::new(0.0, 0.0, 0.0)).length());
2853    if w.dot(normal).abs() > 64.0 * f64::EPSILON * scale {
2854        return Ok(None);
2855    }
2856    // Each ellipse's major axis, turned to lean along the first axis, and
2857    // its semi-major axis.
2858    let majors = bisectors.map(|bisector| {
2859        let length = bisector.length();
2860        let major = (bisector * (1.0 / length)).cross(normal);
2861        let major = if major.dot(d1) < 0.0 { -major } else { major };
2862        (major, 2.0 * r / length)
2863    });
2864    let corner = std::f64::consts::FRAC_1_SQRT_2;
2865    let half = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)];
2866    let mut curves = Vec::with_capacity(2);
2867    for side in [1.0, -1.0] {
2868        let [(m1, a1), (m2, a2)] = majors;
2869        let out = half
2870            .iter()
2871            .map(|&(x, y)| centre + normal * (side * r * x) + m1 * (side * a1 * y));
2872        let back = half[1..]
2873            .iter()
2874            .map(|&(x, y)| centre - normal * (side * r * x) + m2 * (side * a2 * y));
2875        let curve = NurbsCurve::new(
2876            2,
2877            vec![
2878                0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
2879            ],
2880            out.chain(back).collect(),
2881            vec![1.0, corner, 1.0, corner, 1.0, corner, 1.0, corner, 1.0],
2882        )?;
2883        #[allow(clippy::cast_precision_loss)]
2884        let points = (0..=32)
2885            .map(|i| {
2886                let point = curve.evaluate(i as f64 / 32.0);
2887                IntersectionPoint {
2888                    point,
2889                    param1: c1.project_point(point),
2890                    param2: c2.project_point(point),
2891                }
2892            })
2893            .collect();
2894        curves.push(IntersectionCurve { curve, points });
2895    }
2896    Ok(Some(curves))
2897}
2898
2899/// Algebraic cone-cone intersection (NURBS form for the general bounded
2900/// path). Delegates to [`exact_cone_cone`] and returns each exact conic
2901/// (coaxial circle or offset-parallel radical-plane ellipse) as an exact
2902/// rational NURBS `IntersectionCurve` with sample points along it, mirroring
2903/// the sphere-cylinder algebraic path. phase FF prefers the exact circle form
2904/// directly (so the section edge links to the coincident boundary), but a
2905/// caller of `intersect_analytic_analytic_bounded` still gets one clean
2906/// curve instead of the marcher's fragments.
2907fn algebraic_cone_cone(
2908    c1: &ConicalSurface,
2909    c2: &ConicalSurface,
2910) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2911    let Some(exacts) = exact_cone_cone(c1, c2)? else {
2912        return Ok(None);
2913    };
2914    let mut curves = Vec::new();
2915    for exact in exacts {
2916        let n_samples = 33;
2917        let mut points = Vec::with_capacity(n_samples);
2918        #[allow(clippy::cast_precision_loss)]
2919        for i in 0..n_samples {
2920            let theta = TAU * i as f64 / (n_samples - 1) as f64;
2921            let pt = match &exact {
2922                ExactIntersectionCurve::Circle(circle) => {
2923                    crate::traits::ParametricCurve::evaluate(circle, theta)
2924                }
2925                ExactIntersectionCurve::Ellipse(ellipse) => {
2926                    crate::traits::ParametricCurve::evaluate(ellipse, theta)
2927                }
2928                ExactIntersectionCurve::Points(_) => break,
2929            };
2930            points.push(IntersectionPoint {
2931                point: pt,
2932                param1: (0.0, 0.0),
2933                param2: (0.0, 0.0),
2934            });
2935        }
2936        let curve = match &exact {
2937            ExactIntersectionCurve::Circle(c) => {
2938                conic_loop(c.center(), c.u_axis(), c.v_axis(), c.radius(), c.radius())?
2939            }
2940            ExactIntersectionCurve::Ellipse(e) => conic_loop(
2941                e.center(),
2942                e.u_axis(),
2943                e.v_axis(),
2944                e.semi_major(),
2945                e.semi_minor(),
2946            )?,
2947            ExactIntersectionCurve::Points(_) => continue,
2948        };
2949        curves.push(IntersectionCurve { curve, points });
2950    }
2951    Ok(Some(curves))
2952}
2953
2954/// Exact coaxial sphere-cylinder intersection: returns the shared circle(s).
2955///
2956/// A sphere of radius `R` centered at `C` and a cylinder of radius `r` whose
2957/// axis passes through `C` meet in concentric circles of radius `r` at the
2958/// axial stations where `sqrt(R² − z²) = r`, i.e. `z = ±sqrt(R² − r²)`
2959/// measured from `C` along the axis. A proper crossing yields two circles; a
2960/// tangent contact (`r = R`) yields one; a cylinder wider than the sphere, or
2961/// a non-coaxial configuration (quartic curve), yields none/defers.
2962///
2963/// Mirrors [`exact_cone_cylinder`] so phase FF can emit the section as an
2964/// exact `Circle3D` (which the closed-circle split + seam adoption recognise)
2965/// rather than the marcher's NURBS fragments.
2966///
2967/// Returns `Some(vec![..])` (0, 1, or 2 circles) for the coaxial case, and
2968/// `None` (defer to the general marcher) when the axes are not coaxial.
2969///
2970/// # Errors
2971///
2972/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
2973pub fn exact_sphere_cylinder(
2974    sphere: &SphericalSurface,
2975    cyl: &CylindricalSurface,
2976) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2977    let sc = sphere.center();
2978    let r_sphere = sphere.radius();
2979    let co = cyl.origin();
2980    let axis = cyl.axis();
2981    let r_cyl = cyl.radius();
2982
2983    // Project sphere center onto the cylinder axis.
2984    let delta = sc - co;
2985    let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2986    let along = delta_vec.dot(axis);
2987    let perp_vec = delta_vec - axis * along;
2988    let d_perp = perp_vec.length();
2989
2990    // Non-coaxial sphere-cylinder intersections produce quartic curves;
2991    // defer those to the general marcher.
2992    if d_perp > 1e-7 {
2993        return Ok(None);
2994    }
2995
2996    // Coaxial: the sphere center lies on the cylinder axis. No real circle
2997    // when the cylinder is wider than the sphere or they are tangent-internal.
2998    if r_cyl > r_sphere + 1e-10 {
2999        return Ok(Some(vec![]));
3000    }
3001    let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
3002    if z_sq < 0.0 {
3003        return Ok(Some(vec![]));
3004    }
3005    let z = z_sq.sqrt();
3006
3007    // The sphere center projected onto the axis is the midpoint of the two
3008    // section circles, each offset by ±z along the axis with radius `r_cyl`.
3009    let center_axis_pt = Point3::new(
3010        co.x() + axis.x() * along,
3011        co.y() + axis.y() * along,
3012        co.z() + axis.z() * along,
3013    );
3014
3015    let mut circles = Vec::new();
3016    let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
3017    for &z_offset in offsets {
3018        let center = Point3::new(
3019            center_axis_pt.x() + axis.x() * z_offset,
3020            center_axis_pt.y() + axis.y() * z_offset,
3021            center_axis_pt.z() + axis.z() * z_offset,
3022        );
3023        let circle = Circle3D::new(center, axis, r_cyl)?;
3024        circles.push(ExactIntersectionCurve::Circle(circle));
3025    }
3026    Ok(Some(circles))
3027}
3028
3029/// Exact coaxial cone-sphere intersection: the shared circles.
3030///
3031/// When the cone's axis runs through the sphere's centre `C`, every generator
3032/// `apex + v g` (`g` a unit direction, `v` the distance from the apex) has
3033/// the same `h = g·(apex − C)`, so all of them meet the sphere at the same
3034/// roots of `v² + 2hv + |apex − C|² − R² = 0`. Each root ahead of the apex is
3035/// a circle of radius `v cos a` at `v sin a` along the axis: two for a ball
3036/// the cone passes through, one for a ball that swallows the apex, passes
3037/// through it or touches the wall, none for a ball the cone misses or that
3038/// sits inside it clear of the wall.
3039///
3040/// Returns `Some(vec![..])` for a coaxial pair and `None` (the ruling trace
3041/// or the marcher) otherwise.
3042///
3043/// # Errors
3044///
3045/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
3046pub fn exact_cone_sphere(
3047    cone: &ConicalSurface,
3048    sphere: &SphericalSurface,
3049) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3050    let offset = cone.apex() - sphere.center();
3051    let along = offset.dot(cone.axis());
3052    if (offset - cone.axis() * along).length() > 1e-7 {
3053        return Ok(None);
3054    }
3055    let lin_tol = Tolerance::new().linear;
3056    let (sin_a, cos_a) = cone.half_angle().sin_cos();
3057    let (far_sq, radius_sq) = (offset.dot(offset), sphere.radius() * sphere.radius());
3058    let b = 2.0 * sin_a * along;
3059    let (disc, far, near) = ruling_quadratic(1.0, b, far_sq - radius_sq);
3060    // At a tangent ball `b² − 4c` cancels to a few ulps of its terms, which
3061    // can land below zero: that is a touch, not a miss.
3062    let noise = 16.0 * f64::EPSILON * 4.0f64.mul_add(far_sq + radius_sq, b * b);
3063    if disc < -noise {
3064        return Ok(Some(vec![]));
3065    }
3066    let roots: &[f64] = if far - near < lin_tol {
3067        &[far]
3068    } else {
3069        &[near, far]
3070    };
3071    let mut circles = Vec::new();
3072    for &v in roots {
3073        if v * cos_a > lin_tol {
3074            let centre = cone.apex() + cone.axis() * (v * sin_a);
3075            let circle = Circle3D::new(centre, cone.axis(), v * cos_a)?;
3076            circles.push(ExactIntersectionCurve::Circle(circle));
3077        }
3078    }
3079    Ok(Some(circles))
3080}
3081
3082/// Algebraic sphere-cylinder intersection (NURBS form for the general bounded
3083/// path). A coaxial pair delegates to [`exact_sphere_cylinder`] and returns
3084/// each exact circle as an exact rational NURBS `IntersectionCurve`. phase FF
3085/// prefers the exact circle form directly (so the section edge links to the
3086/// coincident boundary and the closed-circle splitter can carve the spherical
3087/// band), but a caller of `intersect_analytic_analytic_bounded` still gets
3088/// clean curves instead of the marcher's fragments. Any other pair is traced
3089/// along the cylinder's rulings ([`off_axis_sphere_cylinder`]).
3090fn algebraic_sphere_cylinder(
3091    sphere: &SphericalSurface,
3092    cyl: &CylindricalSurface,
3093    sphere_first: bool,
3094) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3095    let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
3096        return Ok(off_axis_sphere_cylinder(sphere, cyl, sphere_first));
3097    };
3098
3099    let mut curves = Vec::new();
3100    for exact in exacts {
3101        let ExactIntersectionCurve::Circle(circle) = exact else {
3102            continue;
3103        };
3104        let n_samples = 33;
3105        let mut points = Vec::with_capacity(n_samples);
3106        #[allow(clippy::cast_precision_loss)]
3107        for i in 0..n_samples {
3108            let theta = TAU * i as f64 / (n_samples - 1) as f64;
3109            let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
3110            let (param1, param2) = in_order(
3111                sphere.project_point(pt),
3112                cyl.project_point(pt),
3113                sphere_first,
3114            );
3115            points.push(IntersectionPoint {
3116                point: pt,
3117                param1,
3118                param2,
3119            });
3120        }
3121        let r = circle.radius();
3122        let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
3123        curves.push(IntersectionCurve { curve, points });
3124    }
3125
3126    Ok(Some(curves))
3127}
3128
3129/// A sphere and a cylinder whose axis misses the sphere's centre (a drill
3130/// entering a ball off its axis), traced along the cylinder's rulings: the
3131/// ruling `c(u) + v·a` meets the sphere where `v² + 2(q·a)·v + |q|² − R² = 0`,
3132/// with `q = c(u) − C`. When every ruling meets the sphere (the cylinder
3133/// passes wholly through it) the roots trace an entry and an exit loop;
3134/// otherwise each window of meeting rulings carries one loop. `Some(empty)`
3135/// when the two cannot meet, `None` when the sampling misses a window
3136/// narrower than itself.
3137fn off_axis_sphere_cylinder(
3138    sphere: &SphericalSurface,
3139    cyl: &CylindricalSurface,
3140    sphere_first: bool,
3141) -> Option<Vec<IntersectionCurve>> {
3142    let (centre, radius) = (sphere.center(), sphere.radius());
3143    let axis = cyl.axis();
3144    let offset = centre - cyl.origin();
3145    let axis_distance = (offset - axis * offset.dot(axis)).length();
3146    let lin_tol = Tolerance::new().linear;
3147    if axis_distance > radius + cyl.radius() + lin_tol
3148        || axis_distance + radius < cyl.radius() - lin_tol
3149    {
3150        return Some(Vec::new());
3151    }
3152    let roots = |u: f64| {
3153        let q = cyl.evaluate(u, 0.0) - centre;
3154        ruling_quadratic(1.0, 2.0 * q.dot(axis), q.dot(q) - radius * radius)
3155    };
3156    let samples = ruling_samples(cyl, &roots);
3157    let loops = if samples.iter().all(Option::is_some) {
3158        closed_ruling_loops(cyl, &roots, &samples)
3159    } else {
3160        partial_ruling_loops(cyl, &roots, &samples)
3161    };
3162    if loops.is_empty() {
3163        return None;
3164    }
3165    Some(fit_ruling_loops(&loops, |p| {
3166        in_order(sphere.project_point(p), cyl.project_point(p), sphere_first)
3167    }))
3168}
3169
3170/// Parameters on the pair's first and second surfaces, from those on `a`
3171/// and `b` and whether `a` came first.
3172const fn in_order(a: (f64, f64), b: (f64, f64), a_first: bool) -> ((f64, f64), (f64, f64)) {
3173    if a_first { (a, b) } else { (b, a) }
3174}
3175
3176/// Two cylinders whose axes are parallel but apart meet along rulings:
3177/// every plane across the axes cuts them in two circles `d` apart, which
3178/// cross in two points, touch in one, or miss, alike in every plane. Each
3179/// crossing sweeps a ruling, cut to the stretch of axis both faces' `v`
3180/// ranges share. Two crossings closer than the linear tolerance are the one
3181/// where the circles touch, side by side or one inside the other. `None`
3182/// (the next solver's case) when neither range is known, since a ruling has
3183/// no ends of its own, or when a ruling's end strays off the second
3184/// cylinder, its axis leaning off the first's by more than the span allows.
3185fn parallel_cylinders(
3186    c1: &CylindricalSurface,
3187    c2: &CylindricalSurface,
3188    v_range_1: Option<(f64, f64)>,
3189    v_range_2: Option<(f64, f64)>,
3190) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3191    let axis = c1.axis();
3192    let delta = c2.origin() - c1.origin();
3193    let along = delta.dot(axis);
3194    let across = delta - axis * along;
3195    let d = across.length();
3196    let (r1, r2) = (c1.radius(), c2.radius());
3197    // The second face's range, measured along the first one's axis.
3198    let flip = c2.axis().dot(axis);
3199    let ranges = [
3200        v_range_1,
3201        v_range_2.map(|(a, b)| (along + a * flip, along + b * flip)),
3202    ];
3203    let (lo, hi) = ranges
3204        .into_iter()
3205        .flatten()
3206        .fold((f64::NEG_INFINITY, f64::INFINITY), |(lo, hi), (a, b)| {
3207            (lo.max(a.min(b)), hi.min(a.max(b)))
3208        });
3209    if !lo.is_finite() || !hi.is_finite() {
3210        return Ok(None);
3211    }
3212    let rounding = 8.0 * f64::EPSILON * (r1 + r2 + d);
3213    if d > r1 + r2 + rounding || d < (r1 - r2).abs() - rounding || hi <= lo {
3214        return Ok(Some(Vec::new()));
3215    }
3216    let toward = across * (1.0 / d);
3217    let side = axis.cross(toward);
3218    let x = r2.mul_add(-r2, d.mul_add(d, r1 * r1)) / (2.0 * d);
3219    let y = r1.mul_add(r1, -(x * x)).max(0.0).sqrt();
3220    let linear = Tolerance::new().linear;
3221    let feet = if 2.0 * y <= linear {
3222        vec![toward * x]
3223    } else {
3224        vec![toward * x + side * y, toward * x - side * y]
3225    };
3226    let on_second = |p: Point3| {
3227        let w = p - c2.origin();
3228        ((w - c2.axis() * w.dot(c2.axis())).length() - r2).abs() <= linear
3229    };
3230    let mut rulings = Vec::with_capacity(feet.len());
3231    for foot in feet {
3232        let base = c1.origin() + foot;
3233        let (from, to) = (base + axis * lo, base + axis * hi);
3234        if !on_second(from) || !on_second(to) {
3235            return Ok(None);
3236        }
3237        rulings.push(ruling_segment(from, to, |p| {
3238            (c1.project_point(p), c2.project_point(p))
3239        })?);
3240    }
3241    Ok(Some(rulings))
3242}
3243
3244/// A straight intersection curve from `from` to `to`, carrying its ends and
3245/// middle as points.
3246fn ruling_segment(
3247    from: Point3,
3248    to: Point3,
3249    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3250) -> Result<IntersectionCurve, MathError> {
3251    let curve = NurbsCurve::new(1, vec![0.0, 0.0, 1.0, 1.0], vec![from, to], vec![1.0, 1.0])?;
3252    let points = [from, from + (to - from) * 0.5, to]
3253        .into_iter()
3254        .map(|point| {
3255            let (param1, param2) = params(point);
3256            IntersectionPoint {
3257                point,
3258                param1,
3259                param2,
3260            }
3261        })
3262        .collect();
3263    Ok(IntersectionCurve { curve, points })
3264}
3265
3266/// Algebraic cylinder-cylinder intersection for non-coaxial cylinders.
3267///
3268/// For two cylinders with axes that are NOT parallel, the intersection
3269/// consists of up to two closed space curves. These are found by
3270/// parameterizing one cylinder's angular coordinate `u ∈ [0, 2π]` and
3271/// solving a quadratic in the axial parameter `v` to find where each
3272/// "ring" of cylinder A sits on cylinder B.
3273///
3274/// The quadratic is:
3275///   `v²·(1 - α²) + 2v·(q·a₁ - α·q·a₂) + (|q|² - (q·a₂)² - r₂²) = 0`
3276/// where `α = a₁·a₂`, `q(u)` is the radial point on cylinder 1 minus
3277/// cylinder 2's origin, `a₁`/`a₂` are the cylinder axes, and `r₂` is
3278/// cylinder 2's radius.
3279#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
3280fn algebraic_cylinder_cylinder(
3281    c1: &CylindricalSurface,
3282    c2: &CylindricalSurface,
3283) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3284    if let Some(halves) = crossing_equal_cylinders(c1, c2)? {
3285        return Ok(Some(halves));
3286    }
3287    let alpha = c1.axis().dot(c2.axis());
3288    let a_coeff = 1.0 - alpha * alpha;
3289
3290    // Should only be called for non-parallel axes.
3291    if a_coeff.abs() < 1e-12 {
3292        return Ok(None);
3293    }
3294
3295    let r1 = c1.radius();
3296    let r2 = c2.radius();
3297    let o1 = c1.origin();
3298    let o2 = c2.origin();
3299    let a1 = c1.axis();
3300    let a2 = c2.axis();
3301
3302    // Separation check: distance between axes vs sum of radii.
3303    // Closest approach of two skew lines:
3304    let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
3305    let cross = a1.cross(a2);
3306    let cross_len = cross.length();
3307    if cross_len > 1e-12 {
3308        let axis_dist = delta.dot(cross).abs() / cross_len;
3309        if axis_dist > r1 + r2 + Tolerance::new().linear {
3310            return Ok(Some(vec![])); // No intersection
3311        }
3312    }
3313
3314    // Solve every ruling of one cylinder against the other. When EVERY
3315    // ruling of the swept cylinder meets the other (the thinner of two
3316    // crossing tubes), the two roots trace the curve's two closed loops.
3317    // Swept the other way only a window of rulings meets, and each root
3318    // traces an open arc of one loop.
3319    let roots = |sweep: &CylindricalSurface, other: &CylindricalSurface| {
3320        let (o, a, radius) = (other.origin(), other.axis(), other.radius());
3321        let alpha = sweep.axis().dot(a);
3322        let quad = 1.0 - alpha * alpha;
3323        let (axis, sweep) = (sweep.axis(), sweep.clone());
3324        move |u: f64| {
3325            let q = sweep.evaluate(u, 0.0) - o;
3326            let (q_a1, q_a2) = (q.dot(axis), q.dot(a));
3327            let b = 2.0 * (q_a1 - alpha * q_a2);
3328            let c = q.dot(q) - q_a2 * q_a2 - radius * radius;
3329            ruling_quadratic(quad, b, c)
3330        }
3331    };
3332    let (roots1, roots2) = (roots(c1, c2), roots(c2, c1));
3333    let samples1 = ruling_samples(c1, &roots1);
3334    let loops = if samples1.iter().all(Option::is_some) {
3335        closed_ruling_loops(c1, &roots1, &samples1)
3336    } else {
3337        let samples2 = ruling_samples(c2, &roots2);
3338        if samples2.iter().all(Option::is_some) {
3339            closed_ruling_loops(c2, &roots2, &samples2)
3340        } else if samples1.iter().any(Option::is_some) {
3341            partial_ruling_loops(c1, &roots1, &samples1)
3342        } else {
3343            partial_ruling_loops(c2, &roots2, &samples2)
3344        }
3345    };
3346    if loops.is_empty() {
3347        return Ok(None);
3348    }
3349    Ok(Some(fit_ruling_loops(&loops, |p| {
3350        (c1.project_point(p), c2.project_point(p))
3351    })))
3352}
3353
3354/// A cone and a cylinder whose axes are not parallel, traced along the
3355/// cylinder's rulings. A ruling `q + t w` meets the cone's double quadric
3356/// `|p - apex|^2 = h^2 / sin^2(half_angle)`, with `h` the offset along the
3357/// cone's axis, where a quadratic in `t` vanishes. `None` (the marcher's
3358/// case) when a ruling meets the far nappe, where no cone face lies, when
3359/// the rulings run along the cone's generators, or when no ruling meets it.
3360fn ruling_cone_cylinder(
3361    cone: &ConicalSurface,
3362    cyl: &CylindricalSurface,
3363    cone_first: bool,
3364) -> Option<Vec<IntersectionCurve>> {
3365    let (sin_t, cos_t) = cone.half_angle().sin_cos();
3366    if sin_t < 1e-12 || cos_t < 1e-12 {
3367        return None;
3368    }
3369    let (apex, d, w) = (cone.apex(), cone.axis(), cyl.axis());
3370    let s = 1.0 / (sin_t * sin_t);
3371    let alpha = w.dot(d);
3372    let quad = 1.0 - s * alpha * alpha;
3373    if quad.abs() < 1e-9 {
3374        return None;
3375    }
3376    let roots = |u: f64| {
3377        let delta = cyl.evaluate(u, 0.0) - apex;
3378        let (dd, dw) = (delta.dot(d), delta.dot(w));
3379        let b = 2.0 * (dw - s * dd * alpha);
3380        let c = delta.dot(delta) - s * dd * dd;
3381        ruling_quadratic(quad, b, c)
3382    };
3383    let lin_tol = Tolerance::new().linear;
3384    let far_nappe = (0..WINDOW_SCAN * RULING_SAMPLES).any(|k| {
3385        #[allow(clippy::cast_precision_loss)]
3386        let u = TAU * (k as f64 + 0.5) / (WINDOW_SCAN * RULING_SAMPLES) as f64;
3387        let (disc, vp, vm) = roots(u);
3388        disc >= -lin_tol
3389            && [vp, vm]
3390                .iter()
3391                .any(|&t| (cyl.evaluate(u, t) - apex).dot(d) < -lin_tol)
3392    });
3393    if far_nappe {
3394        return None;
3395    }
3396    let samples = ruling_samples(cyl, &roots);
3397    // A window of meeting rulings narrower than the sampling would vanish
3398    // (a cone's tip just through the wall) while the others still made
3399    // loops; a finer scan finds every window, and any that the sampling
3400    // covers thinly goes to the marcher.
3401    let scan = WINDOW_SCAN * RULING_SAMPLES;
3402    // Ruling sample `i` lies midway between scan points
3403    // `WINDOW_SCAN i + 7` and `WINDOW_SCAN i + 8`.
3404    #[allow(clippy::cast_precision_loss)]
3405    let meets = |k: usize| roots(TAU * ((k % scan) as f64 + 0.5) / scan as f64).0 >= -lin_tol;
3406    if let Some(start) = (0..scan).find(|&k| !meets(k)) {
3407        let mut k = start;
3408        while k < start + scan {
3409            if !meets(k) {
3410                k += 1;
3411                continue;
3412            }
3413            let first = k;
3414            while k < start + scan && meets(k) {
3415                k += 1;
3416            }
3417            let covered = (first..k)
3418                .filter(|&j| j % WINDOW_SCAN == WINDOW_SCAN / 2 - 1 && meets(j + 1))
3419                .count();
3420            if covered < WINDOW_MIN_SAMPLES {
3421                return None;
3422            }
3423        }
3424    }
3425    let loops = if samples.iter().all(Option::is_some) {
3426        closed_ruling_loops(cyl, &roots, &samples)
3427    } else {
3428        partial_ruling_loops(cyl, &roots, &samples)
3429    };
3430    if loops.is_empty() {
3431        return None;
3432    }
3433    Some(fit_ruling_loops(&loops, |p| {
3434        in_order(cone.project_point(p), cyl.project_point(p), cone_first)
3435    }))
3436}
3437
3438/// A torus and a cylinder whose axes are not parallel, where every ruling
3439/// of the cylinder meets the torus the same nonzero even number of times (a
3440/// rod through the ring's tube): a ruling meets the torus where a quartic in
3441/// its parameter vanishes, and each of its roots, taken in order, sweeps one
3442/// closed loop around the cylinder. `None` (the marcher's case) when the
3443/// count varies between rulings, where the curve turns back between them,
3444/// checked on a scan finer than the sampling so a narrow window of missing
3445/// rulings is not stepped over, and for a spindle torus, whose quartic also
3446/// holds its inner lemon.
3447fn ruling_torus_cylinder(
3448    torus: &ToroidalSurface,
3449    cyl: &CylindricalSurface,
3450    torus_first: bool,
3451) -> Option<Vec<IntersectionCurve>> {
3452    if cyl.axis().dot(torus.z_axis()).abs() > 1.0 - 1e-9
3453        || torus.minor_radius() >= torus.major_radius()
3454    {
3455        return None;
3456    }
3457    let roots = |u: f64| intersect_line_torus(torus, cyl.evaluate(u, 0.0), cyl.axis());
3458    let rows: Vec<Vec<f64>> = (0..RULING_SAMPLES).map(|i| roots(ruling_u(i))).collect();
3459    let count = rows[0].len();
3460    let scan = WINDOW_SCAN * RULING_SAMPLES;
3461    #[allow(clippy::cast_precision_loss)]
3462    if count == 0
3463        || count % 2 == 1
3464        || (0..scan).any(|k| roots(TAU * (k as f64 + 0.5) / scan as f64).len() != count)
3465    {
3466        return None;
3467    }
3468    let loops: Vec<Vec<Point3>> = (0..count)
3469        .map(|j| {
3470            let mut pts: Vec<Point3> = rows
3471                .iter()
3472                .enumerate()
3473                .map(|(i, r)| cyl.evaluate(ruling_u(i), r[j]))
3474                .collect();
3475            pts.push(pts[0]);
3476            pts
3477        })
3478        .collect();
3479    Some(fit_ruling_loops(&loops, |p| {
3480        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
3481    }))
3482}
3483
3484/// A cone and a sphere whose centre is off the cone's axis, where every
3485/// generator of the cone crosses the sphere twice on the cone's nappe (a pin
3486/// through a ball): along a generator `apex + v g` the sphere is a quadratic
3487/// in `v`, and each of its two roots, taken in order, sweeps one closed loop
3488/// around the cone. A ball holding the apex is left once by every generator,
3489/// one loop. `None` when the centre lies on the axis (phase FF takes
3490/// [`exact_cone_sphere`]'s circles there), or the apex on the sphere. A
3491/// sphere only some generators cross goes to [`window_cone_sphere`].
3492fn ruling_cone_sphere(
3493    cone: &ConicalSurface,
3494    sphere: &SphericalSurface,
3495    cone_first: bool,
3496) -> Option<Vec<IntersectionCurve>> {
3497    let (apex, centre, radius) = (cone.apex(), sphere.center(), sphere.radius());
3498    let offset = apex - centre;
3499    let lin_tol = Tolerance::new().linear;
3500    let along = offset.dot(cone.axis());
3501    let across = (offset - cone.axis() * along).length();
3502    if across < lin_tol {
3503        return None;
3504    }
3505    // With the apex inside the ball, `v² + 2hv + K` has roots of opposite
3506    // signs (`K = |offset|² − R² < 0`): every generator leaves the ball once
3507    // ahead of the apex, at `v = √(h² − K) − h`, one loop round the cone.
3508    // Where `h > 0` the root is taken as `−K / (h + √(h² − K))`, free of the
3509    // cancellation.
3510    let k = offset.dot(offset) - radius * radius;
3511    if radius - offset.length() > lin_tol {
3512        let exit = |u: f64| {
3513            let h = (cone.evaluate(u, 1.0) - apex).dot(offset);
3514            let root = h.mul_add(h, -k).sqrt();
3515            cone.evaluate(u, if h > 0.0 { -k / (h + root) } else { root - h })
3516        };
3517        // A ball that barely holds the apex turns the loop sharply where it
3518        // passes the apex, at the scale of `√−K`: a step whose midpoint
3519        // strays from its chord by a hundredth of the chord (a turn of about
3520        // 0.08 radians) is halved until the turn is resolved.
3521        let mut samples: Vec<(f64, Point3)> = (0..=RULING_SAMPLES)
3522            .map(|i| (ruling_u(i), exit(ruling_u(i))))
3523            .collect();
3524        for _ in 0..10 {
3525            let mut refined = Vec::with_capacity(2 * samples.len());
3526            for pair in samples.windows(2) {
3527                let ((u0, p0), (u1, p1)) = (pair[0], pair[1]);
3528                refined.push(pair[0]);
3529                let um = 0.5 * (u0 + u1);
3530                let pm = exit(um);
3531                let chord = (p1 - p0).length();
3532                if chord > lin_tol && (pm - (p0 + (p1 - p0) * 0.5)).length() > 0.01 * chord {
3533                    refined.push((um, pm));
3534                }
3535            }
3536            refined.extend(samples.last().copied());
3537            if refined.len() == samples.len() {
3538                break;
3539            }
3540            samples = refined;
3541        }
3542        let mut pts: Vec<Point3> = samples.iter().map(|&(_, p)| p).collect();
3543        if let Some(last) = pts.last_mut() {
3544            *last = samples[0].1;
3545        }
3546        return Some(fit_ruling_loops(&[pts], |p| {
3547            in_order(cone.project_point(p), sphere.project_point(p), cone_first)
3548        }));
3549    }
3550    // Both roots along a generator of unit direction `g` (`v` the distance
3551    // from the apex), nearer first, from `h = g·offset`, when it crosses the
3552    // sphere twice ahead of the apex.
3553    let crossing = |h: f64| {
3554        let (disc, vp, vm) = ruling_quadratic(1.0, 2.0 * h, k);
3555        (disc > lin_tol && vm >= lin_tol).then_some((vm, vp))
3556    };
3557    // Around the cone `h` runs between these bounds. Where both roots lie
3558    // ahead of the apex, raising `h` shrinks the discriminant and moves the
3559    // nearer root out, so every generator crosses when the two extreme ones
3560    // do.
3561    let (sin_a, cos_a) = cone.half_angle().sin_cos();
3562    if crossing(sin_a.mul_add(along, cos_a * across)).is_none()
3563        || crossing(sin_a.mul_add(along, -cos_a * across)).is_none()
3564    {
3565        return window_cone_sphere(cone, sphere, cone_first);
3566    }
3567    let rows: Vec<(f64, f64)> = (0..RULING_SAMPLES)
3568        .map(|i| crossing((cone.evaluate(ruling_u(i), 1.0) - apex).dot(offset)))
3569        .collect::<Option<_>>()?;
3570    let loops: Vec<Vec<Point3>> = [0, 1]
3571        .iter()
3572        .map(|&j| {
3573            let mut pts: Vec<Point3> = rows
3574                .iter()
3575                .enumerate()
3576                .map(|(i, &(near, far))| {
3577                    cone.evaluate(ruling_u(i), if j == 0 { near } else { far })
3578                })
3579                .collect();
3580            pts.push(pts[0]);
3581            pts
3582        })
3583        .collect();
3584    Some(fit_ruling_loops(&loops, |p| {
3585        in_order(cone.project_point(p), sphere.project_point(p), cone_first)
3586    }))
3587}
3588
3589/// A cone and a sphere off its axis that only some generators cross (a ball
3590/// against the cone's side), with the apex outside the sphere: along the
3591/// generator at `u`, `h(u) = g·(apex − C)` is `c + A cos(u − φ)`, and the
3592/// generator crosses twice ahead of the apex where `h ≤ −√K`, with
3593/// `K = |apex − C|² − R²`. That is one arc of `u`, whose ends are where the
3594/// generator touches the sphere; the section is one loop, the nearer roots
3595/// out along the arc and the farther ones back. Sampled at
3596/// `u = mid − half·cos θ`, the roots' split `±√(h² − K)` changes sign with
3597/// `sin θ` and the loop stays smooth through both touching generators.
3598/// `Some(empty)` when no generator crosses ahead of the apex. `None`, the
3599/// marcher's case, when the apex lies within the sphere, when the centre is
3600/// too near the axis to place the arc, and when every generator reaches the
3601/// sphere (the extremes' test then failed on a touching generator or a root
3602/// at the apex).
3603fn window_cone_sphere(
3604    cone: &ConicalSurface,
3605    sphere: &SphericalSurface,
3606    cone_first: bool,
3607) -> Option<Vec<IntersectionCurve>> {
3608    let offset = cone.apex() - sphere.center();
3609    let lin_tol = Tolerance::new().linear;
3610    if offset.length() - sphere.radius() <= lin_tol {
3611        return None;
3612    }
3613    let k = offset.dot(offset) - sphere.radius() * sphere.radius();
3614    let (sin_a, cos_a) = cone.half_angle().sin_cos();
3615    let (ox, oy) = (offset.dot(cone.x_axis()), offset.dot(cone.y_axis()));
3616    let (c, a) = (sin_a * offset.dot(cone.axis()), cos_a * ox.hypot(oy));
3617    if a < lin_tol {
3618        return None;
3619    }
3620    let reach = (-k.sqrt() - c) / a;
3621    if reach <= -1.0 {
3622        return Some(Vec::new());
3623    }
3624    if reach >= 1.0 {
3625        return None;
3626    }
3627    let (mid, half) = (oy.atan2(ox) + std::f64::consts::PI, reach.acos());
3628    let half = std::f64::consts::PI - half;
3629    let n = RULING_SAMPLES;
3630    let mut pts: Vec<Point3> = (0..n)
3631        .map(|i| {
3632            #[allow(clippy::cast_precision_loss)]
3633            let theta = TAU * i as f64 / n as f64;
3634            let u = half.mul_add(-theta.cos(), mid);
3635            let h = a.mul_add((u - mid + std::f64::consts::PI).cos(), c);
3636            let split = h.mul_add(h, -k).max(0.0).sqrt();
3637            cone.evaluate(u, -h - split.copysign(theta.sin()))
3638        })
3639        .collect();
3640    pts.push(pts[0]);
3641    Some(fit_ruling_loops(&[pts], |p| {
3642        in_order(cone.project_point(p), sphere.project_point(p), cone_first)
3643    }))
3644}
3645
3646/// Scan points per ruling sample when looking for windows of meeting
3647/// rulings, and the fewest samples a window needs to be fit.
3648const WINDOW_SCAN: usize = 16;
3649const WINDOW_MIN_SAMPLES: usize = 8;
3650
3651/// Rulings sampled around a swept cylinder, half a step off u = 0 so the
3652/// branches of a self-touching curve (equal crossing cylinders) do not share
3653/// a sample.
3654const RULING_SAMPLES: usize = 128;
3655
3656#[allow(clippy::cast_precision_loss)]
3657fn ruling_u(i: usize) -> f64 {
3658    TAU * (i as f64 + 0.5) / RULING_SAMPLES as f64
3659}
3660
3661/// The discriminant and roots of `quad·v² + b·v + c = 0`.
3662fn ruling_quadratic(quad: f64, b: f64, c: f64) -> (f64, f64, f64) {
3663    let disc = b * b - 4.0 * quad * c;
3664    let root = disc.max(0.0).sqrt();
3665    (disc, (-b + root) / (2.0 * quad), (-b - root) / (2.0 * quad))
3666}
3667
3668/// The two points where each sampled ruling of `sweep` meets the other
3669/// surface, from `roots(u)` (the discriminant and the two axial parameters),
3670/// or `None` for a ruling that misses it.
3671fn ruling_samples(
3672    sweep: &CylindricalSurface,
3673    roots: &impl Fn(f64) -> (f64, f64, f64),
3674) -> Vec<Option<(Point3, Point3)>> {
3675    let lin_tol = Tolerance::new().linear;
3676    (0..RULING_SAMPLES)
3677        .map(|i| {
3678            let u = ruling_u(i);
3679            let (disc, vp, vm) = roots(u);
3680            (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
3681        })
3682        .collect()
3683}
3684
3685/// Every ruling meets the other surface: each root traces a closed loop.
3686/// Where the loops pass closest at one ruling they are sampled from it,
3687/// closer together near it, so the fit follows the narrow neck between
3688/// them; where they touch there, they are the two halves of one curve
3689/// crossing itself, each with a corner at that point, which then falls at
3690/// their shared start and end, where the fit keeps it.
3691fn closed_ruling_loops(
3692    sweep: &CylindricalSurface,
3693    roots: &impl Fn(f64) -> (f64, f64, f64),
3694    samples: &[Option<(Point3, Point3)>],
3695) -> Vec<Vec<Point3>> {
3696    let (mut plus, mut minus): (Vec<Point3>, Vec<Point3>) =
3697        if let Some((neck, touching)) = narrowest_ruling(roots) {
3698            let count = 2 * RULING_SAMPLES;
3699            #[allow(clippy::cast_precision_loss)]
3700            (0..count)
3701                .map(|i| {
3702                    let t = i as f64 / count as f64;
3703                    let u = TAU.mul_add(t - 0.9 * (TAU * t).sin() / TAU, neck);
3704                    let (_, vp, vm) = roots(u);
3705                    if i == 0 && touching {
3706                        let at = sweep.evaluate(u, 0.5 * (vp + vm));
3707                        (at, at)
3708                    } else {
3709                        (sweep.evaluate(u, vp), sweep.evaluate(u, vm))
3710                    }
3711                })
3712                .unzip()
3713        } else {
3714            samples.iter().flatten().copied().unzip()
3715        };
3716    plus.push(plus[0]);
3717    minus.push(minus[0]);
3718    vec![plus, minus]
3719}
3720
3721/// The ruling where the two roots pass closest, when exactly one ruling
3722/// stands out: a local minimum of their gap, scanned finer than the
3723/// sampling and refined, that either closes to within tolerance (the
3724/// roots touch there; the tolerance scales with the widest gap, the loops'
3725/// own size, so the decision does not move with the model) or narrows
3726/// below a quarter of the widest gap while no other minimum does. Equal
3727/// crossing cylinders touch at two rulings and get `None`.
3728fn narrowest_ruling(roots: &impl Fn(f64) -> (f64, f64, f64)) -> Option<(f64, bool)> {
3729    let scan = WINDOW_SCAN * RULING_SAMPLES;
3730    #[allow(clippy::cast_precision_loss)]
3731    let step = TAU / scan as f64;
3732    let gap = |u: f64| {
3733        let (_, vp, vm) = roots(u);
3734        (vp - vm).abs()
3735    };
3736    #[allow(clippy::cast_precision_loss)]
3737    let gaps: Vec<f64> = (0..scan).map(|k| gap(step * k as f64)).collect();
3738    let widest = gaps.iter().copied().fold(0.0, f64::max);
3739    let tol = Tolerance::new().linear * (1.0 + widest);
3740    let mut necks = Vec::new();
3741    for k in 0..scan {
3742        let (before, here, after) = (gaps[(k + scan - 1) % scan], gaps[k], gaps[(k + 1) % scan]);
3743        if here > before || here >= after || here >= 0.25 * widest {
3744            continue;
3745        }
3746        #[allow(clippy::cast_precision_loss)]
3747        let (mut lo, mut hi) = (step * (k as f64 - 1.0), step * (k as f64 + 1.0));
3748        for _ in 0..100 {
3749            let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
3750            if gap(a) < gap(b) {
3751                hi = b;
3752            } else {
3753                lo = a;
3754            }
3755        }
3756        let u = 0.5 * (lo + hi);
3757        necks.push((u, gap(u) <= tol));
3758    }
3759    match necks[..] {
3760        [neck] => Some(neck),
3761        _ => None,
3762    }
3763}
3764
3765/// Only windows of rulings meet the other surface: each cyclic window
3766/// carries one loop, out along one root and back along the other, the two
3767/// joined where the discriminant vanishes. Empty when no sample meets it (a
3768/// window narrower than the sampling).
3769fn partial_ruling_loops(
3770    sweep: &CylindricalSurface,
3771    roots: &impl Fn(f64) -> (f64, f64, f64),
3772    samples: &[Option<(Point3, Point3)>],
3773) -> Vec<Vec<Point3>> {
3774    let branch_point = |inside: usize, outside: usize| -> Point3 {
3775        let (mut lo, mut hi) = (ruling_u(inside), ruling_u(outside));
3776        if (hi - lo).abs() > std::f64::consts::PI {
3777            hi += if hi < lo { TAU } else { -TAU };
3778        }
3779        for _ in 0..60 {
3780            let mid = 0.5 * (lo + hi);
3781            if roots(mid).0 >= 0.0 {
3782                lo = mid;
3783            } else {
3784                hi = mid;
3785            }
3786        }
3787        let (_, vp, vm) = roots(lo);
3788        sweep.evaluate(lo, 0.5 * (vp + vm))
3789    };
3790    let Some(first_gap) = samples.iter().position(Option::is_none) else {
3791        return Vec::new();
3792    };
3793    let mut loops = Vec::new();
3794    let mut k = 0;
3795    while k < RULING_SAMPLES {
3796        let i = (first_gap + k) % RULING_SAMPLES;
3797        if samples[i].is_none() {
3798            k += 1;
3799            continue;
3800        }
3801        let start = i;
3802        let mut run = Vec::new();
3803        while k < RULING_SAMPLES {
3804            let j = (first_gap + k) % RULING_SAMPLES;
3805            let Some(pair) = samples[j] else { break };
3806            run.push(pair);
3807            k += 1;
3808        }
3809        let end = (start + run.len() - 1) % RULING_SAMPLES;
3810        let head = branch_point(start, (start + RULING_SAMPLES - 1) % RULING_SAMPLES);
3811        let tail = branch_point(end, (end + 1) % RULING_SAMPLES);
3812        let mut pts = vec![head];
3813        pts.extend(run.iter().map(|p| p.0));
3814        pts.push(tail);
3815        pts.extend(run.iter().rev().map(|p| p.1));
3816        pts.push(head);
3817        loops.push(pts);
3818    }
3819    loops
3820}
3821
3822/// Cubic interpolants through the swept loops, with `params(p)` giving each
3823/// point's parameters on the two surfaces.
3824fn fit_ruling_loops(
3825    loops: &[Vec<Point3>],
3826    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3827) -> Vec<IntersectionCurve> {
3828    let mut curves = Vec::new();
3829    for pts in loops {
3830        if pts.len() < 4 {
3831            continue;
3832        }
3833        let ipts: Vec<IntersectionPoint> = pts
3834            .iter()
3835            .map(|&p| {
3836                let (param1, param2) = params(p);
3837                IntersectionPoint {
3838                    point: p,
3839                    param1,
3840                    param2,
3841                }
3842            })
3843            .collect();
3844        let degree = 3.min(pts.len() - 1);
3845        if let Ok(curve) = interpolate(pts, degree) {
3846            curves.push(IntersectionCurve {
3847                curve,
3848                points: ipts,
3849            });
3850        }
3851    }
3852    curves
3853}
3854
3855/// Algebraic cone-cylinder intersection for PARALLEL (or antiparallel) axes.
3856///
3857/// When the axes are parallel, every plane perpendicular to them cuts the cone
3858/// in a circle of radius `rho = v * cos(half_angle)` about a FIXED centre and
3859/// the cylinder in a circle of radius `R` about a second FIXED centre, so the
3860/// axis separation `d` is constant in `v`. Two coplanar circles meet at
3861/// `u = phi0 +/- acos((d^2 + rho^2 - R^2) / (2*d*rho))`, giving two branches
3862/// parameterised exactly by the cone's own `v`. The branches exist only where
3863/// `rho` lies in `[|d - R|, d + R]`, which bounds the curve naturally.
3864///
3865/// This replaces the general grid-seeded marcher for the configuration, which
3866/// mis-handles it badly: seeds are accepted anywhere within half the surface
3867/// diagonal of the partner, the march-result dedup only consumes seeds the
3868/// traced polyline passes near, and the survivors are dozens of overlapping
3869/// partial traces of the same curve. Those fragments carry no usable in-face
3870/// span, so a cone corner-round crossed by a boss cylinder never splits (a
3871/// counterbore/countersink meeting a pad — the gridfinity lightweight base).
3872///
3873/// Returns `None` (defer to the caller's other paths) when the axes are not
3874/// parallel, or when they are coaxial — a coaxial pair degenerates to shared
3875/// circles, which [`exact_cone_cylinder`] emits exactly and phase FF calls
3876/// directly. Note that `intersect_analytic_analytic_bounded` does NOT consult
3877/// `exact_cone_cylinder`, so a coaxial pair reaching this path through that
3878/// caller falls through to the marcher; only the FF path gets the exact circles.
3879// Result-wrapped to match the other `try_algebraic_intersection` arms' shape.
3880#[allow(clippy::unnecessary_wraps)]
3881fn algebraic_parallel_cone_cylinder(
3882    cone: &ConicalSurface,
3883    cyl: &CylindricalSurface,
3884    v_range_cone: Option<(f64, f64)>,
3885    v_range_cyl: Option<(f64, f64)>,
3886) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3887    let axis = cone.axis();
3888    if axis.dot(cyl.axis()).abs() < 1.0 - 1e-10 {
3889        return Ok(None); // Skew or oblique: `ruling_cone_cylinder` traces it.
3890    }
3891
3892    let apex = cone.apex();
3893    let delta = cyl.origin() - apex;
3894    let along = delta.dot(axis);
3895    let perp = delta - axis * along;
3896    let d = perp.length();
3897    if d < 1e-9 {
3898        return Ok(None); // Coaxial — `exact_cone_cylinder` owns this.
3899    }
3900
3901    let (e1, e2) = (cone.x_axis(), cone.y_axis());
3902    let phi0 = perp.dot(e2).atan2(perp.dot(e1));
3903
3904    let (sin_t, cos_t) = cone.half_angle().sin_cos();
3905    if cos_t < 1e-12 || sin_t < 1e-12 {
3906        return Ok(None);
3907    }
3908    let r = cyl.radius();
3909
3910    // Branch existence: |d - R| <= rho <= d + R, with rho = v * cos(half_angle).
3911    let mut v_min = (d - r).abs() / cos_t;
3912    let mut v_max = (d + r) / cos_t;
3913    if v_max <= v_min {
3914        return Ok(Some(vec![]));
3915    }
3916
3917    // Narrow the sampled span to the faces' own extents so the fixed sample
3918    // budget resolves the in-face part of the curve rather than spreading over
3919    // a loop that mostly lies off both patches. A face's crossing can be a
3920    // fraction of a degree of the cone's sweep (the corner-round case above),
3921    // and an unnarrowed sampling puts fewer than one sample across it.
3922    let mut lo = v_min;
3923    let mut hi = v_max;
3924    // Clip EXACTLY to the hints, not to a padded window: an endpoint that lands
3925    // exactly on the face's own v-limit lies ON that boundary rim, so the
3926    // downstream pave machinery anchors it to the rim edge instead of leaving
3927    // the section dangling just past the face.
3928    if let Some((a, b)) = v_range_cone {
3929        let (a, b) = if a <= b { (a, b) } else { (b, a) };
3930        lo = lo.max(a);
3931        hi = hi.min(b);
3932    }
3933    if let Some((a, b)) = v_range_cyl {
3934        // The cylinder's v is a signed distance along its axis from its origin;
3935        // convert both ends to the cone's v via the shared axial direction.
3936        let flip = cyl.axis().dot(axis);
3937        let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
3938        let (a, b) = (to_cone_v(a), to_cone_v(b));
3939        let (a, b) = if a <= b { (a, b) } else { (b, a) };
3940        lo = lo.max(a);
3941        hi = hi.min(b);
3942    }
3943    let (turn_lo, turn_hi) = (v_min, v_max);
3944    v_min = lo.max(v_min);
3945    v_max = hi.min(v_max);
3946    if v_max - v_min <= 1e-12 {
3947        return Ok(Some(vec![]));
3948    }
3949    // A cylinder beside the axis, with both turning points inside both faces,
3950    // meets the cone in a whole loop: traced along the cylinder's rulings,
3951    // each of which meets the nappe once, it comes back as one closed curve,
3952    // which the band split of the cylinder it winds needs. Around the axis
3953    // the loop winds the cone too and stays in two branches, and so does a
3954    // wall passing so near the axis that the loop's bend there, about
3955    // `(d - r) / sqrt(d r)` of a turn wide, spans fewer than a few rulings.
3956    let slack = Tolerance::new().linear;
3957    #[allow(clippy::cast_precision_loss)]
3958    let resolved = d - r > 3.0 * (d * r).sqrt() * TAU / RULING_SAMPLES as f64;
3959    if v_min <= turn_lo + slack && v_max >= turn_hi - slack && resolved {
3960        let mut pts: Vec<Point3> = (0..RULING_SAMPLES)
3961            .map(|i| {
3962                let (sin_u, cos_u) = ruling_u(i).sin_cos();
3963                let foot = cyl.origin() + (cyl.x_axis() * cos_u + cyl.y_axis() * sin_u) * r;
3964                let off = foot - apex;
3965                let across = off - axis * off.dot(axis);
3966                apex + across + axis * (across.length() * sin_t / cos_t)
3967            })
3968            .collect();
3969        pts.push(pts[0]);
3970        return Ok(Some(fit_ruling_loops(&[pts], |p| {
3971            (cone.project_point(p), cyl.project_point(p))
3972        })));
3973    }
3974
3975    let n_samples = 128;
3976    let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
3977    let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
3978    #[allow(clippy::cast_precision_loss)]
3979    for i in 0..=n_samples {
3980        let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
3981        let rho = v * cos_t;
3982        if rho < 1e-12 {
3983            // The apex. `cos_alpha` has rho in its denominator, so it is only
3984            // meaningful in the limit: it tends to 0 (alpha -> pi/2) when the
3985            // cylinder passes exactly through the apex (d == R), and diverges
3986            // otherwise — where the clamp would manufacture a spurious alpha of
3987            // 0 or pi. So keep the apex only in the d == R case, where it is a
3988            // genuine point of the intersection and the shared endpoint at
3989            // which the two branches meet.
3990            if (d - r).abs() < 1e-12 {
3991                let apex = cone.evaluate(phi0, v);
3992                plus.push(apex);
3993                minus.push(apex);
3994            }
3995            continue;
3996        }
3997        let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
3998        let alpha = cos_alpha.acos();
3999        plus.push(cone.evaluate(phi0 + alpha, v));
4000        minus.push(cone.evaluate(phi0 - alpha, v));
4001    }
4002
4003    let mut curves = Vec::new();
4004    for pts in [&plus, &minus] {
4005        // Fewer than four samples in range means this branch does not cross the
4006        // bounded region at all (the other branch may still).
4007        if pts.len() < 4 {
4008            continue;
4009        }
4010        let ipts: Vec<IntersectionPoint> = pts
4011            .iter()
4012            .map(|&p| IntersectionPoint {
4013                point: p,
4014                param1: cone.project_point(p),
4015                param2: cyl.project_point(p),
4016            })
4017            .collect();
4018        let degree = 3.min(pts.len() - 1);
4019        match interpolate(pts, degree) {
4020            Ok(curve) => curves.push(IntersectionCurve {
4021                curve,
4022                points: ipts,
4023            }),
4024            // Emitting only the branch that happened to fit would starve the
4025            // section chain of exactly the piece this path exists to supply —
4026            // the same silent half-answer the marcher's fragments produced.
4027            // Defer the whole pair to the caller's other paths instead.
4028            Err(_) => return Ok(None),
4029        }
4030    }
4031
4032    Ok(Some(curves))
4033}
4034
4035/// Algebraic sphere-sphere intersection.
4036///
4037/// Two spheres intersect in a circle lying in the radical plane.
4038/// The radical plane is perpendicular to the line connecting the centers,
4039/// at a distance d1 from center1 where:
4040///   d1 = (D² + R1² - R2²) / (2D)
4041/// and D is the distance between centers.
4042fn algebraic_sphere_sphere(
4043    s1: &SphericalSurface,
4044    s2: &SphericalSurface,
4045) -> Result<Vec<IntersectionCurve>, MathError> {
4046    let c1 = s1.center();
4047    let c2 = s2.center();
4048    let r1 = s1.radius();
4049    let r2 = s2.radius();
4050
4051    let delta = c2 - c1;
4052    let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
4053    let d = d_sq.sqrt();
4054
4055    if d < 1e-12 {
4056        // Concentric spheres: no intersection (unless same radius → degenerate).
4057        return Ok(vec![]);
4058    }
4059
4060    // Check separation conditions.
4061    if d > r1 + r2 + 1e-10 {
4062        return Ok(vec![]); // Too far apart
4063    }
4064    if d + r2.min(r1) + 1e-10 < r1.max(r2) {
4065        return Ok(vec![]); // One inside the other
4066    }
4067
4068    // Distance from c1 to the radical plane along the center line.
4069    let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
4070
4071    // Radius of the intersection circle.
4072    let r_circle_sq = r1 * r1 - d1 * d1;
4073    if r_circle_sq < 0.0 {
4074        // Tangent or no intersection (numerical noise).
4075        if r_circle_sq > -1e-10 {
4076            // Tangent: single point.
4077            let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
4078            let tangent_pt = Point3::new(
4079                c1.x() + axis.x() * d1,
4080                c1.y() + axis.y() * d1,
4081                c1.z() + axis.z() * d1,
4082            );
4083            let ipt = IntersectionPoint {
4084                point: tangent_pt,
4085                param1: (0.0, 0.0),
4086                param2: (0.0, 0.0),
4087            };
4088            // Single-point "curve" — not very useful but correct.
4089            return Ok(vec![IntersectionCurve {
4090                curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
4091                points: vec![ipt],
4092            }]);
4093        }
4094        return Ok(vec![]);
4095    }
4096
4097    let r_circle = r_circle_sq.sqrt();
4098    let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
4099    let center = Point3::new(
4100        c1.x() + axis.x() * d1,
4101        c1.y() + axis.y() * d1,
4102        c1.z() + axis.z() * d1,
4103    );
4104
4105    // Build a reference frame for the circle.
4106    let basis = Frame3::from_normal(center, axis)?;
4107    let u_dir = basis.x;
4108    let v_dir = basis.y;
4109
4110    // Sample points along the circle for the IntersectionCurve.
4111    let n_samples = 33; // Odd for symmetry
4112    let mut points = Vec::with_capacity(n_samples);
4113    #[allow(clippy::cast_precision_loss)]
4114    for i in 0..n_samples {
4115        let theta = TAU * i as f64 / (n_samples - 1) as f64;
4116        let (sin_t, cos_t) = theta.sin_cos();
4117        let pt = Point3::new(
4118            center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
4119            center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
4120            center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
4121        );
4122        points.push(IntersectionPoint {
4123            point: pt,
4124            param1: (0.0, 0.0),
4125            param2: (0.0, 0.0),
4126        });
4127    }
4128
4129    let curve = conic_loop(center, u_dir, v_dir, r_circle, r_circle)?;
4130
4131    Ok(vec![IntersectionCurve { curve, points }])
4132}
4133
4134/// Newton correction: project a point back onto the intersection curve
4135/// of two analytic surfaces. Solves the 3×3 system:
4136///   δ · na = -da  (eliminate distance to surface A)
4137///   δ · nb = -db  (eliminate distance to surface B)
4138///   δ · t  = 0    (minimal correction, perpendicular to tangent)
4139#[allow(clippy::too_many_arguments)]
4140fn correct_to_intersection(
4141    a: &AnalyticSurface<'_>,
4142    b: &AnalyticSurface<'_>,
4143    surf_a: &dyn Fn(f64, f64) -> Point3,
4144    norm_a: &dyn Fn(f64, f64) -> Vec3,
4145    surf_b: &dyn Fn(f64, f64) -> Point3,
4146    norm_b: &dyn Fn(f64, f64) -> Vec3,
4147    point: Point3,
4148    u_range_a: (f64, f64),
4149    v_range_a: (f64, f64),
4150    u_range_b: (f64, f64),
4151    v_range_b: (f64, f64),
4152    max_iters: usize,
4153) -> Point3 {
4154    let mut p = point;
4155    for _ in 0..max_iters {
4156        let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
4157        let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
4158        let pa = surf_a(ua, va);
4159        let pb = surf_b(ub, vb);
4160        let na = norm_a(ua, va);
4161        let nb = norm_b(ub, vb);
4162        let pv = Vec3::new(p.x(), p.y(), p.z());
4163
4164        let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
4165        let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
4166
4167        if da.abs() < 1e-7 && db.abs() < 1e-7 {
4168            break;
4169        }
4170
4171        let t = na.cross(nb);
4172        let t_len = t.length();
4173        if t_len < 1e-10 {
4174            // Surfaces are tangent — fall back to midpoint.
4175            return Point3::new(
4176                (pa.x() + pb.x()) * 0.5,
4177                (pa.y() + pb.y()) * 0.5,
4178                (pa.z() + pb.z()) * 0.5,
4179            );
4180        }
4181        let t_hat = t * (1.0 / t_len);
4182
4183        // Solve [na; nb; t_hat] · δ = [-da, -db, 0] via Cramer's rule.
4184        let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
4185            - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
4186            + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
4187        if det.abs() < 1e-15 {
4188            return Point3::new(
4189                (pa.x() + pb.x()) * 0.5,
4190                (pa.y() + pb.y()) * 0.5,
4191                (pa.z() + pb.z()) * 0.5,
4192            );
4193        }
4194        let inv = 1.0 / det;
4195        // Cramer's rule: replace each column of A with rhs = (-da, -db, 0).
4196        let dx = inv
4197            * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
4198                + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
4199        let dy = inv
4200            * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
4201                - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
4202        let dz = inv
4203            * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
4204                + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
4205        let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
4206
4207        // Divergence guard: if the correction moves farther from both
4208        // surfaces, abandon Newton and return the best point so far.
4209        let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
4210        let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
4211        let pc_a = surf_a(uc, vc);
4212        let pc_b = surf_b(ud, vd);
4213        let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
4214        let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
4215            .dot(norm_a(uc, vc))
4216            .abs();
4217        let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
4218            .dot(norm_b(ud, vd))
4219            .abs();
4220        if da_new > da.abs() && db_new > db.abs() {
4221            return p;
4222        }
4223
4224        p = candidate;
4225    }
4226    p
4227}
4228
4229/// March along the intersection of two surfaces from a seed point.
4230///
4231/// Uses the cross product of surface normals as the tangent direction
4232/// and projects back onto both surfaces using analytical projection
4233/// (for cylinders/spheres) or grid search (fallback).
4234#[allow(clippy::too_many_arguments)]
4235fn march_analytic_intersection(
4236    a: &AnalyticSurface<'_>,
4237    b: &AnalyticSurface<'_>,
4238    surf_a: &dyn Fn(f64, f64) -> Point3,
4239    norm_a: &dyn Fn(f64, f64) -> Vec3,
4240    surf_b: &dyn Fn(f64, f64) -> Point3,
4241    norm_b: &dyn Fn(f64, f64) -> Vec3,
4242    seed: Point3,
4243    u_range_a: (f64, f64),
4244    v_range_a: (f64, f64),
4245    u_range_b: (f64, f64),
4246    v_range_b: (f64, f64),
4247    initial_step: f64,
4248    u_periodic_a: bool,
4249    u_periodic_b: bool,
4250    region: Option<Aabb3>,
4251) -> Vec<Point3> {
4252    let max_steps = 500;
4253    let h_min = 1e-6;
4254    let h_max = initial_step * 4.0;
4255    // Fixed closure threshold: the adaptive step `h` varies with curvature
4256    // and can shrink below the actual miss distance at the seed re-approach.
4257    // Use `initial_step * 5` to robustly detect closure on the first pass.
4258    let closure_dist = initial_step * 5.0;
4259    // Angular thresholds for curvature-adaptive stepping.
4260    let max_angle = 10.0_f64.to_radians();
4261    let min_angle = 2.0_f64.to_radians();
4262
4263    // March forward from seed, collecting points.
4264    let mut forward = Vec::new();
4265    // March backward from seed, collecting points (reversed at end).
4266    let mut backward = Vec::new();
4267
4268    for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
4269        let mut current = seed;
4270        let mut h = initial_step;
4271        let mut prev_tangent: Option<Vec3> = None;
4272
4273        for _ in 0..max_steps {
4274            let (ua, va) = project_analytic(a, current, u_range_a, v_range_a);
4275            let (ub, vb) = project_analytic(b, current, u_range_b, v_range_b);
4276
4277            let na = norm_a(ua, va);
4278            let nb = norm_b(ub, vb);
4279
4280            let tangent = na.cross(nb);
4281            let t_len = tangent.length();
4282            if t_len < 1e-10 {
4283                break;
4284            }
4285            let t_dir = tangent * (direction / t_len);
4286
4287            // Curvature-adaptive step: check angular deviation from previous tangent.
4288            if let Some(prev_t) = prev_tangent {
4289                let cos_angle = prev_t.dot(t_dir).clamp(-1.0, 1.0);
4290                let angle = cos_angle.acos();
4291                if angle > max_angle && h > h_min {
4292                    h = (h * 0.5).max(h_min);
4293                } else if angle < min_angle {
4294                    h = (h * 2.0).min(h_max);
4295                }
4296            }
4297            prev_tangent = Some(t_dir);
4298
4299            let next = Point3::new(
4300                h.mul_add(t_dir.x(), current.x()),
4301                h.mul_add(t_dir.y(), current.y()),
4302                h.mul_add(t_dir.z(), current.z()),
4303            );
4304
4305            let (ua2, va2) = project_analytic(a, next, u_range_a, v_range_a);
4306            let (ub2, vb2) = project_analytic(b, next, u_range_b, v_range_b);
4307
4308            let pa = surf_a(ua2, va2);
4309            let pb = surf_b(ub2, vb2);
4310            let mid = Point3::new(
4311                (pa.x() + pb.x()) * 0.5,
4312                (pa.y() + pb.y()) * 0.5,
4313                (pa.z() + pb.z()) * 0.5,
4314            );
4315            let out_a = (!u_periodic_a && (ua2 <= u_range_a.0 || ua2 >= u_range_a.1))
4316                || va2 <= v_range_a.0
4317                || va2 >= v_range_a.1;
4318            let out_b = (!u_periodic_b && (ub2 <= u_range_b.0 || ub2 >= u_range_b.1))
4319                || vb2 <= v_range_b.0
4320                || vb2 >= v_range_b.1;
4321
4322            if out_a || out_b {
4323                break;
4324            }
4325            if region.is_some_and(|r| !r.contains_point(mid)) {
4326                points.push(mid);
4327                break;
4328            }
4329
4330            // Check for loop closure — if we've collected enough points and
4331            // the current point is close to the seed, the curve is closed.
4332            // Require ≥10 steps to avoid premature closure near the seed.
4333            let dist_to_seed = (mid - seed).length();
4334            if points.len() > 10 && dist_to_seed < closure_dist {
4335                points.push(seed);
4336                break;
4337            }
4338
4339            points.push(mid);
4340            current = mid;
4341        }
4342    }
4343
4344    // Assemble result: backward (reversed) + seed + forward
4345    backward.reverse();
4346    let mut result = backward;
4347    result.push(seed);
4348    result.append(&mut forward);
4349
4350    // Refine all points onto the intersection curve via Newton correction.
4351    for pt in &mut result {
4352        *pt = correct_to_intersection(
4353            a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b, v_range_b,
4354            5,
4355        );
4356    }
4357
4358    result
4359}
4360
4361/// Project a 3D point onto an analytic surface using the surface's
4362/// analytical projection method. Falls back to grid search for surface
4363/// types without analytical projection.
4364fn project_analytic(
4365    surface: &AnalyticSurface<'_>,
4366    point: Point3,
4367    u_range: (f64, f64),
4368    v_range: (f64, f64),
4369) -> (f64, f64) {
4370    match surface {
4371        AnalyticSurface::Cylinder(cyl) => {
4372            let (u, v) = cyl.project_point(point);
4373            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4374        }
4375        AnalyticSurface::Sphere(sphere) => {
4376            let (u, v) = sphere.project_point(point);
4377            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4378        }
4379        AnalyticSurface::Cone(cone) => {
4380            let (u, v) = cone.project_point(point);
4381            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4382        }
4383        AnalyticSurface::Torus(torus) => {
4384            let (u, v) = torus.project_point(point);
4385            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4386        }
4387    }
4388}
4389
4390/// Returns `true` if the surface's u-parameter is periodic (wraps around 2π).
4391/// All current `AnalyticSurface` variants have periodic u — this is trivially
4392/// true today but exists as a guard for future non-periodic analytic types.
4393fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
4394    matches!(
4395        surface,
4396        AnalyticSurface::Cylinder(_)
4397            | AnalyticSurface::Cone(_)
4398            | AnalyticSurface::Sphere(_)
4399            | AnalyticSurface::Torus(_)
4400    )
4401}
4402
4403/// Extract closures and parameter ranges for an analytic surface.
4404#[allow(clippy::type_complexity)]
4405fn surface_closures<'a>(
4406    surface: &'a AnalyticSurface<'a>,
4407) -> (
4408    Box<dyn Fn(f64, f64) -> Point3 + 'a>,
4409    Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
4410    (f64, f64),
4411    (f64, f64),
4412) {
4413    match surface {
4414        AnalyticSurface::Cylinder(cyl) => (
4415            Box::new(|u, v| cyl.evaluate(u, v)),
4416            Box::new(|u, v| cyl.normal(u, v)),
4417            (0.0, TAU),
4418            (-1.0, 1.0),
4419        ),
4420        AnalyticSurface::Cone(cone) => (
4421            Box::new(|u, v| cone.evaluate(u, v)),
4422            Box::new(|u, v| cone.normal(u, v)),
4423            (0.0, TAU),
4424            (0.01, 2.0),
4425        ),
4426        AnalyticSurface::Sphere(sphere) => (
4427            Box::new(|u, v| sphere.evaluate(u, v)),
4428            Box::new(|u, v| sphere.normal(u, v)),
4429            (0.0, TAU),
4430            (-FRAC_PI_2, FRAC_PI_2),
4431        ),
4432        AnalyticSurface::Torus(torus) => (
4433            Box::new(|u, v| torus.evaluate(u, v)),
4434            Box::new(|u, v| torus.normal(u, v)),
4435            (0.0, TAU),
4436            (0.0, TAU),
4437        ),
4438    }
4439}
4440
4441#[cfg(test)]
4442#[allow(clippy::unwrap_used, clippy::expect_used)]
4443mod tests {
4444    use super::*;
4445    use crate::tolerance::Tolerance;
4446
4447    /// Arcs of a cone's hyperbola (a plane parallel to the axis) and parabola
4448    /// (a plane parallel to a ruling) between two of their sampled points
4449    /// stay on both the plane and the cone everywhere, not just at samples.
4450    #[test]
4451    fn plane_cone_conic_arcs_lie_on_both_surfaces() {
4452        let half_angle = 1.1_f64;
4453        let cone = ConicalSurface::new(
4454            Point3::new(0.0, 0.0, 0.0),
4455            Vec3::new(0.0, 0.0, 1.0),
4456            half_angle,
4457        )
4458        .unwrap();
4459        let ruling = Vec3::new(half_angle.sin(), 0.0, half_angle.cos());
4460        for (normal, d) in [(Vec3::new(1.0, 0.0, 0.0), 0.5), (ruling, 1.0)] {
4461            let chains =
4462                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, d, 10.0)
4463                    .unwrap();
4464            let chain = chains
4465                .iter()
4466                .find_map(|c| match c {
4467                    ExactIntersectionCurve::Points(chain) => Some(chain),
4468                    _ => None,
4469                })
4470                .expect("a parabola or hyperbola section is sampled");
4471            let (from, to) = (chain[2], chain[chain.len() - 3]);
4472            let arc = plane_cone_conic_arc(&cone, normal, d, from, to)
4473                .unwrap()
4474                .expect("an exact arc");
4475            let (t0, t1) = arc.domain();
4476            assert!((arc.evaluate(t0) - from).length() < 1e-12);
4477            assert!((arc.evaluate(t1) - to).length() < 1e-12);
4478            for i in 0..=200 {
4479                let q = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0);
4480                let w = q - Point3::new(0.0, 0.0, 0.0);
4481                let off_plane = (normal.dot(w) - d).abs();
4482                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
4483                assert!(off_plane < 1e-9, "off the plane by {off_plane}");
4484                assert!(off_cone < 1e-9, "off the cone by {off_cone}");
4485            }
4486        }
4487    }
4488
4489    /// A plane a few 1e-10 short of parallel to a ruling cuts a vast ellipse
4490    /// that the parabola's closed form only approximates: the arc is either
4491    /// declined or on the cone, and an arc with coincident ends is declined.
4492    #[test]
4493    fn plane_cone_conic_arc_declines_a_near_parabolic_ellipse() {
4494        let half_angle = 1.1_f64;
4495        let cone = ConicalSurface::new(
4496            Point3::new(0.0, 0.0, 0.0),
4497            Vec3::new(0.0, 0.0, 1.0),
4498            half_angle,
4499        )
4500        .unwrap();
4501        for shortfall in [1e-10, 3e-10, 8e-10] {
4502            let tilt = half_angle - shortfall / (2.0 * half_angle).sin();
4503            let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
4504            let chains =
4505                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, 1.0, 10.0)
4506                    .unwrap();
4507            let Some(chain) = chains.iter().find_map(|c| match c {
4508                ExactIntersectionCurve::Points(chain) => Some(chain),
4509                _ => None,
4510            }) else {
4511                continue;
4512            };
4513            let (from, to) = (chain[2], chain[chain.len() - 3]);
4514            assert!(
4515                plane_cone_conic_arc(&cone, normal, 1.0, from, from)
4516                    .unwrap()
4517                    .is_none(),
4518                "coincident ends"
4519            );
4520            let Some(arc) = plane_cone_conic_arc(&cone, normal, 1.0, from, to).unwrap() else {
4521                continue;
4522            };
4523            let (t0, t1) = arc.domain();
4524            for i in 0..=200 {
4525                let w = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0)
4526                    - Point3::new(0.0, 0.0, 0.0);
4527                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
4528                assert!(off_cone < 1e-8, "{shortfall}: off the cone by {off_cone}");
4529            }
4530        }
4531    }
4532
4533    #[test]
4534    fn plane_cylinder_perpendicular() {
4535        let cyl =
4536            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
4537                .unwrap();
4538
4539        // Horizontal plane at z=3 -- produces a circle at height 3.
4540        let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
4541        assert!(!curves.is_empty(), "should find intersection curve");
4542        assert!(
4543            curves[0].points.len() > 10,
4544            "should have many sample points"
4545        );
4546
4547        let tol = Tolerance::loose();
4548        for pt in &curves[0].points {
4549            assert!(
4550                tol.approx_eq(pt.point.z(), 3.0),
4551                "z should be ~3.0, got {}",
4552                pt.point.z()
4553            );
4554            let r = pt.point.x().hypot(pt.point.y());
4555            assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
4556        }
4557    }
4558
4559    #[test]
4560    fn plane_sphere_equator() {
4561        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
4562
4563        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
4564        assert!(!curves.is_empty());
4565
4566        let tol = Tolerance::loose();
4567        for pt in &curves[0].points {
4568            assert!(
4569                tol.approx_eq(pt.point.z(), 0.0),
4570                "z should be ~0, got {}",
4571                pt.point.z()
4572            );
4573            let r = pt.point.x().hypot(pt.point.y());
4574            assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
4575        }
4576    }
4577
4578    #[test]
4579    fn plane_sphere_no_intersection() {
4580        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
4581
4582        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
4583        assert!(curves.is_empty());
4584    }
4585
4586    #[test]
4587    fn plane_cone_cross_section() {
4588        let cone = ConicalSurface::new(
4589            Point3::new(0.0, 0.0, 0.0),
4590            Vec3::new(0.0, 0.0, 1.0),
4591            std::f64::consts::FRAC_PI_4,
4592        )
4593        .unwrap();
4594
4595        let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
4596        assert!(!curves.is_empty(), "should find intersection with cone");
4597    }
4598
4599    /// The 1u gridfinity spacer lip fuse corner (#1570): the body's lip
4600    /// recess cone (45 deg, opening downward) meets the tool's lip cone
4601    /// (45 deg, opening upward) with axes offset 0.25mm in x and y. Equal
4602    /// half-angle tangents put the whole intersection on the radical plane,
4603    /// so the section is one exact ellipse; the marcher shredded this into
4604    /// ~64 closed micro-loops per pair.
4605    #[test]
4606    fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
4607        let c1 = ConicalSurface::new(
4608            Point3::new(
4609                -16.999_999_999_999_975,
4610                -16.999_999_999_999_975,
4611                5.849_999_999_999_951,
4612            ),
4613            Vec3::new(0.0, 0.0, -1.0),
4614            0.785_398_163_397_433_5,
4615        )
4616        .unwrap();
4617        let c2 = ConicalSurface::new(
4618            Point3::new(
4619                -16.750_000_000_000_036,
4620                -16.750_000_000_000_018,
4621                0.749_999_999_999_881,
4622            ),
4623            Vec3::new(0.0, 0.0, 1.0),
4624            0.785_398_163_397_467_6,
4625        )
4626        .unwrap();
4627
4628        let curves = exact_cone_cone(&c1, &c2)
4629            .unwrap()
4630            .expect("offset parallel equal-angle cones must take the radical-plane path");
4631        assert_eq!(curves.len(), 1, "expected exactly one section conic");
4632        assert!(
4633            matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
4634            "expected an ellipse section, got {:?}",
4635            curves[0]
4636        );
4637        let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
4638            return;
4639        };
4640
4641        // Every sample must lie on BOTH cones: distance to the axis equals
4642        // tan(half_angle) times the axial distance from the apex, on the
4643        // real nappe of each.
4644        for i in 0..16 {
4645            let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
4646            for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
4647                let rel = p - cone.apex();
4648                let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
4649                let axial = rel_v.dot(cone.axis());
4650                let radial = (rel_v - cone.axis() * axial).length();
4651                assert!(
4652                    axial > 0.0,
4653                    "{label}: sample on phantom nappe (axial {axial})"
4654                );
4655                let expect = cone.half_angle().tan() * axial;
4656                assert!(
4657                    (radial - expect).abs() < 1e-9,
4658                    "{label}: sample off surface by {}",
4659                    (radial - expect).abs()
4660                );
4661            }
4662        }
4663    }
4664
4665    /// Opposed cones whose real nappes occupy disjoint half-spaces share a
4666    /// radical-plane conic only on the phantom nappe — the exact path must
4667    /// report a definitive empty intersection, not defer to the marcher.
4668    #[test]
4669    fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
4670        let c1 = ConicalSurface::new(
4671            Point3::new(0.0, 0.0, 5.0),
4672            Vec3::new(0.0, 0.0, -1.0),
4673            std::f64::consts::FRAC_PI_4,
4674        )
4675        .unwrap();
4676        let c2 = ConicalSurface::new(
4677            Point3::new(0.25, 0.25, 20.0),
4678            Vec3::new(0.0, 0.0, 1.0),
4679            std::f64::consts::FRAC_PI_4,
4680        )
4681        .unwrap();
4682        let curves = exact_cone_cone(&c1, &c2)
4683            .unwrap()
4684            .expect("radical-plane path");
4685        assert!(curves.is_empty(), "disjoint nappes must yield no curves");
4686    }
4687
4688    /// Unequal half-angles keep a quadratic term in the pencil — no plane
4689    /// reduction exists, so the exact path must defer to the marcher.
4690    #[test]
4691    fn offset_parallel_cones_with_unequal_angles_defer() {
4692        let c1 = ConicalSurface::new(
4693            Point3::new(0.0, 0.0, 5.0),
4694            Vec3::new(0.0, 0.0, -1.0),
4695            std::f64::consts::FRAC_PI_4,
4696        )
4697        .unwrap();
4698        let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
4699            .unwrap();
4700        assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
4701    }
4702
4703    /// A 45 degree cone and a radius 0.1 tube tilted 40 degrees that pierces
4704    /// both nappes, so the ruling path declines and the general marcher runs:
4705    /// the tube's axis meets the near nappe at (0.1, -1.368, 1.370).
4706    fn cone_and_tilted_tube() -> (ConicalSurface, CylindricalSurface) {
4707        let cone = ConicalSurface::new(
4708            Point3::new(0.0, 0.0, 0.0),
4709            Vec3::new(0.0, 0.0, 1.0),
4710            std::f64::consts::FRAC_PI_4,
4711        )
4712        .unwrap();
4713        let (s, c) = 40.0_f64.to_radians().sin_cos();
4714        let tube =
4715            CylindricalSurface::new(Point3::new(0.1, 0.0, 3.0), Vec3::new(0.0, s, c), 0.1).unwrap();
4716        (cone, tube)
4717    }
4718
4719    #[test]
4720    fn marcher_keeps_to_its_region() {
4721        let (cone, tube) = cone_and_tilted_tube();
4722        let run = |region: Option<Aabb3>| {
4723            let (a, b) = (
4724                AnalyticSurface::Cone(&cone),
4725                AnalyticSurface::Cylinder(&tube),
4726            );
4727            let (va, vb) = (Some((0.5, 4.0)), Some((-5.0, 5.0)));
4728            match region {
4729                Some(r) => intersect_analytic_analytic_in_region(a, b, 32, va, vb, r),
4730                None => intersect_analytic_analytic_bounded(a, b, 32, va, vb),
4731            }
4732            .unwrap()
4733        };
4734        assert!(!run(None).is_empty());
4735        let near = Aabb3 {
4736            min: Point3::new(-0.5, -2.0, 0.8),
4737            max: Point3::new(0.7, -0.7, 2.0),
4738        };
4739        let curves = run(Some(near));
4740        assert!(!curves.is_empty(), "the loop through the region is kept");
4741        // The region's margin (two grid cells) and one marching step past it.
4742        let reach = near.expanded(0.6);
4743        for curve in &curves {
4744            assert!(curve.points.iter().all(|p| reach.contains_point(p.point)));
4745        }
4746        let away = Aabb3 {
4747            min: Point3::new(5.0, 5.0, 5.0),
4748            max: Point3::new(6.0, 6.0, 6.0),
4749        };
4750        assert!(run(Some(away)).is_empty(), "nothing is marched outside it");
4751    }
4752
4753    #[test]
4754    fn coaxial_cones_cross_at_single_circle() {
4755        // Two coaxial truncated cones (outer base r10->top r8, inner r9->r8
4756        // over height 10) cross where their radii match: z=10, r=8. The
4757        // intersection must be ONE clean circle, not the dozens of degenerate
4758        // micro-curves the general marcher produces at near-tangency.
4759        let outer = ConicalSurface::new(
4760            Point3::new(0.0, 0.0, 50.0),
4761            Vec3::new(0.0, 0.0, -1.0),
4762            5.0_f64.atan(),
4763        )
4764        .unwrap();
4765        let inner = ConicalSurface::new(
4766            Point3::new(0.0, 0.0, 90.0),
4767            Vec3::new(0.0, 0.0, -1.0),
4768            10.0_f64.atan(),
4769        )
4770        .unwrap();
4771
4772        let curves = intersect_analytic_analytic_bounded(
4773            AnalyticSurface::Cone(&outer),
4774            AnalyticSurface::Cone(&inner),
4775            32,
4776            None,
4777            None,
4778        )
4779        .unwrap();
4780
4781        assert_eq!(
4782            curves.len(),
4783            1,
4784            "coaxial cones crossing at one circle must yield exactly one curve, got {}",
4785            curves.len()
4786        );
4787        for p in &curves[0].points {
4788            let r = p.point.x().hypot(p.point.y());
4789            assert!(
4790                (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
4791                "intersection point off the expected z=10,r=8 circle: {:?}",
4792                p.point
4793            );
4794        }
4795    }
4796
4797    #[test]
4798    fn plane_torus_cross_section() {
4799        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
4800
4801        let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
4802        assert!(
4803            !curves.is_empty(),
4804            "should find intersection curves with torus"
4805        );
4806    }
4807
4808    /// A plane resting on a torus's tube touches it along one circle of the
4809    /// torus's own radius, ring or spindle, at the tube's top or bottom.
4810    #[test]
4811    fn plane_tangent_to_a_tube_touches_it_along_one_circle() {
4812        for (major, minor) in [(5.0, 1.0), (0.1, 2.45)] {
4813            let torus = ToroidalSurface::new(Point3::new(1.0, 2.0, 3.0), major, minor).unwrap();
4814            for z in [3.0 - minor, 3.0 + minor] {
4815                let exact = exact_plane_analytic(
4816                    AnalyticSurface::Torus(&torus),
4817                    Vec3::new(0.0, 0.0, 1.0),
4818                    z,
4819                )
4820                .unwrap();
4821                assert_eq!(exact.len(), 1, "R={major} r={minor} z={z}");
4822                let circle = match &exact[0] {
4823                    ExactIntersectionCurve::Circle(c) => Some(c),
4824                    _ => None,
4825                };
4826                let c = circle.expect("a circle");
4827                assert!((c.radius() - major).abs() < 1e-12);
4828                assert!((c.center() - Point3::new(1.0, 2.0, z)).length() < 1e-12);
4829
4830                let sampled = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), z).unwrap();
4831                assert_eq!(sampled.len(), 1, "R={major} r={minor} z={z}");
4832            }
4833            // A tilted plane cuts no single circle of radius R.
4834            let single = |normal: Vec3, d: f64| {
4835                matches!(
4836                    exact_plane_analytic(AnalyticSurface::Torus(&torus), normal, d)
4837                        .unwrap()
4838                        .as_slice(),
4839                    [ExactIntersectionCurve::Circle(_)]
4840                )
4841            };
4842            assert!(!single(Vec3::new(1e-6, 0.0, 1.0), 3.0 + minor));
4843        }
4844    }
4845
4846    /// Tangency is read from the plane's distance to the tube's top, so it
4847    /// survives rounding on a large torus, and a plane further inside than
4848    /// the linear tolerance still cuts its two circles.
4849    #[test]
4850    fn plane_tangent_to_a_large_tube_is_read_through_rounding() {
4851        let torus = ToroidalSurface::new(Point3::new(0.3, -0.7, 3.0), 200.0, 100.1).unwrap();
4852        let level = Vec3::new(0.0, 0.0, 1.0);
4853        let curves =
4854            |d: f64| exact_plane_analytic(AnalyticSurface::Torus(&torus), level, d).unwrap();
4855        assert!(matches!(
4856            curves(3.0 + 100.1).as_slice(),
4857            [ExactIntersectionCurve::Circle(_)]
4858        ));
4859        let inside = curves(3.0 + 100.1 - 4e-7);
4860        assert!(!matches!(
4861            inside.as_slice(),
4862            [ExactIntersectionCurve::Circle(_)]
4863        ));
4864    }
4865
4866    /// Signed distance of a point to a z-axis torus centred at the origin:
4867    /// `sqrt((sqrt(x^2+y^2) - R)^2 + z^2) - r`.
4868    fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
4869        let rho = p.x().hypot(p.y());
4870        ((rho - major).hypot(p.z())) - minor
4871    }
4872
4873    /// The gridfinity lightweight base's failing corner, reduced: a cavity
4874    /// corner-round cone (apex below the floor, 45 deg, axis +z) crossed by a
4875    /// parallel-axis boss cylinder. The general marcher returned ~49 overlapping
4876    /// partial traces of one curve here; the algebraic path must return exactly
4877    /// the two branches, each ON both surfaces and inside the cone's v-hint.
4878    #[test]
4879    fn oblique_cone_cylinder_traces_curves_on_both() {
4880        use crate::traits::ParametricCurve;
4881        // A pointed cone opening down from (0, 0, 3), radius half the depth,
4882        // and a rod along y through (x0, ., 1): one loop through the wall
4883        // when the rod pokes out, two when every ruling meets the cone.
4884        let cone = ConicalSurface::new(
4885            Point3::new(0.0, 0.0, 3.0),
4886            Vec3::new(0.0, 0.0, -1.0),
4887            2.0_f64.atan(),
4888        )
4889        .unwrap();
4890        for (x0, loops) in [(0.5, 1), (0.0, 2)] {
4891            let cyl =
4892                CylindricalSurface::new(Point3::new(x0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
4893                    .unwrap();
4894            for cone_first in [true, false] {
4895                let (a, b) = if cone_first {
4896                    (
4897                        AnalyticSurface::Cone(&cone),
4898                        AnalyticSurface::Cylinder(&cyl),
4899                    )
4900                } else {
4901                    (
4902                        AnalyticSurface::Cylinder(&cyl),
4903                        AnalyticSurface::Cone(&cone),
4904                    )
4905                };
4906                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
4907                assert_eq!(curves.len(), loops, "x0 {x0}: loops");
4908                for c in &curves {
4909                    let (t0, t1) = c.curve.domain();
4910                    for k in 0..=64 {
4911                        let t = (t1 - t0).mul_add(f64::from(k) / 64.0, t0);
4912                        let p = ParametricCurve::evaluate(&c.curve, t);
4913                        // A cubic through the ruling samples, bent most at the
4914                        // loop's branch points.
4915                        let rod = (p.x() - x0).hypot(p.z() - 1.0);
4916                        assert!(
4917                            (rod - 0.6).abs() < 1e-4,
4918                            "x0 {x0}: off the rod by {}",
4919                            rod - 0.6
4920                        );
4921                        let cone_r = p.x().hypot(p.y());
4922                        assert!(
4923                            (cone_r - 0.5 * (3.0 - p.z())).abs() < 1e-4,
4924                            "x0 {x0}: off the cone at {p:?}"
4925                        );
4926                    }
4927                }
4928            }
4929        }
4930    }
4931
4932    #[test]
4933    fn a_rod_through_a_rings_tube_traces_four_loops() {
4934        use crate::traits::ParametricCurve;
4935        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
4936        // Along y through (0.5, ., 0.3): every ruling enters and leaves the
4937        // tube on either side of the hole, four roots, four loops.
4938        let rod =
4939            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.3), Vec3::new(0.0, 1.0, 0.0), 0.6)
4940                .unwrap();
4941        let curves = ruling_torus_cylinder(&ring, &rod, true).unwrap();
4942        assert_eq!(curves.len(), 4);
4943        for c in &curves {
4944            let (t0, t1) = c.curve.domain();
4945            for k in 0..=64 {
4946                let p =
4947                    ParametricCurve::evaluate(&c.curve, (t1 - t0).mul_add(f64::from(k) / 64.0, t0));
4948                let on_rod = (p.x() - 0.5).hypot(p.z() - 0.3) - 0.6;
4949                let on_ring = (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
4950                assert!(
4951                    on_rod.abs() < 1e-4 && on_ring.abs() < 1e-4,
4952                    "off by {on_rod}, {on_ring}"
4953                );
4954            }
4955        }
4956        // Higher, the rod's top rulings pass over the tube: the count varies.
4957        let high =
4958            CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
4959                .unwrap();
4960        assert!(ruling_torus_cylinder(&ring, &high, true).is_none());
4961        // Its top clears the tube only between two sampled rulings.
4962        let grazing =
4963            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.9001), Vec3::new(0.0, 1.0, 0.0), 0.6)
4964                .unwrap();
4965        assert!(ruling_torus_cylinder(&ring, &grazing, true).is_none());
4966        // A spindle torus's quartic also holds its inner lemon.
4967        let spindle = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap();
4968        let thin =
4969            CylindricalSurface::new(Point3::new(0.3, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 0.2)
4970                .unwrap();
4971        assert!(ruling_torus_cylinder(&spindle, &thin, true).is_none());
4972    }
4973
4974    #[test]
4975    fn a_pin_through_a_ball_traces_two_loops() {
4976        use crate::traits::ParametricCurve;
4977        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
4978        // A pin tapering from radius 1.2 at (1, 0.5, -5) to 0.4 at 10 up:
4979        // radial 0.08 per unit of height.
4980        let half = 0.08_f64.atan();
4981        let apex = Point3::new(1.0, 0.5, -5.0 + 1.2 / 0.08);
4982        let pin = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, -1.0), FRAC_PI_2 - half).unwrap();
4983        for cone_first in [true, false] {
4984            let (a, b) = if cone_first {
4985                (AnalyticSurface::Cone(&pin), AnalyticSurface::Sphere(&ball))
4986            } else {
4987                (AnalyticSurface::Sphere(&ball), AnalyticSurface::Cone(&pin))
4988            };
4989            let curves = intersect_analytic_analytic(a, b, 32).unwrap();
4990            assert_eq!(curves.len(), 2, "entry and exit loops");
4991            for c in &curves {
4992                let (t0, t1) = c.curve.domain();
4993                for k in 0..=64 {
4994                    let p = ParametricCurve::evaluate(
4995                        &c.curve,
4996                        (t1 - t0).mul_add(f64::from(k) / 64.0, t0),
4997                    );
4998                    let on_ball = (p - Point3::new(0.0, 0.0, 0.0)).length() - 3.0;
4999                    let axial = apex.z() - p.z();
5000                    let on_pin = (p.x() - 1.0).hypot(p.y() - 0.5) - axial * half.tan();
5001                    assert!(
5002                        on_ball.abs() < 1e-4 && on_pin.abs() < 1e-4,
5003                        "off by {on_ball}, {on_pin}"
5004                    );
5005                }
5006            }
5007        }
5008        // On the ball's axis the loops are circles, which defer. A pin whose
5009        // apex is inside the ball leaves it once along every generator, and
5010        // one only partly through the ball meets it over the generators that
5011        // reach it: one loop each. One that opens away meets it not at all.
5012        let coaxial =
5013            ConicalSurface::new(Point3::new(0.0, 0.0, 10.0), Vec3::new(0.0, 0.0, -1.0), 1.4)
5014                .unwrap();
5015        assert!(ruling_cone_sphere(&coaxial, &ball, true).is_none());
5016        let aside = ConicalSurface::new(
5017            Point3::new(2.8, 0.0, 10.0),
5018            Vec3::new(0.0, 0.0, -1.0),
5019            FRAC_PI_2 - half,
5020        )
5021        .unwrap();
5022        assert_eq!(ruling_cone_sphere(&aside, &ball, true).unwrap().len(), 1);
5023        let holding = ConicalSurface::new(
5024            Point3::new(1.0, 0.5, 1.0),
5025            Vec3::new(0.0, 0.0, -1.0),
5026            FRAC_PI_2 - half,
5027        )
5028        .unwrap();
5029        assert_eq!(ruling_cone_sphere(&holding, &ball, true).unwrap().len(), 1);
5030        let away = ConicalSurface::new(
5031            Point3::new(1.0, 0.5, 10.0),
5032            Vec3::new(0.0, 0.0, 1.0),
5033            FRAC_PI_2 - half,
5034        )
5035        .unwrap();
5036        assert!(ruling_cone_sphere(&away, &ball, true).unwrap().is_empty());
5037        // Grazing: the generators that miss span about 0.002 radians,
5038        // narrower than a 2048-angle scan's step, and the near and far
5039        // roots join into one loop across them.
5040        let step = TAU / 2048.0;
5041        let grazed =
5042            SphericalSurface::new(Point3::new(step.cos(), step.sin(), 10.0), 9.255_250_971_8)
5043                .unwrap();
5044        let wide =
5045            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5).unwrap();
5046        assert_eq!(ruling_cone_sphere(&wide, &grazed, true).unwrap().len(), 1);
5047    }
5048
5049    #[test]
5050    fn a_ball_beside_a_cone_meets_it_in_one_loop() {
5051        use crate::traits::ParametricCurve;
5052        // Apex 3 up, opening downward, the radius half the depth below it.
5053        let cone = ConicalSurface::new(
5054            Point3::new(0.0, 0.0, 3.0),
5055            Vec3::new(0.0, 0.0, -1.0),
5056            2.0_f64.atan(),
5057        )
5058        .unwrap();
5059        for (centre, radius) in [
5060            (Point3::new(1.0, 0.8, 1.2), 1.1),
5061            (Point3::new(1.5, 0.0, 0.0), 0.8),
5062        ] {
5063            let ball = SphericalSurface::new(centre, radius).unwrap();
5064            let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
5065            assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
5066            let (t0, t1) = curves[0].curve.domain();
5067            for k in 0..=64 {
5068                let p = ParametricCurve::evaluate(
5069                    &curves[0].curve,
5070                    (t1 - t0).mul_add(f64::from(k) / 64.0, t0),
5071                );
5072                let on_ball = (p - centre).length() - radius;
5073                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5074                assert!(
5075                    on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5,
5076                    "ball at {centre:?}: off by {on_ball}, {on_cone}"
5077                );
5078            }
5079        }
5080        // A ball the nappe's generators miss, and one on the apex.
5081        let clear = SphericalSurface::new(Point3::new(4.0, 0.0, 0.0), 0.5).unwrap();
5082        assert!(ruling_cone_sphere(&cone, &clear, true).unwrap().is_empty());
5083        let on_apex = SphericalSurface::new(Point3::new(0.6, 0.0, 3.8), 1.0).unwrap();
5084        assert!(ruling_cone_sphere(&cone, &on_apex, true).is_none());
5085    }
5086
5087    #[test]
5088    fn a_ball_holding_a_cones_apex_meets_it_in_one_loop() {
5089        use crate::traits::ParametricCurve;
5090        let cone = ConicalSurface::new(
5091            Point3::new(0.0, 0.0, 3.0),
5092            Vec3::new(0.0, 0.0, -1.0),
5093            2.0_f64.atan(),
5094        )
5095        .unwrap();
5096        // Off the axis, and barely holding the apex: the generators pointing
5097        // away from the centre leave it just past the apex.
5098        for (centre, radius) in [
5099            (Point3::new(0.5, 0.0, 2.5), 2.0),
5100            (Point3::new(-0.4, 0.3, 2.0), 1.5),
5101            (Point3::new(0.0, 0.8, 3.0), 0.8001),
5102            (Point3::new(0.0, 0.8, 3.0), 0.800_001),
5103        ] {
5104            let ball = SphericalSurface::new(centre, radius).unwrap();
5105            let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
5106            assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
5107            let (t0, t1) = curves[0].curve.domain();
5108            for k in 0..=4096 {
5109                let p = ParametricCurve::evaluate(
5110                    &curves[0].curve,
5111                    (t1 - t0).mul_add(f64::from(k) / 4096.0, t0),
5112                );
5113                let on_ball = (p - centre).length() - radius;
5114                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5115                assert!(
5116                    on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5 && p.z() < 3.0,
5117                    "ball at {centre:?}: off by {on_ball}, {on_cone} at {p:?}"
5118                );
5119            }
5120        }
5121    }
5122
5123    #[test]
5124    fn oblique_cone_cylinder_defers_where_rulings_cannot_trace_it() {
5125        let t = 2.0_f64.atan();
5126        let cone =
5127            ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 0.0, -1.0), t).unwrap();
5128        // A rod through the apex meets the far nappe.
5129        let through_apex =
5130            CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
5131                .unwrap();
5132        assert!(ruling_cone_cylinder(&cone, &through_apex, true).is_none());
5133        // A rod along a generator meets each ruling once.
5134        let generator = Vec3::new(t.cos(), 0.0, -t.sin());
5135        let along = CylindricalSurface::new(Point3::new(0.0, 0.3, 0.0), generator, 0.2).unwrap();
5136        assert!(ruling_cone_cylinder(&cone, &along, true).is_none());
5137        // A pin's tip just through a tube's wall: the tube's rulings that
5138        // meet it span a window narrower than the sampling.
5139        let pin =
5140            ConicalSurface::new(Point3::new(20.5, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), t).unwrap();
5141        let tube =
5142            CylindricalSurface::new(Point3::new(0.0, 0.0, -10.0), Vec3::new(0.0, 0.0, 1.0), 20.0)
5143                .unwrap();
5144        assert!(ruling_cone_cylinder(&pin, &tube, true).is_none());
5145    }
5146
5147    #[test]
5148    fn parallel_cone_cylinder_gives_two_exact_branches() {
5149        use crate::traits::ParametricCurve;
5150        let cone = ConicalSurface::new(
5151            Point3::new(-5.45, -36.55, -4.85),
5152            Vec3::new(0.0, 0.0, 1.0),
5153            std::f64::consts::FRAC_PI_4,
5154        )
5155        .unwrap();
5156        let cyl = CylindricalSurface::new(
5157            Point3::new(-8.0, -34.0, -5.0),
5158            Vec3::new(0.0, 0.0, 1.0),
5159            4.45,
5160        )
5161        .unwrap();
5162        // The cone face spans z in [-3.8, -3.0]; v = (z - apex_z) / sin(45 deg).
5163        let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
5164        let curves = intersect_analytic_analytic_bounded(
5165            AnalyticSurface::Cone(&cone),
5166            AnalyticSurface::Cylinder(&cyl),
5167            32,
5168            Some(v_hint),
5169            Some((0.0, 2.5)),
5170        )
5171        .unwrap();
5172
5173        assert_eq!(curves.len(), 2, "expected exactly the two branches");
5174        for c in &curves {
5175            let (t0, t1) = c.curve.domain();
5176            for k in 0..=32 {
5177                let t = (t1 - t0).mul_add(f64::from(k) / 32.0, t0);
5178                let p = ParametricCurve::evaluate(&c.curve, t);
5179                // On the cylinder: radial distance from its axis is the radius.
5180                let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
5181                assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
5182                // On the cone: radial distance from its axis is z - apex_z.
5183                let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
5184                assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
5185                // Inside the cone face's own v-window (the hint is respected).
5186                assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
5187            }
5188        }
5189    }
5190
5191    #[test]
5192    fn parallel_rod_through_a_cones_wall_closes_one_loop() {
5193        use crate::traits::ParametricCurve;
5194        // Apex 3 up, opening downward, the radius half the depth below it.
5195        let cone = ConicalSurface::new(
5196            Point3::new(0.0, 0.0, 3.0),
5197            Vec3::new(0.0, 0.0, -1.0),
5198            2.0_f64.atan(),
5199        )
5200        .unwrap();
5201        // Beside the axis: each ruling meets the nappe once.
5202        for (x, y) in [(0.0, 1.3), (1.2, 0.5)] {
5203            let rod =
5204                CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
5205                    .unwrap();
5206            let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
5207                .unwrap()
5208                .unwrap();
5209            assert_eq!(curves.len(), 1, "one closed loop at ({x}, {y})");
5210            let (t0, t1) = curves[0].curve.domain();
5211            let (first, last) = (
5212                ParametricCurve::evaluate(&curves[0].curve, t0),
5213                ParametricCurve::evaluate(&curves[0].curve, t1),
5214            );
5215            assert!((first - last).length() < 1e-9, "open at ({x}, {y})");
5216            for k in 0..=64 {
5217                let p = ParametricCurve::evaluate(
5218                    &curves[0].curve,
5219                    (t1 - t0).mul_add(f64::from(k) / 64.0, t0),
5220                );
5221                let on_rod = (p.x() - x).hypot(p.y() - y) - 0.6;
5222                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5223                assert!(
5224                    on_rod.abs() < 1e-5 && on_cone.abs() < 1e-5,
5225                    "({x}, {y}): off by {on_rod}, {on_cone}"
5226                );
5227            }
5228        }
5229        // Around the axis, and beside it by less than the bend the rulings
5230        // resolve: two branches.
5231        for (x, y) in [(0.3, 0.2), (0.65, 0.0)] {
5232            let rod =
5233                CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
5234                    .unwrap();
5235            let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
5236                .unwrap()
5237                .unwrap();
5238            assert_eq!(curves.len(), 2, "two branches at ({x}, {y})");
5239        }
5240    }
5241
5242    /// A coaxial pair has no radical line; the algebraic path must defer rather
5243    /// than divide by a zero axis separation.
5244    #[test]
5245    fn coaxial_cone_cylinder_defers_to_other_paths() {
5246        let cone = ConicalSurface::new(
5247            Point3::new(0.0, 0.0, 0.0),
5248            Vec3::new(0.0, 0.0, 1.0),
5249            std::f64::consts::FRAC_PI_4,
5250        )
5251        .unwrap();
5252        let cyl =
5253            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
5254                .unwrap();
5255        assert!(
5256            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
5257                .unwrap()
5258                .is_none()
5259        );
5260    }
5261
5262    #[test]
5263    fn oblique_cone_cylinder_defers_to_other_paths() {
5264        let cone = ConicalSurface::new(
5265            Point3::new(0.0, 0.0, 0.0),
5266            Vec3::new(0.0, 0.0, 1.0),
5267            std::f64::consts::FRAC_PI_4,
5268        )
5269        .unwrap();
5270        let cyl =
5271            CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
5272                .unwrap();
5273        assert!(
5274            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
5275                .unwrap()
5276                .is_none()
5277        );
5278    }
5279
5280    #[test]
5281    fn plane_torus_lobe_closes_and_stays_on_surface() {
5282        use crate::traits::ParametricCurve;
5283        let (major, minor) = (10.0, 3.0);
5284        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5285
5286        // The census cutting planes (y=-4, x=6) each cut the +x and -x tube lobes
5287        // in a CLOSED oval. The greedy marcher stops one grid step short of
5288        // closing; the wrap-close must make every fitted lobe close exactly.
5289        for (n, d) in [
5290            (Vec3::new(0.0, -1.0, 0.0), 4.0),  // y = -4
5291            (Vec3::new(-1.0, 0.0, 0.0), -6.0), // x = 6
5292            (Vec3::new(0.0, 0.0, 1.0), 0.0),   // z = 0 -> two concentric circles
5293        ] {
5294            let curves = intersect_plane_torus(&torus, n, d).unwrap();
5295            assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
5296            for c in &curves {
5297                let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
5298                let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
5299                assert!(
5300                    (p0 - p1).length() < 1e-7,
5301                    "lobe not closed: gap={} (n={n:?} d={d})",
5302                    (p0 - p1).length()
5303                );
5304                // Every fitted sample stays on the torus (shape-preserving).
5305                for k in 0..=64 {
5306                    let t = f64::from(k) / 64.0;
5307                    let p = ParametricCurve::evaluate(&c.curve, t);
5308                    assert!(
5309                        torus_implicit(p, major, minor).abs() < 1e-2,
5310                        "off-surface point {p:?} implicit={}",
5311                        torus_implicit(p, major, minor)
5312                    );
5313                }
5314            }
5315        }
5316    }
5317
5318    /// A plane tangent to the inner equator (x = major - minor = 7) cuts a
5319    /// figure-eight that crosses itself on that equator. It comes out as its
5320    /// two lobes, each a loop that starts and ends on the node, one either
5321    /// side of the plane y = 0, never as one loop sealed across the node.
5322    #[test]
5323    fn plane_torus_inner_tangent_figure_eight_is_two_loops_through_its_node() {
5324        let (major, minor) = (10.0, 3.0);
5325        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5326        let curves =
5327            intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
5328        assert_eq!(curves.len(), 2, "one loop per lobe");
5329        let node = Point3::new(major - minor, 0.0, 0.0);
5330        let mut sides = Vec::new();
5331        for c in &curves {
5332            let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5333            assert!((first - node).length() < 1e-6, "starts at {first:?}");
5334            assert_eq!(first, last, "closes on the node");
5335            for p in c.points.iter().map(|p| p.point) {
5336                assert!((p.x() - node.x()).abs() < 1e-9, "off the plane at {p:?}");
5337                assert!(
5338                    torus_implicit(p, major, minor).abs() < 1e-6,
5339                    "off the torus at {p:?}"
5340                );
5341            }
5342            let y: f64 = c.points.iter().map(|p| p.point.y()).sum();
5343            sides.push(y > 0.0);
5344            assert!(
5345                c.points.iter().all(|p| p.point.y() * y >= -1e-9),
5346                "a lobe crosses y = 0"
5347            );
5348        }
5349        assert_ne!(sides[0], sides[1], "the lobes lie either side of y = 0");
5350    }
5351
5352    /// A wall just off the inner tangent has no node. Just past it the
5353    /// section has a gap 0.028 wide in tube angle about the inner equator,
5354    /// between two samples inside it, and is one loop turning either side of
5355    /// the gap; just short of it the section winds the tube twice. Every
5356    /// point lies on the wall.
5357    #[test]
5358    fn a_wall_just_off_the_inner_tangent_cuts_no_node() {
5359        let (major, minor) = (3.0, 1.0);
5360        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5361        for (x, loops) in [(2.0001, 1), (1.9999, 2)] {
5362            let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), x).unwrap();
5363            assert_eq!(curves.len(), loops, "x = {x}");
5364            for c in &curves {
5365                let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5366                assert_eq!(first, last, "x = {x}: the loop closes");
5367                for p in c.points.iter().map(|p| p.point) {
5368                    assert!((p.x() - x).abs() < 1e-9, "x = {x}: off the wall at {p:?}");
5369                    assert!(
5370                        torus_implicit(p, major, minor).abs() < 1e-6,
5371                        "x = {x}: off the torus at {p:?}"
5372                    );
5373                }
5374            }
5375        }
5376        // The loop past the tangent turns either side of the gap, 0.028 apart.
5377        let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), 2.0001).unwrap();
5378        let low = curves[0]
5379            .points
5380            .iter()
5381            .map(|p| p.point)
5382            .filter(|p| p.y().abs() < 1e-6)
5383            .map(Point3::z)
5384            .collect::<Vec<_>>();
5385        let gap = (2.0001_f64 - 2.0)
5386            .mul_add(2.0, -(2.0001_f64 - 2.0).powi(2))
5387            .sqrt();
5388        assert!(
5389            low.iter().any(|z| (z - gap).abs() < 1e-6)
5390                && low.iter().any(|z| (z + gap).abs() < 1e-6),
5391            "turns at {low:?}, not at z = ±{gap}"
5392        );
5393    }
5394
5395    /// A plane tangent to the tube's inner side off its equator, at a saddle,
5396    /// cuts a figure-eight that crosses itself where it touches. Its lobes
5397    /// come out as two loops, each starting and ending on that node.
5398    #[test]
5399    fn a_tilted_plane_tangent_inside_the_tube_cuts_two_loops_through_its_node() {
5400        let (major, minor) = (3.0, 1.0);
5401        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5402        for v0 in [1.7_f64, 2.0, 2.5, 4.0] {
5403            let normal = Vec3::new(v0.cos(), 0.0, v0.sin());
5404            let node = torus.evaluate(0.0, v0);
5405            let d = normal.dot(Vec3::new(node.x(), node.y(), node.z()));
5406            let curves = intersect_plane_torus(&torus, normal, d).unwrap();
5407            assert_eq!(curves.len(), 2, "v0 {v0}: one loop per lobe");
5408            for c in &curves {
5409                let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5410                assert!(
5411                    (first - node).length() < 1e-6,
5412                    "v0 {v0}: starts at {first:?}, not {node:?}"
5413                );
5414                assert_eq!(first, last, "v0 {v0}: closes on the node");
5415                for p in c.points.iter().map(|p| p.point) {
5416                    let off = normal.dot(Vec3::new(p.x(), p.y(), p.z())) - d;
5417                    assert!(off.abs() < 1e-9, "v0 {v0}: off the plane at {p:?}");
5418                    assert!(
5419                        torus_implicit(p, major, minor).abs() < 1e-6,
5420                        "v0 {v0}: off the torus at {p:?}"
5421                    );
5422                }
5423            }
5424        }
5425    }
5426
5427    /// A wall parallel to the axis cuts one loop from the ring past the
5428    /// inner equator (its two turns where the branches meet), and two loops
5429    /// winding the tube inside it; each closes, at any scale, however near
5430    /// the wall runs to an equator.
5431    #[test]
5432    fn plane_torus_wall_sections_close_into_their_loops() {
5433        for (major, minor) in [(4.0, 1.5), (100.0, 30.0), (0.05, 0.01)] {
5434            let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5435            for k in 1..200 {
5436                let (d, want) = match k.cmp(&100) {
5437                    // Within the inner equator: two loops winding the tube.
5438                    std::cmp::Ordering::Less => ((major - minor) * f64::from(k) / 100.0, 2),
5439                    // Past it, short of the outer equator: one loop.
5440                    std::cmp::Ordering::Greater => (
5441                        2.0f64.mul_add(minor * f64::from(k - 100) / 100.0, major - minor),
5442                        1,
5443                    ),
5444                    std::cmp::Ordering::Equal => continue,
5445                };
5446                let loops = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), d, 128);
5447                let closed = loops
5448                    .iter()
5449                    .filter(|l| (l[0].point - l[l.len() - 1].point).length() < 1e-12)
5450                    .count();
5451                assert_eq!(
5452                    (loops.len(), closed),
5453                    (want, want),
5454                    "R {major} r {minor}, wall at {d}"
5455                );
5456            }
5457        }
5458    }
5459
5460    /// A plane through the centre tilted a little from the equator cuts two
5461    /// loops that each run all the way round the axis on a short run of `v`;
5462    /// their fitted curves stay on the torus.
5463    #[test]
5464    fn plane_torus_sections_round_the_axis_stay_on_the_torus() {
5465        let (major, minor) = (4.0, 1.5);
5466        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5467        for tilt in [0.03_f64, 0.08, 0.2] {
5468            let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
5469            let curves = intersect_plane_torus(&torus, normal, 0.0).unwrap();
5470            assert_eq!(curves.len(), 2, "tilt {tilt}");
5471            for c in &curves {
5472                let (t0, t1) = c.curve.domain();
5473                let off = (0..=400)
5474                    .map(|k| {
5475                        let p = c
5476                            .curve
5477                            .evaluate((t1 - t0).mul_add(f64::from(k) / 400.0, t0));
5478                        (p.x().hypot(p.y()) - major).hypot(p.z()) - minor
5479                    })
5480                    .fold(0.0_f64, |m, e| m.max(e.abs()));
5481                assert!(
5482                    off < 1e-6,
5483                    "tilt {tilt}: fitted section {off} off the torus"
5484                );
5485            }
5486        }
5487    }
5488
5489    #[test]
5490    fn line_torus_box_edge_crossing_is_exact() {
5491        // The census box edge x=6, y=-4 (z varying) crosses the torus (R=10,r=3)
5492        // at z = ±sqrt(r² − (rho−R)²), rho = hypot(6,4) ≈ 7.2111 → z ≈ ±1.1055.
5493        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
5494        let ts = intersect_line_torus(
5495            &torus,
5496            Point3::new(6.0, -4.0, -5.0),
5497            Vec3::new(0.0, 0.0, 1.0),
5498        );
5499        // Vertical line through (6,-4) meets the tube twice.
5500        assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
5501        let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
5502        let rho = 6.0_f64.hypot(4.0);
5503        let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
5504        assert!(
5505            (zs[0] - (-z_exp)).abs() < 1e-9,
5506            "z0={} exp={}",
5507            zs[0],
5508            -z_exp
5509        );
5510        assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
5511        // Each crossing lies on the torus.
5512        for &t in &ts {
5513            let p = Point3::new(6.0, -4.0, -5.0 + t);
5514            let rho = p.x().hypot(p.y());
5515            let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
5516            assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
5517        }
5518    }
5519
5520    /// A ray out of a pocket corner's spindle torus (major 0.1, minor 2.45)
5521    /// meets the tube swung across the axis at t 0.124 and its own tube at
5522    /// 0.398: each root lies on one of the two tubes, not polished off the
5523    /// first onto a point beside the second.
5524    #[test]
5525    fn line_spindle_torus_roots_lie_on_their_tubes() {
5526        let torus = ToroidalSurface::new(Point3::new(41.0, 17.0, 4.7), 0.1, 2.45).unwrap();
5527        let origin = Point3::new(42.36, 18.31, 3.4);
5528        let dir = Vec3::new(
5529            0.573_576_436_351_046,
5530            0.740_535_693_464_567_5,
5531            0.350_889_803_483_932_2,
5532        );
5533        let ts = intersect_line_torus(&torus, origin, dir);
5534        let tube = |t: f64, across: f64| {
5535            let q = origin + dir * t;
5536            ((q.x() - 41.0).hypot(q.y() - 17.0) - across * 0.1).hypot(q.z() - 4.7) - 2.45
5537        };
5538        for &t in &ts {
5539            assert!(
5540                tube(t, 1.0).abs().min(tube(t, -1.0).abs()) < 1e-9,
5541                "root {t} off both tubes in {ts:?}"
5542            );
5543        }
5544        for want in [0.124, 0.398] {
5545            assert!(
5546                ts.iter().any(|&t| (t - want).abs() < 1e-3),
5547                "no root near {want} in {ts:?}"
5548            );
5549        }
5550    }
5551
5552    #[test]
5553    fn line_torus_miss_and_tangent() {
5554        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
5555        // A vertical line at rho beyond the outer rim (x=20) misses entirely.
5556        let miss = intersect_line_torus(
5557            &torus,
5558            Point3::new(20.0, 0.0, 0.0),
5559            Vec3::new(0.0, 0.0, 1.0),
5560        );
5561        assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
5562        // The z-axis (rho=0) passes through the hole — no intersection.
5563        let axis =
5564            intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
5565        assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
5566    }
5567
5568    #[test]
5569    fn dispatch_via_analytic_surface() {
5570        let cyl =
5571            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5572                .unwrap();
5573        let curves = intersect_plane_analytic(
5574            AnalyticSurface::Cylinder(&cyl),
5575            Vec3::new(0.0, 0.0, 1.0),
5576            0.0,
5577        )
5578        .unwrap();
5579        assert!(!curves.is_empty());
5580    }
5581
5582    #[test]
5583    fn perpendicular_cylinders_intersect() {
5584        let cyl_z =
5585            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5586                .unwrap();
5587        let cyl_x =
5588            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
5589                .unwrap();
5590
5591        let curves = intersect_analytic_analytic(
5592            AnalyticSurface::Cylinder(&cyl_z),
5593            AnalyticSurface::Cylinder(&cyl_x),
5594            16,
5595        )
5596        .unwrap();
5597
5598        assert!(
5599            !curves.is_empty(),
5600            "perpendicular cylinders should intersect"
5601        );
5602
5603        for c in &curves {
5604            assert!(
5605                c.points.len() >= 2,
5606                "intersection curve should have >= 2 points, got {}",
5607                c.points.len()
5608            );
5609        }
5610    }
5611
5612    /// Neither cylinder's rulings all meet the other: the curve is one loop
5613    /// joined at its two branch points.
5614    #[test]
5615    fn partially_overlapping_cylinders_meet_in_one_closed_loop() {
5616        let cyl_z =
5617            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5618                .unwrap();
5619        let cyl_x =
5620            CylindricalSurface::new(Point3::new(0.0, 1.2, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
5621                .unwrap();
5622        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
5623            .unwrap()
5624            .unwrap();
5625        assert_eq!(curves.len(), 1);
5626        let curve = &curves[0].curve;
5627        let (t0, t1) = curve.domain();
5628        assert!((curve.evaluate(t0) - curve.evaluate(t1)).length() < 1e-9);
5629        let off = |p: Point3| {
5630            let on_z = (p.x().hypot(p.y()) - 1.0).abs();
5631            let on_x = ((p.y() - 1.2).hypot(p.z()) - 1.0).abs();
5632            on_z.max(on_x)
5633        };
5634        let worst = (0..=400)
5635            .map(|k| off(curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0)))
5636            .fold(0.0, f64::max);
5637        assert!(worst < 2e-4, "curve leaves the cylinders by {worst}");
5638    }
5639
5640    /// Near tangency the thick cylinder's window of rulings (0.02 either side
5641    /// of a quarter turn) falls between its samples; the thin one's sweep
5642    /// finds the loop.
5643    #[test]
5644    fn near_tangent_cylinders_find_their_loop_on_the_thinner_sweep() {
5645        let cyl_z =
5646            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5647                .unwrap();
5648        let cyl_x =
5649            CylindricalSurface::new(Point3::new(0.0, 1.1998, 0.0), Vec3::new(1.0, 0.0, 0.0), 0.2)
5650                .unwrap();
5651        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
5652            .unwrap()
5653            .expect("the thin cylinder's sweep finds the loop");
5654        assert_eq!(curves.len(), 1);
5655    }
5656
5657    /// Cylinders of radius 1.5 whose axes cross at 60° meet in two ellipses
5658    /// crossing at the ends of the axes' common normal: two exact loops,
5659    /// one from each end, each the halves of both ellipses on one side of
5660    /// the crossing along the first axis, on both cylinders to rounding.
5661    #[test]
5662    fn equal_cylinders_with_crossing_axes_meet_in_two_cornered_loops() {
5663        let crossing = Point3::new(1.0, 2.0, 3.0);
5664        let (s, c) = 60.0_f64.to_radians().sin_cos();
5665        let (d1, d2) = (Vec3::new(0.0, 0.0, 1.0), Vec3::new(s, 0.0, c));
5666        let c1 = CylindricalSurface::new(crossing - d1 * 2.0, d1, 1.5).unwrap();
5667        let c2 = CylindricalSurface::new(crossing + d2 * 0.7, d2, 1.5).unwrap();
5668        let curves = algebraic_cylinder_cylinder(&c1, &c2).unwrap().unwrap();
5669        assert_eq!(curves.len(), 2);
5670        let off = |p: Point3, cyl: &CylindricalSurface| {
5671            let q = p - cyl.origin();
5672            ((q - cyl.axis() * q.dot(cyl.axis())).length() - 1.5).abs()
5673        };
5674        let ends = [
5675            crossing + Vec3::new(0.0, 1.5, 0.0),
5676            crossing - Vec3::new(0.0, 1.5, 0.0),
5677        ];
5678        let mut vertices: Vec<Point3> = Vec::new();
5679        for (ic, (end, side)) in curves.iter().zip([(ends[0], 1.0), (ends[1], -1.0)]) {
5680            let (t0, t1) = ic.curve.domain();
5681            for k in 0..=400 {
5682                let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
5683                assert!(off(p, &c1).max(off(p, &c2)) < 1e-13);
5684                assert!(side * (p - crossing).dot(d1) > -1e-13);
5685            }
5686            assert!((ic.curve.evaluate(t0) - end).length() < 1e-14);
5687            assert!((ic.curve.evaluate(t1) - end).length() < 1e-14);
5688            let other = ends[usize::from(side > 0.0)];
5689            assert!((ic.curve.evaluate(0.5) - other).length() < 1e-14);
5690            for t in [0.25, 0.75] {
5691                let vertex = ic.curve.evaluate(t);
5692                assert!(vertices.iter().all(|&v| (v - vertex).length() > 1.0));
5693                vertices.push(vertex);
5694            }
5695        }
5696    }
5697
5698    /// Axes that miss each other by 1e-9, or radii that differ by as much,
5699    /// part the curves where the ellipses would cross; neither is taken for
5700    /// a pair of ellipses, nor a miss of 1e-6 read between origins 1e8
5701    /// apart along an axis.
5702    #[test]
5703    fn nearly_crossing_equal_cylinders_are_not_ellipses() {
5704        let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5705            .unwrap();
5706        let x = |(x0, y): (f64, f64), r: f64| {
5707            CylindricalSurface::new(Point3::new(x0, y, 0.0), Vec3::new(1.0, 0.0, 0.0), r).unwrap()
5708        };
5709        let taken = |c: &CylindricalSurface| crossing_equal_cylinders(&z, c).unwrap().is_some();
5710        assert!(taken(&x((-2.0, 0.0), 1.0)));
5711        assert!(!taken(&x((-2.0, 1e-9), 1.0)));
5712        assert!(!taken(&x((-2.0, 0.0), 1.0 + 1e-9)));
5713        assert!(!taken(&x((-1e8, 1e-6), 1.0)));
5714    }
5715
5716    /// Axes 1e-8 and 1.5e-5 apart in angle cross in ellipses whose far
5717    /// vertices rounding alone would move past the tolerance; they are
5718    /// left to the rulings.
5719    #[test]
5720    fn nearly_parallel_equal_cylinders_are_not_ellipses() {
5721        let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 10.0)
5722            .unwrap();
5723        for slope in [1e-8, 1.5e-5] {
5724            let tilted = CylindricalSurface::new(
5725                Point3::new(0.0, 0.0, 0.0),
5726                Vec3::new(slope, 0.0, 1.0),
5727                10.0,
5728            )
5729            .unwrap();
5730            assert!(crossing_equal_cylinders(&z, &tilted).unwrap().is_none());
5731        }
5732    }
5733
5734    #[test]
5735    fn sphere_cylinder_intersect() {
5736        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
5737        let cyl =
5738            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5739                .unwrap();
5740
5741        let curves = intersect_analytic_analytic(
5742            AnalyticSurface::Sphere(&sphere),
5743            AnalyticSurface::Cylinder(&cyl),
5744            16,
5745        )
5746        .unwrap();
5747
5748        // A sphere of radius 2 and a cylinder of radius 1, both centered
5749        // at the origin, should intersect (the cylinder passes through
5750        // the sphere).
5751        assert!(!curves.is_empty(), "sphere and cylinder should intersect");
5752    }
5753
5754    #[test]
5755    fn exact_sphere_cylinder_coaxial_two_circles() {
5756        // Sphere r=6 at origin, coaxial cylinder r=3 along z: two latitude
5757        // circles at z = ±sqrt(36-9) = ±sqrt(27), each of radius 3.
5758        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
5759        let cyl =
5760            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
5761                .unwrap();
5762        let circles = exact_sphere_cylinder(&sphere, &cyl)
5763            .unwrap()
5764            .expect("coaxial case returns Some");
5765        assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
5766        let mut zs: Vec<f64> = circles
5767            .iter()
5768            .filter_map(|c| match c {
5769                ExactIntersectionCurve::Circle(circle) => {
5770                    assert!(
5771                        (circle.radius() - 3.0).abs() < 1e-9,
5772                        "rim radius == cyl radius"
5773                    );
5774                    Some(circle.center().z())
5775                }
5776                _ => None,
5777            })
5778            .collect();
5779        assert_eq!(zs.len(), 2, "both sections must be exact circles");
5780        zs.sort_by(f64::total_cmp);
5781        let z = 27.0_f64.sqrt();
5782        assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
5783    }
5784
5785    #[test]
5786    fn exact_sphere_cylinder_non_coaxial_defers() {
5787        // Cylinder axis offset from the sphere center → quartic curve, deferred.
5788        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
5789        let cyl =
5790            CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
5791                .unwrap();
5792        assert!(
5793            exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
5794            "non-coaxial sphere/cylinder defers to the marcher"
5795        );
5796    }
5797
5798    #[test]
5799    fn a_ball_on_a_cones_axis_meets_it_in_circles() {
5800        // Apex 3 up, opening downward, the radius half the depth below it.
5801        let cone = ConicalSurface::new(
5802            Point3::new(0.0, 0.0, 3.0),
5803            Vec3::new(0.0, 0.0, -1.0),
5804            2.0_f64.atan(),
5805        )
5806        .unwrap();
5807        for (height, radius, count) in [
5808            (0.0, 2.0, 2), // through the cone's middle
5809            (2.5, 1.3, 1), // swallowing the apex
5810            (2.5, 0.5, 1), // through the apex: the apex root is no circle
5811            (0.0, 1.0, 0), // inside, clear of the wall
5812            (5.0, 1.0, 0), // on the other nappe's side
5813        ] {
5814            let centre = Point3::new(0.0, 0.0, height);
5815            let ball = SphericalSurface::new(centre, radius).unwrap();
5816            let curves = exact_cone_sphere(&cone, &ball).unwrap().unwrap();
5817            let circles = circles_of(&curves);
5818            assert_eq!(circles.len(), count, "ball at {height}, radius {radius}");
5819            for circle in circles {
5820                for k in 0..16 {
5821                    let p = circle.evaluate(TAU * f64::from(k) / 16.0);
5822                    let on_ball = (p - centre).length() - radius;
5823                    let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5824                    assert!(
5825                        on_ball.abs() < 1e-9 && on_cone.abs() < 1e-9,
5826                        "ball at {height}: off by {on_ball}, {on_cone}"
5827                    );
5828                }
5829            }
5830        }
5831        let aside = SphericalSurface::new(Point3::new(0.5, 0.0, 0.0), 2.0).unwrap();
5832        assert!(exact_cone_sphere(&cone, &aside).unwrap().is_none());
5833        // A ball touching a wide cone a million units out, where the
5834        // discriminant cancels to a few ulps below zero.
5835        let wide =
5836            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.3).unwrap();
5837        let far = SphericalSurface::new(Point3::new(0.0, 0.0, 1e6), 1e6 * 0.3_f64.cos()).unwrap();
5838        let curves = exact_cone_sphere(&wide, &far).unwrap().unwrap();
5839        let circles = circles_of(&curves);
5840        assert_eq!(circles.len(), 1, "the touch");
5841        let touch = 1e6 * 0.3_f64.sin() * 0.3_f64.cos();
5842        assert!(
5843            (circles[0].radius() - touch).abs() < 1e-3,
5844            "{}",
5845            circles[0].radius()
5846        );
5847    }
5848
5849    /// The circles among exact section curves.
5850    fn circles_of(curves: &[ExactIntersectionCurve]) -> Vec<&Circle3D> {
5851        curves
5852            .iter()
5853            .filter_map(|c| match c {
5854                ExactIntersectionCurve::Circle(circle) => Some(circle),
5855                _ => None,
5856            })
5857            .collect()
5858    }
5859
5860    /// Worst distance of a circle's points from a torus and from a second
5861    /// surface given by its own distance function.
5862    fn worst_off(
5863        circles: &[&Circle3D],
5864        torus: &ToroidalSurface,
5865        other: impl Fn(Point3) -> f64,
5866    ) -> f64 {
5867        let mut worst = 0.0_f64;
5868        for circle in circles {
5869            for k in 0..16 {
5870                let p = circle.evaluate(TAU * f64::from(k) / 16.0);
5871                let q = p - torus.center();
5872                let along = q.dot(torus.z_axis());
5873                let rho = (q - torus.z_axis() * along).length();
5874                let off = ((rho - torus.major_radius()).hypot(along) - torus.minor_radius()).abs();
5875                worst = worst.max(off).max(other(p).abs());
5876            }
5877        }
5878        worst
5879    }
5880
5881    #[test]
5882    fn exact_sphere_torus_meets_a_ball_on_the_axis_in_circles() {
5883        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
5884        for height in [0.0, 1.0] {
5885            let centre = Point3::new(0.0, 0.0, height);
5886            let sphere = SphericalSurface::new(centre, 3.0).unwrap();
5887            let curves = exact_sphere_torus(&sphere, &torus).unwrap().unwrap();
5888            let circles = circles_of(&curves);
5889            assert_eq!((curves.len(), circles.len()), (2, 2), "height {height}");
5890            let worst = worst_off(&circles, &torus, |p| (p - centre).length() - 3.0);
5891            assert!(worst < 1e-9, "height {height}: {worst}");
5892        }
5893    }
5894
5895    #[test]
5896    fn exact_sphere_torus_misses_touches_and_defers() {
5897        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
5898        let ball = |x: f64, r: f64| SphericalSurface::new(Point3::new(x, 0.0, 0.0), r).unwrap();
5899        assert!(
5900            exact_sphere_torus(&ball(0.0, 1.0), &torus)
5901                .unwrap()
5902                .unwrap()
5903                .is_empty(),
5904            "a small ball in the hole misses"
5905        );
5906        let touching = exact_sphere_torus(&ball(0.0, 2.5), &torus)
5907            .unwrap()
5908            .unwrap();
5909        let circles = circles_of(&touching);
5910        assert_eq!(
5911            circles.len(),
5912            1,
5913            "a ball in the hole touches the inner equator"
5914        );
5915        assert!((circles[0].radius() - 2.5).abs() < 1e-12);
5916        assert!(circles[0].center().z().abs() < 1e-12);
5917        assert!(
5918            exact_sphere_torus(&ball(1.0, 3.0), &torus)
5919                .unwrap()
5920                .is_none(),
5921            "a ball off the axis defers"
5922        );
5923        let spindle = ToroidalSurface::with_axis_and_ref_dir(
5924            Point3::new(0.0, 0.0, 0.0),
5925            1.0,
5926            2.0,
5927            Vec3::new(0.0, 0.0, 1.0),
5928            Vec3::new(1.0, 0.0, 0.0),
5929        )
5930        .unwrap();
5931        assert!(
5932            exact_sphere_torus(&ball(0.0, 2.5), &spindle)
5933                .unwrap()
5934                .is_none()
5935        );
5936    }
5937
5938    #[test]
5939    fn exact_cylinder_torus_meets_a_coaxial_rod_in_circles() {
5940        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
5941        let z = Vec3::new(0.0, 0.0, 1.0);
5942        let rod = |r: f64| CylindricalSurface::new(Point3::new(0.0, 0.0, -5.0), z, r).unwrap();
5943        let curves = exact_cylinder_torus(&rod(4.2), &torus).unwrap().unwrap();
5944        let circles = circles_of(&curves);
5945        assert_eq!((curves.len(), circles.len()), (2, 2));
5946        let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - 4.2);
5947        assert!(worst < 1e-9, "{worst}");
5948        assert!(
5949            exact_cylinder_torus(&rod(2.0), &torus)
5950                .unwrap()
5951                .unwrap()
5952                .is_empty(),
5953            "a rod clear in the hole misses"
5954        );
5955        for (wall, label) in [(5.5, "outer"), (2.5, "inner")] {
5956            let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
5957            let circles = circles_of(&curves);
5958            assert_eq!(circles.len(), 1, "a wall touching the {label} equator");
5959            assert!(circles[0].center().z().abs() < 1e-12, "{label}");
5960            let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - wall);
5961            assert!(worst < 1e-9, "{label}: {worst}");
5962        }
5963        assert!(
5964            exact_cylinder_torus(&rod(5.5 + 1e-6), &torus)
5965                .unwrap()
5966                .unwrap()
5967                .is_empty(),
5968            "a wall clear of the tube by more than the tolerance misses it"
5969        );
5970        assert_eq!(
5971            exact_cylinder_torus(&rod(5.5 - 1e-6), &torus)
5972                .unwrap()
5973                .unwrap()
5974                .len(),
5975            2,
5976            "a wall into the tube by more than the tolerance crosses it twice"
5977        );
5978        // Within the linear tolerance of the tube the wall reads as touching
5979        // it: the two crossings lie under 1e-3 apart on a band the wall
5980        // never leaves by more than that tolerance.
5981        for wall in [5.5 - 5e-8, 5.5 + 5e-8] {
5982            let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
5983            assert_eq!(circles_of(&curves).len(), 1, "a wall at {wall}");
5984        }
5985        let tilted =
5986            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 1.0), 4.2)
5987                .unwrap();
5988        let offset = CylindricalSurface::new(Point3::new(0.5, 0.0, 0.0), z, 4.2).unwrap();
5989        assert!(exact_cylinder_torus(&tilted, &torus).unwrap().is_none());
5990        assert!(exact_cylinder_torus(&offset, &torus).unwrap().is_none());
5991        let spindle = ToroidalSurface::with_axis_and_ref_dir(
5992            Point3::new(0.0, 0.0, 0.0),
5993            1.0,
5994            2.0,
5995            z,
5996            Vec3::new(1.0, 0.0, 0.0),
5997        )
5998        .unwrap();
5999        assert!(
6000            exact_cylinder_torus(&rod(0.5), &spindle).unwrap().is_none(),
6001            "a spindle torus's inner lemon also meets the rod"
6002        );
6003        // The rounded air wall of a fillet whose radius nearly fills its
6004        // corner: the spindle's outer equator rests on the wall.
6005        let spindle = ToroidalSurface::with_axis_and_ref_dir(
6006            Point3::new(0.0, 0.0, 4.7),
6007            0.1,
6008            2.45,
6009            z,
6010            Vec3::new(1.0, 0.0, 0.0),
6011        )
6012        .unwrap();
6013        let curves = exact_cylinder_torus(&rod(2.55), &spindle).unwrap().unwrap();
6014        let circles = circles_of(&curves);
6015        assert_eq!(circles.len(), 1);
6016        assert!((circles[0].center().z() - 4.7).abs() < 1e-12);
6017        let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.55);
6018        assert!(worst < 1e-9, "{worst}");
6019        let curves = exact_cylinder_torus(&rod(2.4), &spindle).unwrap().unwrap();
6020        let circles = circles_of(&curves);
6021        assert_eq!(circles.len(), 2, "a wall into the spindle's outer tube");
6022        let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.4);
6023        assert!(worst < 1e-9, "{worst}");
6024    }
6025
6026    /// Loops of an off-axis sphere-cylinder pair: `(count, worst distance
6027    /// from either surface)`.
6028    fn off_axis_loops(cylinder_origin: Point3, cylinder_radius: f64) -> (usize, f64) {
6029        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
6030        let cyl =
6031            CylindricalSurface::new(cylinder_origin, Vec3::new(0.0, 0.0, 1.0), cylinder_radius)
6032                .unwrap();
6033        let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
6034            .unwrap()
6035            .unwrap();
6036        let mut worst: f64 = 0.0;
6037        for c in &curves {
6038            for ip in &c.points {
6039                let on_sphere = sphere.evaluate(ip.param1.0, ip.param1.1);
6040                let on_cylinder = cyl.evaluate(ip.param2.0, ip.param2.1);
6041                worst = worst
6042                    .max((on_sphere - ip.point).length())
6043                    .max((on_cylinder - ip.point).length());
6044            }
6045            let (t0, t1) = c.curve.domain();
6046            assert!((c.curve.evaluate(t0) - c.curve.evaluate(t1)).length() < 1e-9);
6047            for k in 0..=400 {
6048                let p = c.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
6049                let on_sphere = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 2.0).abs();
6050                let on_cylinder = ((p.x() - cylinder_origin.x())
6051                    .hypot(p.y() - cylinder_origin.y())
6052                    - cylinder_radius)
6053                    .abs();
6054                worst = worst.max(on_sphere).max(on_cylinder);
6055            }
6056        }
6057        (curves.len(), worst)
6058    }
6059
6060    /// A drill off the ball's axis passes through it: an entry and an exit
6061    /// loop.
6062    #[test]
6063    fn off_axis_drill_through_a_sphere_meets_it_in_two_loops() {
6064        let (count, worst) = off_axis_loops(Point3::new(0.5, 0.0, 0.0), 0.2);
6065        assert_eq!(count, 2);
6066        assert!(worst < 1e-5, "loops leave the surfaces by {worst}");
6067    }
6068
6069    /// A cylinder over the ball's side: one loop joined at its branch points.
6070    #[test]
6071    fn cylinder_over_a_spheres_side_meets_it_in_one_loop() {
6072        let (count, worst) = off_axis_loops(Point3::new(1.8, 0.0, 0.0), 0.5);
6073        assert_eq!(count, 1);
6074        assert!(worst < 5e-4, "loop leaves the surfaces by {worst}");
6075    }
6076
6077    #[test]
6078    fn disjoint_cylinders_no_intersection() {
6079        let cyl_a =
6080            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
6081                .unwrap();
6082        let cyl_b =
6083            CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
6084                .unwrap();
6085
6086        let curves = intersect_analytic_analytic(
6087            AnalyticSurface::Cylinder(&cyl_a),
6088            AnalyticSurface::Cylinder(&cyl_b),
6089            16,
6090        )
6091        .unwrap();
6092
6093        assert!(curves.is_empty(), "disjoint cylinders should not intersect");
6094    }
6095
6096    // ── Oblique plane × cone conic (ellipse / parabola / hyperbola) ──────
6097
6098    /// Collect 3D points from a returned exact curve, sampling analytic forms.
6099    fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
6100        use crate::traits::ParametricCurve;
6101        match curve {
6102            ExactIntersectionCurve::Circle(c) => (0..=64)
6103                .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
6104                .collect(),
6105            ExactIntersectionCurve::Ellipse(e) => (0..=64)
6106                .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
6107                .collect(),
6108            ExactIntersectionCurve::Points(pts) => pts.clone(),
6109        }
6110    }
6111
6112    /// Assert every returned point lies on the plane and the cone surface, on
6113    /// the real (`v >= 0`) nappe, and within a sane axial bound.
6114    fn assert_on_plane_and_cone(
6115        curves: &[ExactIntersectionCurve],
6116        cone: &ConicalSurface,
6117        n: Vec3,
6118        d: f64,
6119        z_bound: (f64, f64),
6120    ) {
6121        assert!(!curves.is_empty(), "expected at least one section curve");
6122        let mut total = 0;
6123        for curve in curves {
6124            for p in collect_points(curve) {
6125                total += 1;
6126                let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
6127                assert!(
6128                    plane_err < 1e-9,
6129                    "point off plane by {plane_err:.2e}: {p:?}"
6130                );
6131                let (u, v) = cone.project_point(p);
6132                let q = cone.evaluate(u, v);
6133                let cone_err =
6134                    ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
6135                        .sqrt();
6136                assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
6137                assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
6138                assert!(
6139                    p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
6140                    "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
6141                    p.z()
6142                );
6143            }
6144        }
6145        assert!(total >= 8, "too few section points ({total})");
6146    }
6147
6148    #[test]
6149    fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
6150        // 45°-half-angle cone (axis +z). A plane tilted only ~16.7° off horizontal
6151        // has plane-axis angle ≈ 73° > 45° (the cone's half-opening from axis) →
6152        // ellipse. Must come back as an exact Ellipse, fully on both surfaces.
6153        let cone = ConicalSurface::new(
6154            Point3::new(0.0, 0.0, 0.0),
6155            Vec3::new(0.0, 0.0, 1.0),
6156            std::f64::consts::FRAC_PI_4,
6157        )
6158        .unwrap();
6159        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
6160        // Plane through (0,0,5): d = n·(0,0,5).
6161        let d = n.z() * 5.0;
6162        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6163        assert!(
6164            curves
6165                .iter()
6166                .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
6167            "oblique steep plane × cone must yield an exact Ellipse"
6168        );
6169        // The ellipse straddles z=5; with the 0.3 tilt the z-extent stays modest.
6170        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
6171    }
6172
6173    #[test]
6174    fn oblique_plane_cone_wrong_nappe_is_empty() {
6175        // Same ellipse-regime plane as above, but offset to the FAR side of the
6176        // apex (z=-5). The +z cone's real (v≥0) nappe is not met — only the
6177        // phantom v<0 nappe — so the result must be EMPTY, not a phantom ellipse.
6178        let cone = ConicalSurface::new(
6179            Point3::new(0.0, 0.0, 0.0),
6180            Vec3::new(0.0, 0.0, 1.0),
6181            std::f64::consts::FRAC_PI_4,
6182        )
6183        .unwrap();
6184        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
6185        let d = n.z() * -5.0;
6186        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6187        assert!(
6188            curves.is_empty(),
6189            "plane on the phantom-nappe side must yield no real curve, got {}",
6190            curves.len()
6191        );
6192    }
6193
6194    #[test]
6195    fn oblique_plane_cone_parabola_on_both_single_branch() {
6196        // Plane normal at exactly 45° to the axis (= the cone half-opening) → the
6197        // plane is parallel to a generator → parabola. One unbounded branch.
6198        let cone = ConicalSurface::new(
6199            Point3::new(0.0, 0.0, 0.0),
6200            Vec3::new(0.0, 0.0, 1.0),
6201            std::f64::consts::FRAC_PI_4,
6202        )
6203        .unwrap();
6204        let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
6205        let d = n.x() * 3.0 + n.z() * 3.0; // through (3,0,3)
6206        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6207        assert_eq!(
6208            curves.len(),
6209            1,
6210            "a parabola is a single branch, got {}",
6211            curves.len()
6212        );
6213        // Bounded by r_max = 32·|e|; |e| here is O(few), so allow a wide z window.
6214        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
6215    }
6216
6217    #[test]
6218    fn oblique_plane_cone_hyperbola_real_nappe_only() {
6219        // Faithful scooplabel lip-foot geometry: a 45° cone with axis −z and
6220        // apex at (−59,−59,15.85) (a bin corner), cut by the upper ramp tread
6221        // plane n=(0,0.99518,0.09802), d=−58.36056. The plane is nearly parallel
6222        // to the axis (cos≈0.098) → plane-axis angle ≈ 5.6° < 45° → hyperbola.
6223        // The downward real nappe is hit by exactly one branch; the phantom
6224        // upward nappe (and the asymptote runaway) must NOT appear, and the arc
6225        // must stay near the apex (the plane is ~1.2 mm from it).
6226        let cone = ConicalSurface::new(
6227            Point3::new(-59.0, -59.0, 15.85),
6228            Vec3::new(0.0, 0.0, -1.0),
6229            std::f64::consts::FRAC_PI_4,
6230        )
6231        .unwrap();
6232        let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
6233        let d = -58.360_56;
6234        let cos_theta = n.dot(cone.axis()).abs();
6235        assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
6236        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6237        // Real downward nappe only: never above the apex (z=15.85). The vertex is
6238        // ~1.2 mm from the apex, so the bounded arc stays within a few mm of it.
6239        assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
6240        // Every returned curve is sampled Points (no false Circle/Ellipse).
6241        for c in &curves {
6242            assert!(
6243                matches!(c, ExactIntersectionCurve::Points(_)),
6244                "hyperbola must be sampled Points, not a closed conic"
6245            );
6246        }
6247    }
6248
6249    /// Two spheres meet in one circle on both of them; spheres apart, one
6250    /// inside the other, or concentric of different radii meet in nothing,
6251    /// and one sphere twice has no curve.
6252    #[test]
6253    fn sphere_sphere_meets_in_a_circle_on_both() {
6254        let ball = |x: f64, y: f64, z: f64, r: f64| {
6255            SphericalSurface::new(Point3::new(x, y, z), r).unwrap()
6256        };
6257        let (a, b) = (ball(0.0, 0.0, 0.0, 2.0), ball(1.6, 0.3, 0.2, 1.5));
6258        let curves = exact_sphere_sphere(&a, &b).unwrap().unwrap();
6259        assert_eq!(curves.len(), 1);
6260        let circle = match &curves[0] {
6261            ExactIntersectionCurve::Circle(circle) => circle,
6262            other => unreachable!("expected a circle, got {other:?}"),
6263        };
6264        for k in 0..16 {
6265            let p = circle.evaluate(std::f64::consts::TAU * f64::from(k) / 16.0);
6266            assert!(((p - a.center()).length() - 2.0).abs() < 1e-12);
6267            assert!(((p - b.center()).length() - 1.5).abs() < 1e-12);
6268        }
6269        assert!(
6270            exact_sphere_sphere(&a, &ball(4.0, 0.0, 0.0, 1.5))
6271                .unwrap()
6272                .unwrap()
6273                .is_empty()
6274        );
6275        assert!(
6276            exact_sphere_sphere(&a, &ball(0.2, 0.0, 0.0, 1.0))
6277                .unwrap()
6278                .unwrap()
6279                .is_empty()
6280        );
6281        assert!(
6282            exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 1.0))
6283                .unwrap()
6284                .unwrap()
6285                .is_empty()
6286        );
6287        assert!(
6288            exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 2.0))
6289                .unwrap()
6290                .is_none()
6291        );
6292
6293        // A tiny sphere nearly bisected by a large one, in either order, and a
6294        // pair far from the origin: each meets in its small circle.
6295        let radius = |p: &SphericalSurface, q: &SphericalSurface| -> f64 {
6296            match exact_sphere_sphere(p, q).unwrap().unwrap().as_slice() {
6297                [ExactIntersectionCurve::Circle(c)] => c.radius(),
6298                other => unreachable!("expected one circle, got {other:?}"),
6299            }
6300        };
6301        let tiny = ball(2.0, 0.0, 0.0, 1e-5);
6302        assert!((radius(&a, &tiny) - 1e-5).abs() < 1e-9);
6303        assert!((radius(&tiny, &a) - 1e-5).abs() < 1e-9);
6304        let near = radius(&ball(0.0, 0.0, 0.0, 2.0), &ball(3.5, 0.0, 0.0, 1.500_001));
6305        let far = radius(
6306            &ball(1e10, 0.0, 0.0, 2.0),
6307            &ball(1e10 + 3.5, 0.0, 0.0, 1.500_001),
6308        );
6309        assert!(near > 1e-3);
6310        assert!((far - near).abs() < 1e-9 * near.max(1.0));
6311    }
6312
6313    /// Each line among `sections`, and whether it is a ray; any other
6314    /// section fails the test.
6315    #[allow(clippy::panic)]
6316    fn lines_of(sections: &[PlaneSection]) -> Vec<(Line3D, bool)> {
6317        sections
6318            .iter()
6319            .map(|s| match s {
6320                PlaneSection::Line { line, ray } => (line.clone(), *ray),
6321                other => panic!("expected a line, got {other:?}"),
6322            })
6323            .collect()
6324    }
6325
6326    /// A plane along a cylinder's axis cuts its rulings: two through the
6327    /// axis, two 2e-6 apart where it sinks a hair into the cylinder, the one
6328    /// it touches along, and none past it. `exact_plane_analytic` gives no
6329    /// curve for any of them.
6330    #[test]
6331    fn a_plane_along_a_cylinder_cuts_its_rulings() {
6332        let cyl =
6333            CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6334                .unwrap();
6335        let y = Vec3::new(0.0, 1.0, 0.0);
6336        let surface = AnalyticSurface::Cylinder(&cyl);
6337        let on_both = |p: Point3, d: f64| {
6338            assert!((p.y() - d).abs() < 1e-12, "{p:?} off the plane y = {d}");
6339            assert!(
6340                (p.x().hypot(p.y()) - 1.0).abs() < 1e-12,
6341                "{p:?} off the cylinder"
6342            );
6343        };
6344        for (d, count) in [(0.0, 2), (1e-6_f64.cos(), 2), (1.0, 1), (1.5, 0)] {
6345            assert!(exact_plane_analytic(surface, y, d).unwrap().is_empty());
6346            let lines = lines_of(&exact_plane_section(surface, y, d).unwrap());
6347            assert_eq!(lines.len(), count, "plane y = {d}");
6348            let mut xs = Vec::new();
6349            for (line, ray) in lines {
6350                assert!(!ray);
6351                assert!(line.direction().cross(cyl.axis()).length() < 1e-12);
6352                for t in [-3.0, 0.0, 3.0] {
6353                    on_both(line.evaluate(t), d);
6354                }
6355                xs.push(line.evaluate(0.0).x());
6356            }
6357            if count == 2 {
6358                let apart = (xs[0] - xs[1]).abs();
6359                let want = 2.0 * (1.0 - d * d).sqrt();
6360                assert!(
6361                    (apart - want).abs() < 1e-9 * want.max(1e-6),
6362                    "{apart} apart"
6363                );
6364            }
6365        }
6366    }
6367
6368    /// A plane through a cone's apex cuts rays from it: two for a plane
6369    /// through the axis, one for a plane touching the cone along a ruling,
6370    /// and the apex alone for a plane missing the nappe. A plane 5e-8 off the
6371    /// apex still cuts its conic.
6372    #[test]
6373    #[allow(clippy::panic)]
6374    fn a_plane_through_a_cone_apex_cuts_its_rulings() {
6375        use std::f64::consts::FRAC_PI_4;
6376
6377        let cone = ConicalSurface::new(
6378            Point3::new(1.0, 2.0, 3.0),
6379            Vec3::new(0.0, 0.0, 1.0),
6380            FRAC_PI_4,
6381        )
6382        .unwrap();
6383        let surface = AnalyticSurface::Cone(&cone);
6384        let apex = cone.apex();
6385        let through = |n: Vec3| {
6386            let n = n.normalize().unwrap();
6387            let d = n.dot(apex - Point3::new(0.0, 0.0, 0.0));
6388            assert!(exact_plane_analytic(surface, n, d).unwrap().is_empty());
6389            (n, d, exact_plane_section(surface, n, d).unwrap())
6390        };
6391        for (n, count) in [
6392            (Vec3::new(1.0, 0.0, 0.0), 2),
6393            (Vec3::new(1.0, 0.0, -1.0), 1),
6394        ] {
6395            let (n, d, sections) = through(n);
6396            let rays = lines_of(&sections);
6397            assert_eq!(rays.len(), count, "plane normal {n:?}");
6398            for (line, ray) in rays {
6399                assert!(ray);
6400                assert!((line.evaluate(0.0) - apex).length() < 1e-12);
6401                let p = line.evaluate(2.0);
6402                assert!((n.dot(p - Point3::new(0.0, 0.0, 0.0)) - d).abs() < 1e-12);
6403                let rel = p - apex;
6404                assert!(rel.z() > 0.0, "{p:?} on the phantom nappe");
6405                assert!(
6406                    (rel.x().hypot(rel.y()) - rel.z()).abs() < 1e-12,
6407                    "{p:?} off the cone"
6408                );
6409            }
6410        }
6411        for n in [Vec3::new(0.1, 0.0, 1.0), Vec3::new(0.0, 0.0, 1.0)] {
6412            let (_, _, sections) = through(n);
6413            assert!(
6414                matches!(sections[..], [PlaneSection::Point(p)] if (p - apex).length() < 1e-12),
6415                "{sections:?}"
6416            );
6417        }
6418
6419        let upright = ConicalSurface::new(
6420            Point3::new(0.0, 0.0, 0.0),
6421            Vec3::new(0.0, 0.0, 1.0),
6422            FRAC_PI_4,
6423        )
6424        .unwrap();
6425        let n = Vec3::new((0.5 - 1e-8_f64).sqrt(), 0.0, (0.5 + 1e-8_f64).sqrt());
6426        let sections = exact_plane_section(AnalyticSurface::Cone(&upright), n, 5e-8).unwrap();
6427        let [PlaneSection::Ellipse(ellipse)] = &sections[..] else {
6428            panic!("{sections:?}");
6429        };
6430        assert!(
6431            ellipse.semi_major() > 1.0,
6432            "semi-major {}",
6433            ellipse.semi_major()
6434        );
6435    }
6436
6437    /// A plane touching a sphere meets it at the point of contact, and one a
6438    /// hair inside cuts the small circle there, however small.
6439    #[test]
6440    #[allow(clippy::panic)]
6441    fn a_plane_touching_a_sphere_meets_it_at_a_point() {
6442        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 1.0), 1.0).unwrap();
6443        let surface = AnalyticSurface::Sphere(&sphere);
6444        let z = Vec3::new(0.0, 0.0, 1.0);
6445        assert!(exact_plane_analytic(surface, z, 0.0).unwrap().is_empty());
6446        let sections = exact_plane_section(surface, z, 0.0).unwrap();
6447        assert!(
6448            matches!(sections[..], [PlaneSection::Point(p)] if p.z().abs() < 1e-15 && p.x() == 0.0),
6449            "{sections:?}"
6450        );
6451        assert!(exact_plane_section(surface, z, -1e-9).unwrap().is_empty());
6452        for height in [5e-15, 1e-12, 1e-8] {
6453            let sections = exact_plane_section(surface, z, height).unwrap();
6454            let [PlaneSection::Circle(circle)] = &sections[..] else {
6455                panic!("{sections:?}");
6456            };
6457            let want = (height * (2.0 - height)).sqrt();
6458            assert!(
6459                (circle.radius() - want).abs() < 1e-3 * want,
6460                "circle at z = {height}: radius {}, want {want}",
6461                circle.radius()
6462            );
6463            assert!((circle.center().z() - height).abs() < 1e-15);
6464        }
6465    }
6466
6467    /// The farthest any of `curves` strays from `off`, sampled densely.
6468    fn farthest(curves: &[IntersectionCurve], off: impl Fn(Point3) -> f64) -> f64 {
6469        let mut far = 0.0_f64;
6470        for ic in curves {
6471            let (t0, t1) = ic.curve.domain();
6472            for i in 0..=2000 {
6473                let t = t0 + (t1 - t0) * f64::from(i) / 2000.0;
6474                far = far.max(off(ic.curve.evaluate(t)));
6475            }
6476        }
6477        far
6478    }
6479
6480    /// A ball sitting in a bore of its own radius touches it along its
6481    /// equator, which comes back as the exact circle.
6482    #[test]
6483    fn a_ball_in_its_bore_meets_it_on_an_exact_circle() {
6484        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
6485        let bore =
6486            CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6487                .unwrap();
6488        let curves = intersect_analytic_analytic_bounded(
6489            AnalyticSurface::Sphere(&ball),
6490            AnalyticSurface::Cylinder(&bore),
6491            64,
6492            None,
6493            Some((0.0, 4.0)),
6494        )
6495        .unwrap();
6496        assert_eq!(curves.len(), 1);
6497        let far = farthest(&curves, |p| {
6498            let on_ball = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
6499            on_ball
6500                .max((p.x().hypot(p.y()) - 1.0).abs())
6501                .max(p.z().abs())
6502        });
6503        assert!(far < 1e-14, "circle strays {far:.2e}");
6504    }
6505
6506    /// Two unit balls a unit apart meet in a circle of radius √3/2, which
6507    /// comes back exact.
6508    #[test]
6509    fn overlapping_balls_meet_on_an_exact_circle() {
6510        let a = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
6511        let b = SphericalSurface::new(Point3::new(1.0, 0.0, 0.0), 1.0).unwrap();
6512        let curves = intersect_analytic_analytic_bounded(
6513            AnalyticSurface::Sphere(&a),
6514            AnalyticSurface::Sphere(&b),
6515            64,
6516            None,
6517            None,
6518        )
6519        .unwrap();
6520        assert_eq!(curves.len(), 1);
6521        let far = farthest(&curves, |p| {
6522            let on_a = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
6523            on_a.max(((p - Point3::new(1.0, 0.0, 0.0)).length() - 1.0).abs())
6524        });
6525        assert!(far < 1e-14, "circle strays {far:.2e}");
6526    }
6527
6528    /// A loop with semi-axes 3 and 1.5 in a tilted frame lies on its ellipse
6529    /// all the way round and starts at the end of its major axis.
6530    #[test]
6531    fn a_conic_loop_is_its_ellipse() {
6532        let centre = Point3::new(1.0, -2.0, 0.5);
6533        let frame = Frame3::from_normal(centre, Vec3::new(0.3, -0.4, 1.0)).unwrap();
6534        let curve = conic_loop(centre, frame.x, frame.y, 3.0, 1.5).unwrap();
6535        let (t0, t1) = curve.domain();
6536        assert!((curve.evaluate(t0) - (centre + frame.x * 3.0)).length() < 1e-15);
6537        for i in 0..=2000 {
6538            let p = curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 2000.0) - centre;
6539            let (x, y) = (p.dot(frame.x) / 3.0, p.dot(frame.y) / 1.5);
6540            assert!(
6541                (x.hypot(y) - 1.0).abs() < 1e-14,
6542                "off its ellipse by {}",
6543                x.hypot(y) - 1.0
6544            );
6545            assert!(p.dot(frame.z).abs() < 1e-14);
6546        }
6547    }
6548
6549    /// A ball sitting in a ring's hole, and a ring resting on a wider one,
6550    /// meet them along the one circle where they touch, and the bounded
6551    /// call returns it exactly.
6552    #[test]
6553    fn touching_coaxial_rings_meet_along_one_circle() {
6554        let z = Vec3::new(0.0, 0.0, 1.0);
6555        let x = Vec3::new(1.0, 0.0, 0.0);
6556        let ring =
6557            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), 3.0, 1.0, z, x)
6558                .unwrap();
6559        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
6560        let curves = intersect_analytic_analytic_bounded(
6561            AnalyticSurface::Sphere(&ball),
6562            AnalyticSurface::Torus(&ring),
6563            64,
6564            None,
6565            None,
6566        )
6567        .unwrap();
6568        assert_eq!(curves.len(), 1);
6569        let far = farthest(&curves, |p| {
6570            let q = p - Point3::new(0.0, 0.0, 0.0);
6571            let rho = q.x().hypot(q.y());
6572            let on_ring = ((rho - 3.0).hypot(q.z()) - 1.0).abs();
6573            on_ring.max((q.length() - 2.0).abs())
6574        });
6575        assert!(far < 1e-14, "circle strays {far:.2e}");
6576
6577        // Tubes of radius 1 and 0.5 on rings of radius 3 and 3.9, the second
6578        // raised 1.2: their centres lie 1.5 apart, so they touch a third of
6579        // the way along, at height 0.8 on a circle of radius 3.6.
6580        let wider =
6581            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 1.2), 3.9, 0.5, z, x)
6582                .unwrap();
6583        let touching = exact_torus_torus(&ring, &wider).unwrap().unwrap();
6584        let circles = circles_of(&touching);
6585        assert_eq!(circles.len(), 1);
6586        assert!(
6587            (circles[0].radius() - 3.6).abs() < 1e-12,
6588            "{}",
6589            circles[0].radius()
6590        );
6591        assert!((circles[0].center().z() - 0.8).abs() < 1e-12);
6592    }
6593
6594    /// Unit tubes on rings of radius 1e6 and 1e6 + 1.999 overlap by 0.001
6595    /// and cross in two circles 0.063 apart; on rings 2.001 apart they miss.
6596    /// Neither is read as a touch, at a scale where a millionth of it is
6597    /// two thousandths.
6598    #[test]
6599    fn huge_coaxial_rings_cross_or_miss_rather_than_touch() {
6600        let z = Vec3::new(0.0, 0.0, 1.0);
6601        let x = Vec3::new(1.0, 0.0, 0.0);
6602        let ring = |big: f64| {
6603            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), big, 1.0, z, x)
6604                .unwrap()
6605        };
6606        let crossing = exact_torus_torus(&ring(1e6), &ring(1_000_001.999))
6607            .unwrap()
6608            .unwrap();
6609        let circles = circles_of(&crossing);
6610        assert_eq!(circles.len(), 2);
6611        for circle in circles {
6612            let height = (1.0 - 0.9995_f64 * 0.9995).sqrt();
6613            assert!(
6614                (circle.center().z().abs() - height).abs() < 1e-9,
6615                "{}",
6616                circle.center().z()
6617            );
6618        }
6619        let apart = exact_torus_torus(&ring(1e6), &ring(1_000_002.001))
6620            .unwrap()
6621            .unwrap();
6622        assert!(apart.is_empty());
6623    }
6624
6625    /// A plane parallel to a cone's axis cuts the branch of a hyperbola on
6626    /// the cone's one nappe; planes parallel to a generator cut a parabola
6627    /// on one side of the apex and miss the cone on the other.
6628    #[test]
6629    fn a_plane_cuts_a_cones_open_conics() {
6630        let up = Vec3::new(0.0, 0.0, 1.0);
6631        let on_cone = |p: Point3, slope: f64| (p.z() - slope * p.x().hypot(p.y())).abs();
6632        let steep =
6633            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 60_f64.to_radians()).unwrap();
6634        let slope = 60_f64.to_radians().tan();
6635        let along =
6636            exact_plane_section(AnalyticSurface::Cone(&steep), Vec3::new(1.0, 0.0, 0.0), 1.0)
6637                .unwrap();
6638        let [PlaneSection::Hyperbola(h)] = along.as_slice() else {
6639            unreachable!("{along:?}")
6640        };
6641        for i in -20..=20 {
6642            let p = h.evaluate(f64::from(i) / 5.0);
6643            assert!((p.x() - 1.0).abs() < 1e-12 && p.z() > 0.0, "{p:?}");
6644            assert!(on_cone(p, slope) < 1e-12 * p.z().max(1.0), "{p:?}");
6645        }
6646        let even =
6647            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 45_f64.to_radians()).unwrap();
6648        let tilt = Vec3::new(-1.0, 0.0, 1.0) * std::f64::consts::FRAC_1_SQRT_2;
6649        let above = exact_plane_section(AnalyticSurface::Cone(&even), tilt, 1.0).unwrap();
6650        let [PlaneSection::Parabola(parabola)] = above.as_slice() else {
6651            unreachable!("{above:?}")
6652        };
6653        for i in -20..=20 {
6654            let p = parabola.evaluate(f64::from(i) / 2.0);
6655            assert!(
6656                (tilt.dot(p - Point3::new(0.0, 0.0, 0.0)) - 1.0).abs() < 1e-12,
6657                "{p:?}"
6658            );
6659            assert!(
6660                p.z() > 0.0 && on_cone(p, 1.0) < 1e-12 * p.z().max(1.0),
6661                "{p:?}"
6662            );
6663        }
6664        let below = exact_plane_section(AnalyticSurface::Cone(&even), tilt, -1.0).unwrap();
6665        assert!(below.is_empty(), "{below:?}");
6666    }
6667
6668    /// A cone so flat it rises 1e-7 from its radial plane, cut by a plane
6669    /// tilted 7e-7 off it, and a cone so narrow it opens 5e-7 off its axis,
6670    /// cut by a plane parallel to the axis, give sections that lie on the
6671    /// cone: a hyperbola for the flat one, read from its eccentricity, and
6672    /// sampled points where the formulas lose their digits.
6673    #[test]
6674    fn extreme_cones_give_sections_on_the_cone() {
6675        let up = Vec3::new(0.0, 0.0, 1.0);
6676        let apex = Point3::new(0.0, 0.0, 0.0);
6677        let holds = |cone: &ConicalSurface, q: Point3| {
6678            let w = q - apex;
6679            (w.dot(up) - cone.half_angle().sin() * w.length()).abs() <= 1e-6 * (1.0 + w.length())
6680        };
6681        let flat = ConicalSurface::new(apex, up, 1e-7).unwrap();
6682        let tilt = Vec3::new(5e-13_f64.sqrt(), 0.0, (1.0 - 5e-13_f64).sqrt());
6683        let needle = ConicalSurface::new(apex, up, FRAC_PI_2 - 5e-7).unwrap();
6684        for (cone, normal, d) in [(&flat, tilt, 1.0), (&needle, Vec3::new(1.0, 0.0, 0.0), 1.0)] {
6685            let sections = exact_plane_section(AnalyticSurface::Cone(cone), normal, d).unwrap();
6686            assert!(!sections.is_empty());
6687            for section in &sections {
6688                let points: Vec<Point3> = match section {
6689                    PlaneSection::Hyperbola(h) => {
6690                        (-4..=4).map(|i| h.evaluate(f64::from(i) / 4.0)).collect()
6691                    }
6692                    PlaneSection::Parabola(q) => {
6693                        (-4..=4).map(|i| q.evaluate(f64::from(i))).collect()
6694                    }
6695                    PlaneSection::Points(points) => points.clone(),
6696                    other => unreachable!("{other:?}"),
6697                };
6698                for q in points {
6699                    assert!(holds(cone, q), "{q:?} off the cone");
6700                }
6701            }
6702        }
6703        let flat_section = exact_plane_section(AnalyticSurface::Cone(&flat), tilt, 1.0).unwrap();
6704        assert!(matches!(
6705            flat_section.as_slice(),
6706            [PlaneSection::Hyperbola(_)]
6707        ));
6708    }
6709
6710    /// The rulings two parallel cylinders meet along, from the bounded call
6711    /// with each face's `v` range: each ruling's ends, sorted by height.
6712    fn parallel_rulings(
6713        (c1, r1, v1): (Point3, f64, (f64, f64)),
6714        (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
6715    ) -> Vec<(Point3, Point3)> {
6716        rulings_within((c1, r1, v1), (c2, r2, axis2, v2), 1e-12)
6717    }
6718
6719    /// [`parallel_rulings`] with each curve held to `tolerance` of both
6720    /// cylinders.
6721    fn rulings_within(
6722        (c1, r1, v1): (Point3, f64, (f64, f64)),
6723        (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
6724        tolerance: f64,
6725    ) -> Vec<(Point3, Point3)> {
6726        let a = CylindricalSurface::new(c1, Vec3::new(0.0, 0.0, 1.0), r1).unwrap();
6727        let b = CylindricalSurface::new(c2, axis2, r2).unwrap();
6728        let curves = intersect_analytic_analytic_bounded(
6729            AnalyticSurface::Cylinder(&a),
6730            AnalyticSurface::Cylinder(&b),
6731            32,
6732            Some(v1),
6733            Some(v2),
6734        )
6735        .unwrap();
6736        curves
6737            .iter()
6738            .map(|ic| {
6739                let (t0, t1) = ic.curve.domain();
6740                let (p, q) = (ic.curve.evaluate(t0), ic.curve.evaluate(t1));
6741                for i in 0..=100 {
6742                    let x = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 100.0);
6743                    let on_a = ((x - c1) - Vec3::new(0.0, 0.0, (x - c1).z())).length() - r1;
6744                    let w = x - c2;
6745                    let on_b = (w - axis2 * w.dot(axis2)).length() - r2;
6746                    assert!(
6747                        on_a.abs() < tolerance && on_b.abs() < tolerance,
6748                        "{x:?} off a cylinder by {on_a:.1e}, {on_b:.1e}"
6749                    );
6750                }
6751                if p.z() <= q.z() { (p, q) } else { (q, p) }
6752            })
6753            .collect()
6754    }
6755
6756    /// Rods of radius 1 with axes 1.2 apart overlap along two rulings, at
6757    /// x 0.6 and y ±0.8, over the height both faces share; the second rod's
6758    /// axis runs down, so its range counts down from its origin.
6759    #[test]
6760    fn overlapping_parallel_rods_meet_along_two_rulings() {
6761        let mut rulings = parallel_rulings(
6762            (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 4.0)),
6763            (
6764                Point3::new(1.2, 0.0, 3.0),
6765                1.0,
6766                Vec3::new(0.0, 0.0, -1.0),
6767                (0.0, 2.0),
6768            ),
6769        );
6770        rulings.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
6771        assert_eq!(rulings.len(), 2);
6772        for ((lo, hi), y) in rulings.into_iter().zip([-0.8, 0.8]) {
6773            assert!((lo - Point3::new(0.6, y, 1.0)).length() < 1e-12, "{lo:?}");
6774            assert!((hi - Point3::new(0.6, y, 3.0)).length() < 1e-12, "{hi:?}");
6775        }
6776    }
6777
6778    /// Rods touching side by side, or one inside another against its wall,
6779    /// meet along the one ruling where they touch; rods apart do not meet.
6780    #[test]
6781    fn touching_parallel_rods_meet_along_one_ruling() {
6782        let up = Vec3::new(0.0, 0.0, 1.0);
6783        let beside = parallel_rulings(
6784            (Point3::new(0.0, 0.0, 0.0), 1.0, (-2.0, 2.0)),
6785            (Point3::new(2.0, 0.0, -2.0), 1.0, up, (0.0, 4.0)),
6786        );
6787        assert_eq!(beside.len(), 1);
6788        assert!((beside[0].0 - Point3::new(1.0, 0.0, -2.0)).length() < 1e-12);
6789        assert!((beside[0].1 - Point3::new(1.0, 0.0, 2.0)).length() < 1e-12);
6790        let inside = parallel_rulings(
6791            (Point3::new(0.0, 0.0, 0.0), 2.0, (0.0, 1.0)),
6792            (Point3::new(-1.0, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
6793        );
6794        assert_eq!(inside.len(), 1);
6795        assert!((inside[0].0 - Point3::new(-2.0, 0.0, 0.0)).length() < 1e-12);
6796        let apart = parallel_rulings(
6797            (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 1.0)),
6798            (Point3::new(2.5, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
6799        );
6800        assert!(apart.is_empty());
6801    }
6802
6803    /// Rods whose axes lean 1e-5 apart drift 1e-3 over a span of 100, so
6804    /// the rulings defer to the next solver there; over a span of 0.001
6805    /// they drift 1e-8 and keep their two rulings.
6806    #[test]
6807    fn rods_leaning_apart_keep_rulings_only_over_a_short_span() {
6808        let up = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6809            .unwrap();
6810        let lean = Vec3::new(1e-5_f64.sin(), 0.0, 1e-5_f64.cos());
6811        let leaning = CylindricalSurface::new(Point3::new(1.2, 0.0, 0.0), lean, 1.0).unwrap();
6812        let span = |h: f64| parallel_cylinders(&up, &leaning, Some((0.0, h)), Some((0.0, h)));
6813        assert!(span(100.0).unwrap().is_none());
6814        assert_eq!(span(0.001).unwrap().map(|r| r.len()), Some(2));
6815    }
6816
6817    /// Huge rods a short stretch long still meet along both rulings, and
6818    /// rods of radius 100 whose axes lie 3e-7 short of touching meet along
6819    /// two rulings 0.011 apart, not the one where they would touch.
6820    #[test]
6821    fn parallel_rods_keep_short_and_close_rulings() {
6822        let up = Vec3::new(0.0, 0.0, 1.0);
6823        let huge = rulings_within(
6824            (Point3::new(0.0, 0.0, 0.0), 1e6, (0.0, 0.001)),
6825            (Point3::new(1.2e6, 0.0, 0.0), 1e6, up, (0.0, 0.001)),
6826            1e-9,
6827        );
6828        assert_eq!(huge.len(), 2);
6829        assert!(
6830            huge.iter()
6831                .all(|(lo, hi)| ((*hi - *lo).length() - 0.001).abs() < 1e-12)
6832        );
6833        let mut close = rulings_within(
6834            (Point3::new(0.0, 0.0, 0.0), 100.0, (0.0, 1.0)),
6835            (Point3::new(199.999_999_7, 0.0, 0.0), 100.0, up, (0.0, 1.0)),
6836            1e-9,
6837        );
6838        assert_eq!(close.len(), 2);
6839        close.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
6840        let apart = close[1].0.y() - close[0].0.y();
6841        assert!((apart - 0.010_954).abs() < 1e-5, "{apart}");
6842    }
6843
6844    /// A ball off a ring's axis touches it at one point from outside the
6845    /// tube, from inside it, or holding the whole ring, and that point is
6846    /// all they share. A ball reaching 1e-6 further cuts the tube in a small
6847    /// loop, and one centred on the core circle meets it along a meridian;
6848    /// both are the marcher's.
6849    #[test]
6850    fn a_ball_off_a_rings_axis_touches_it_at_one_point() {
6851        let o = Point3::new(1.0, 2.0, 3.0);
6852        let ring = ToroidalSurface::new(o, 3.0, 1.0).unwrap();
6853        let (s, c) = 30.0_f64.to_radians().sin_cos();
6854        let (out, up) = (Vec3::new(c, s, 0.0), Vec3::new(0.0, 0.0, 1.0));
6855        let on_ring = |p: Point3| {
6856            let q = p - o;
6857            ((q.x().hypot(q.y()) - 3.0).hypot(q.z()) - 1.0).abs()
6858        };
6859        let balls = [
6860            (o + out * 5.0, 1.0),
6861            (o + out * 3.2 + up * 0.1, 1.0 - 0.05_f64.sqrt()),
6862            (o + out + up * 0.5, 1.0 + 16.25_f64.sqrt()),
6863        ];
6864        let mut touches = Vec::new();
6865        for (centre, radius) in balls {
6866            let ball = SphericalSurface::new(centre, radius).unwrap();
6867            let exacts = exact_sphere_torus(&ball, &ring).unwrap().unwrap();
6868            let p = match exacts.as_slice() {
6869                [ExactIntersectionCurve::Points(points)] => points[0],
6870                _ => unreachable!("one touching point"),
6871            };
6872            assert!(on_ring(p) < 1e-12 && ((p - centre).length() - radius).abs() < 1e-12);
6873            let curves = intersect_analytic_analytic(
6874                AnalyticSurface::Sphere(&ball),
6875                AnalyticSurface::Torus(&ring),
6876                16,
6877            )
6878            .unwrap();
6879            assert_eq!(curves.len(), 1);
6880            let (t0, t1) = curves[0].curve.domain();
6881            assert!((curves[0].curve.evaluate(t0) - p).length() < 1e-15);
6882            assert!((curves[0].curve.evaluate(t1) - p).length() < 1e-15);
6883            touches.push(p);
6884        }
6885        assert!((touches[0] - (o + out * 4.0)).length() < 1e-12);
6886        let past = SphericalSurface::new(o + out * 5.0, 1.0 + 1e-6).unwrap();
6887        assert!(exact_sphere_torus(&past, &ring).unwrap().is_none());
6888        let on_core = SphericalSurface::new(o + out * 3.0, 1.0).unwrap();
6889        assert!(exact_sphere_torus(&on_core, &ring).unwrap().is_none());
6890    }
6891}