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 crate::madd::Madd;
8use std::cell::RefCell;
9use std::f64::consts::{FRAC_PI_2, TAU};
10
11use crate::MathError;
12use crate::aabb::Aabb3;
13use crate::curves::{Circle3D, Ellipse3D, Hyperbola3D, Line3D, Parabola3D};
14use crate::frame::Frame3;
15use crate::nurbs::curve::NurbsCurve;
16use crate::nurbs::fitting::interpolate;
17use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
18use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
19use crate::tolerance::Tolerance;
20use crate::vec::{Point3, Vec3};
21
22mod cover;
23mod section_fit;
24use section_fit::{crosses_at, fit_section, settle_on_section};
25pub use section_fit::{point_off_surface, spline_off_surface};
26
27/// Exact curve type resulting from plane-analytic surface intersection.
28#[derive(Debug, Clone)]
29pub enum ExactIntersectionCurve {
30    /// A circle (plane perpendicular to axis of cylinder/cone/sphere).
31    Circle(Circle3D),
32    /// An ellipse (plane oblique to cylinder/cone axis).
33    Ellipse(Ellipse3D),
34    /// Fallback to sampled point chain (torus, degenerate cases).
35    Points(Vec<Point3>),
36}
37
38/// A plane's section of an analytic surface, from [`exact_plane_section`].
39#[derive(Debug, Clone)]
40#[non_exhaustive]
41pub enum PlaneSection {
42    /// A circle.
43    Circle(Circle3D),
44    /// An ellipse.
45    Ellipse(Ellipse3D),
46    /// A straight section: a cylinder's ruling, running both ways from the
47    /// line's origin, or with `ray` a cone's ruling, running from the apex at
48    /// the line's origin along its direction only.
49    Line {
50        /// The ruling's line.
51        line: Line3D,
52        /// Whether the section runs one way only, from the line's origin.
53        ray: bool,
54    },
55    /// The one point where the plane touches the surface.
56    Point(Point3),
57    /// A sampled chain of points along the section.
58    Points(Vec<Point3>),
59    /// A cone's parabola.
60    Parabola(Parabola3D),
61    /// The branch of a cone's hyperbola on the cone's one nappe, which the
62    /// hyperbola's `u_axis` points to from its centre.
63    Hyperbola(Hyperbola3D),
64}
65
66impl From<ExactIntersectionCurve> for PlaneSection {
67    fn from(curve: ExactIntersectionCurve) -> Self {
68        match curve {
69            ExactIntersectionCurve::Circle(circle) => Self::Circle(circle),
70            ExactIntersectionCurve::Ellipse(ellipse) => Self::Ellipse(ellipse),
71            ExactIntersectionCurve::Points(points) => Self::Points(points),
72        }
73    }
74}
75
76/// A plane's exact section of an analytic surface.
77///
78/// It includes the sections [`exact_plane_analytic`] has no curve for: the
79/// rulings a plane along a cylinder's axis or through a cone's apex cuts,
80/// and the point where a plane touches a sphere or meets a cone at its apex
81/// alone. A cone's parabola and hyperbola come back as curves, which
82/// [`exact_plane_analytic`] samples into points, except in a band about the
83/// parabola where neither form keeps its digits.
84///
85/// The plane is `dot(normal, p) = d`, with `normal` of unit length.
86///
87/// # Errors
88///
89/// Returns an error if a section's curve cannot be built.
90pub fn exact_plane_section(
91    surface: AnalyticSurface<'_>,
92    normal: Vec3,
93    d: f64,
94) -> Result<Vec<PlaneSection>, MathError> {
95    match surface {
96        AnalyticSurface::Cylinder(cyl) if normal.dot(cyl.axis()).abs() < 1e-10 => {
97            return plane_cylinder_rulings(cyl, normal, d);
98        }
99        AnalyticSurface::Cone(cone) if plane_holds_apex(cone, normal, d) => {
100            return plane_cone_apex_rulings(cone, normal);
101        }
102        AnalyticSurface::Cone(cone) => {
103            if let Some(open) = plane_cone_open_section(cone, normal, d)? {
104                return Ok(open);
105            }
106        }
107        AnalyticSurface::Sphere(sphere) => {
108            let h = dot_np(normal, sphere.center()) - d;
109            let r = sphere.radius();
110            if (r - h.abs()).abs() <= TOUCH * r {
111                return Ok(vec![PlaneSection::Point(Point3::new(
112                    h.madd(-normal.x(), sphere.center().x()),
113                    h.madd(-normal.y(), sphere.center().y()),
114                    h.madd(-normal.z(), sphere.center().z()),
115                ))]);
116            }
117        }
118        AnalyticSurface::Cylinder(_) | AnalyticSurface::Torus(_) => {}
119    }
120    Ok(exact_plane_analytic(surface, normal, d)?
121        .into_iter()
122        .map(PlaneSection::from)
123        .collect())
124}
125
126/// How far a cone section's `e² − 1` (its eccentricity squared, less one)
127/// may sit from zero for the section to be read as a parabola.
128const PARABOLIC: f64 = 1e-12;
129
130/// Where a cone's hyperbola starts, in `e² − 1`: its centre lies the
131/// plane's offset over the conic coefficient away, and nearer zero its
132/// vertex loses digits.
133const HYPERBOLIC: f64 = 1e-6;
134
135/// A plane's parabola or hyperbola section of a cone, on the cone's one
136/// nappe, worked in the frame of [`exact_plane_cone`]. `None` for a circle
137/// or an ellipse, in the band between [`PARABOLIC`] and [`HYPERBOLIC`], and
138/// for a curve whose points do not hold to the cone (a cone so narrow or so
139/// flat that the formulas lose their digits), all of which go to the
140/// sampled section.
141#[allow(clippy::many_single_char_names)]
142fn plane_cone_open_section(
143    cone: &ConicalSurface,
144    normal: Vec3,
145    d: f64,
146) -> Result<Option<Vec<PlaneSection>>, MathError> {
147    let axis = cone.axis();
148    let c = normal.dot(axis);
149    let p2 = c.madd(-c, 1.0).max(0.0);
150    let p = p2.sqrt();
151    let rise = cone.half_angle().sin();
152    let k = rise * rise;
153    let a_coeff = p2 - k;
154    let eccentric = a_coeff / k;
155    let m = axis - normal * c;
156    let m_len = m.length();
157    if m_len < 1e-12 || eccentric < -PARABOLIC || (eccentric > PARABOLIC && eccentric <= HYPERBOLIC)
158    {
159        return Ok(None);
160    }
161    let e1 = m * (1.0 / m_len);
162    let e2 = normal.cross(e1);
163    let apex = cone.apex();
164    let e = d - dot_np(normal, apex);
165    let origin = apex + normal * e;
166    // A point `s` along `e1` from `origin` lies `e·c + s·p` up the axis from
167    // the apex, which the real nappe keeps non-negative.
168    let real = |s: f64| e.madd(c, s * p) >= 0.0;
169    // On the one nappe a point's height up the axis is `rise` times its
170    // distance from the apex.
171    let holds = |q: Point3| {
172        let w = q - apex;
173        let reach = w.length();
174        reach.is_finite() && (w.dot(axis) - rise * reach).abs() <= 1e-9 * (1.0 + reach)
175    };
176    if eccentric <= PARABOLIC {
177        // k t² = 2ecp s + e²(c² − k): the vertex at t = 0, opening along e1
178        // with the sign of ecp, `1 / 4f = k / 2|ecp|`.
179        let ecp = e * c * p;
180        let vertex_s = -e * (c * c - k) / (2.0 * c * p);
181        let focal = ecp.abs() / (2.0 * k);
182        if !(vertex_s.is_finite() && focal > 0.0 && focal.is_finite()) {
183            return Ok(None);
184        }
185        if !real(vertex_s) {
186            return Ok(Some(Vec::new()));
187        }
188        let parabola = Parabola3D::with_axes(origin + e1 * vertex_s, e1 * ecp.signum(), e2, focal)?;
189        if ![0.0, focal, -focal]
190            .iter()
191            .all(|&t| holds(parabola.evaluate(t)))
192        {
193            return Ok(None);
194        }
195        return Ok(Some(vec![PlaneSection::Parabola(parabola)]));
196    }
197    // A(s − s_c)² − k t² = e²k(1 − k)/A: the branches' vertices lie a real
198    // semi-axis either side of the centre, one on each nappe.
199    let centre_s = -e * c * p / a_coeff;
200    let rhs = e * e * k * (1.0 - k) / a_coeff;
201    let (real_axis, imaginary_axis) = ((rhs / a_coeff).sqrt(), (rhs / k).sqrt());
202    if !(real_axis > 0.0 && imaginary_axis > 0.0 && centre_s.is_finite()) {
203        return Ok(None);
204    }
205    let toward = if real(centre_s + real_axis) { e1 } else { -e1 };
206    let hyperbola = Hyperbola3D::with_axes(
207        origin + e1 * centre_s,
208        real_axis,
209        imaginary_axis,
210        toward,
211        e2,
212    )?;
213    if ![0.0, 1.0, -1.0]
214        .iter()
215        .all(|&t| holds(hyperbola.evaluate(t)))
216    {
217        return Ok(None);
218    }
219    Ok(Some(vec![PlaneSection::Hyperbola(hyperbola)]))
220}
221
222/// Rounding band, relative, within which a plane counts as touching a
223/// surface or passing through a cone's apex.
224const TOUCH: f64 = 4.0 * f64::EPSILON;
225
226/// The rulings a plane along a cylinder's axis cuts from it: two lines, the
227/// one it touches along, or none.
228fn plane_cylinder_rulings(
229    cyl: &CylindricalSurface,
230    normal: Vec3,
231    d: f64,
232) -> Result<Vec<PlaneSection>, MathError> {
233    // n·P(u, 0) = n·O + r·(a cos u + b sin u): the plane holds the ruling at
234    // u where cos(u − φ) = (d − n·O) / (r·√(a² + b²)).
235    let (a, b) = (normal.dot(cyl.x_axis()), normal.dot(cyl.y_axis()));
236    let amp = a.hypot(b);
237    if amp < 1e-12 {
238        return Ok(vec![]);
239    }
240    let ratio = (d - dot_np(normal, cyl.origin())) / (cyl.radius() * amp);
241    if ratio.abs() > 1.0 + TOUCH {
242        return Ok(vec![]);
243    }
244    let phi = b.atan2(a);
245    let spread = ratio.clamp(-1.0, 1.0).acos();
246    let at = if ratio.abs() >= 1.0 - TOUCH {
247        vec![phi + spread]
248    } else {
249        vec![phi + spread, phi - spread]
250    };
251    at.into_iter()
252        .map(|u| {
253            Ok(PlaneSection::Line {
254                line: Line3D::new(cyl.evaluate(u, 0.0), cyl.axis())?,
255                ray: false,
256            })
257        })
258        .collect()
259}
260
261/// Whether a plane passes through a cone's apex, but for rounding.
262fn plane_holds_apex(cone: &ConicalSurface, normal: Vec3, d: f64) -> bool {
263    let apex = cone.apex() - Point3::new(0.0, 0.0, 0.0);
264    (normal.dot(apex) - d).abs() <= TOUCH * (1.0 + apex.length() + d.abs())
265}
266
267/// The rulings a plane through a cone's apex cuts from its nappe, as rays
268/// from the apex: two, the one it touches along, or none, when the plane
269/// meets the cone at the apex alone.
270fn plane_cone_apex_rulings(
271    cone: &ConicalSurface,
272    normal: Vec3,
273) -> Result<Vec<PlaneSection>, MathError> {
274    // g(u) = cos a·(cos u·X + sin u·Y) + sin a·axis, so n·g(u) = 0 reads
275    // A cos u + B sin u = −C.
276    let (sin_a, cos_a) = cone.half_angle().sin_cos();
277    let a = cos_a * normal.dot(cone.x_axis());
278    let b = cos_a * normal.dot(cone.y_axis());
279    let c = sin_a * normal.dot(cone.axis());
280    let amp = a.hypot(b);
281    let apex = cone.apex();
282    if amp < 1e-12 * c.abs().max(1.0) {
283        return Ok(vec![PlaneSection::Point(apex)]);
284    }
285    let ratio = -c / amp;
286    if ratio.abs() > 1.0 + TOUCH {
287        return Ok(vec![PlaneSection::Point(apex)]);
288    }
289    let phi = b.atan2(a);
290    let spread = ratio.clamp(-1.0, 1.0).acos();
291    let at = if ratio.abs() >= 1.0 - TOUCH {
292        vec![phi + spread]
293    } else {
294        vec![phi + spread, phi - spread]
295    };
296    at.into_iter()
297        .map(|u| {
298            Ok(PlaneSection::Line {
299                line: Line3D::new(apex, cone.evaluate(u, 1.0) - apex)?,
300                ray: true,
301            })
302        })
303        .collect()
304}
305
306/// Compute exact intersection curves between a plane and an analytic surface.
307///
308/// Returns exact `Circle3D` or `Ellipse3D` where possible, falling back to
309/// sampled points for complex cases (torus).
310///
311/// A plane along a cylinder's axis or through a cone's apex, whose sections
312/// are straight, and a plane touching a sphere get no curve here;
313/// [`exact_plane_section`] returns those sections.
314///
315/// The plane is defined by `dot(normal, p) = d`.
316///
317/// # Errors
318///
319/// Returns an error if the intersection computation fails.
320pub fn exact_plane_analytic(
321    surface: AnalyticSurface<'_>,
322    plane_normal: Vec3,
323    plane_d: f64,
324) -> Result<Vec<ExactIntersectionCurve>, MathError> {
325    exact_plane_analytic_reaching(surface, plane_normal, plane_d, 0.0)
326}
327
328/// [`exact_plane_analytic`] with a cone's sampled hyperbola or parabola
329/// carried at least `reach` from the apex, so it spans whatever faces the
330/// caller will trim it to.
331///
332/// # Errors
333///
334/// Returns an error if the intersection computation fails.
335pub fn exact_plane_analytic_reaching(
336    surface: AnalyticSurface<'_>,
337    plane_normal: Vec3,
338    plane_d: f64,
339    reach: f64,
340) -> Result<Vec<ExactIntersectionCurve>, MathError> {
341    match surface {
342        AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
343        AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
344        AnalyticSurface::Cone(cone) if plane_holds_apex(cone, plane_normal, plane_d) => Ok(vec![]),
345        AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d, reach),
346        AnalyticSurface::Torus(torus) => {
347            if let Some(circles) = exact_plane_torus(torus, plane_normal, plane_d)? {
348                return Ok(circles);
349            }
350            if let Some(loops) = plane_torus_winding_loops(torus, plane_normal, plane_d, 128) {
351                return Ok(loops
352                    .into_iter()
353                    .map(ExactIntersectionCurve::Points)
354                    .collect());
355            }
356            // Other torus sections are degree-4 — fall back to sampling.
357            let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
358            Ok(chains
359                .into_iter()
360                .map(ExactIntersectionCurve::Points)
361                .collect())
362        }
363    }
364}
365
366/// The plane-torus sections that are circles:
367///
368/// - a plane across the axis at height `h` from the centre, `|h| < r`: the
369///   two circles of radius `R ± sqrt(r² − h²)` about the axis;
370/// - a plane through the axis: the two tube cross-sections of radius `r`,
371///   `R` either side of the axis.
372///
373/// A plane across the axis tangent to the tube's top or bottom touches it
374/// along the one circle of radius `R`, ring or spindle.
375///
376/// `Some` of no curves for a plane across the axis that misses the tube;
377/// `None` for any other plane, and for a section across the axis whose inner
378/// circle would reach the axis.
379fn exact_plane_torus(
380    torus: &ToroidalSurface,
381    normal: Vec3,
382    d: f64,
383) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
384    let len = normal.length();
385    let n = normal.normalize()?;
386    let d = d / len;
387    let axis = torus.z_axis();
388    let center = torus.center();
389    let (big, small) = (torus.major_radius(), torus.minor_radius());
390    let height = d - dot_np(n, center);
391    let along = n.dot(axis);
392    if along.abs() > 1.0 - 1e-10 {
393        if height.abs() >= small - 1e-10 * small {
394            if height.abs() > small + 1e-10 * small {
395                return Ok(Some(Vec::new()));
396            }
397            // Tangent to the tube's top or bottom: the plane touches the
398            // torus along the one circle of its own radius. That circle lies
399            // on the torus within the plane's distance from the tube's top,
400            // so it stands for the section while that distance is within the
401            // linear tolerance, whatever the scale. A tilted plane's section
402            // is no circle.
403            if big <= 1e-10 * small
404                || axis.cross(n).length() > 1e-12
405                || (small - height.abs()).abs() > crate::tolerance::Tolerance::default().linear
406            {
407                return Ok(None);
408            }
409            let middle = center + n * height;
410            return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
411                middle, n, big,
412            )?)]));
413        }
414        let reach = small.madd(small, -(height * height)).sqrt();
415        if big - reach <= 1e-10 * big {
416            return Ok(None);
417        }
418        let middle = center + n * height;
419        return Ok(Some(vec![
420            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big + reach)?),
421            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big - reach)?),
422        ]));
423    }
424    if along.abs() < 1e-10 && height.abs() < 1e-10 * (big + small) {
425        let out = axis.cross(n).normalize()?;
426        return Ok(Some(vec![
427            ExactIntersectionCurve::Circle(Circle3D::new(center + out * big, n, small)?),
428            ExactIntersectionCurve::Circle(Circle3D::new(center - out * big, n, small)?),
429        ]));
430    }
431    Ok(None)
432}
433
434/// Exact plane-cylinder intersection.
435///
436/// - Plane perpendicular to axis → `Circle3D`
437/// - Plane oblique to axis → `Ellipse3D`
438/// - Plane parallel to axis → `Points` fallback (0 or 2 lines)
439fn exact_plane_cylinder(
440    cyl: &CylindricalSurface,
441    normal: Vec3,
442    d: f64,
443) -> Result<Vec<ExactIntersectionCurve>, MathError> {
444    let axis = cyl.axis();
445    let cos_theta = normal.dot(axis).abs();
446    let r = cyl.radius();
447
448    if cos_theta < 1e-10 {
449        // A plane along the axis cuts straight rulings, which
450        // `exact_plane_section` returns.
451        return Ok(vec![]);
452    }
453
454    // Find where axis intersects the plane: axis_point + t*axis, dot(normal, P) = d
455    // t = (d - dot(normal, origin)) / dot(normal, axis)
456    let n_dot_axis = normal.dot(axis);
457    let n_dot_origin = dot_np(normal, cyl.origin());
458    let t = (d - n_dot_origin) / n_dot_axis;
459    let center_on_axis = Point3::new(
460        cyl.origin().x() + t * axis.x(),
461        cyl.origin().y() + t * axis.y(),
462        cyl.origin().z() + t * axis.z(),
463    );
464
465    if cos_theta > 1.0 - 1e-10 {
466        // Plane perpendicular to axis → Circle
467        let circle = Circle3D::new(center_on_axis, normal, r)?;
468        Ok(vec![ExactIntersectionCurve::Circle(circle)])
469    } else {
470        // Oblique plane → Ellipse
471        // Semi-minor = r (the cylinder radius, unchanged)
472        // Semi-major = r / cos(θ) where θ = angle between plane normal and axis
473        let semi_minor = r;
474        let semi_major = r / cos_theta;
475
476        // The major axis direction lies in the intersection of the plane
477        // with the plane containing the axis and the plane normal.
478        // It's the projection of the axis onto the cutting plane, normalized.
479        let axis_proj = Vec3::new(
480            axis.x() - n_dot_axis * normal.x(),
481            axis.y() - n_dot_axis * normal.y(),
482            axis.z() - n_dot_axis * normal.z(),
483        );
484        let u_axis = axis_proj.normalize()?;
485        let v_axis = normal.cross(u_axis);
486
487        let ellipse = Ellipse3D::with_axes(
488            center_on_axis,
489            normal,
490            semi_major,
491            semi_minor,
492            u_axis,
493            v_axis,
494        )?;
495        Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
496    }
497}
498
499/// Exact plane-sphere intersection.
500///
501/// Always produces a `Circle3D` (or empty if no intersection).
502fn exact_plane_sphere(
503    sphere: &SphericalSurface,
504    normal: Vec3,
505    d: f64,
506) -> Result<Vec<ExactIntersectionCurve>, MathError> {
507    let h = dot_np(normal, sphere.center()) - d;
508    let r = sphere.radius();
509
510    // A plane touching the sphere meets it at a point, which
511    // `exact_plane_section` returns.
512    if r - h.abs() <= TOUCH * r {
513        return Ok(vec![]);
514    }
515
516    let circle_r = (r.madd(r, -(h * h))).sqrt();
517    let circle_center = Point3::new(
518        h.madd(-normal.x(), sphere.center().x()),
519        h.madd(-normal.y(), sphere.center().y()),
520        h.madd(-normal.z(), sphere.center().z()),
521    );
522
523    let circle = Circle3D::new(circle_center, normal, circle_r)?;
524    Ok(vec![ExactIntersectionCurve::Circle(circle)])
525}
526
527/// Exact sphere-sphere intersection: the circle on the two spheres' radical
528/// plane, its normal pointing from the first centre to the second. `None`
529/// for one sphere twice (the same surface, no curve).
530///
531/// The circle is built from the smaller sphere, whose radius bounds it, and
532/// from the centres' offset alone, so neither the operands' order nor where
533/// the pair sits in space decides whether a small circle survives.
534///
535/// # Errors
536///
537/// Returns an error if the circle cannot be built.
538pub fn exact_sphere_sphere(
539    s1: &SphericalSurface,
540    s2: &SphericalSurface,
541) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
542    let delta = s2.center() - s1.center();
543    let d = delta.length();
544    let (r1, r2) = (s1.radius(), s2.radius());
545    let scale = r1.max(r2);
546    if d <= 1e-12 * scale {
547        // Concentric spheres of different radii never meet.
548        return Ok(((r1 - r2).abs() > 1e-12 * scale).then(Vec::new));
549    }
550    let normal = delta * (1.0 / d);
551    // From the smaller sphere's centre toward the larger's, the radical plane
552    // lies `along` away.
553    let (centre, toward, r_small, r_big) = if r1 <= r2 {
554        (s1.center(), normal, r1, r2)
555    } else {
556        (s2.center(), -normal, r2, r1)
557    };
558    let along = d.madd(d, r_small.madd(r_small, -(r_big * r_big))) / (2.0 * d);
559    if along.abs() > r_small - 1e-10 * scale.max(1.0) {
560        return Ok(Some(Vec::new()));
561    }
562    let radius = r_small.madd(r_small, -(along * along)).sqrt();
563    let circle = Circle3D::new(centre + toward * along, normal, radius)?;
564    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
565}
566
567/// Exact plane-cone intersection.
568///
569/// The conic type is set by the cone's half-opening angle from the axis
570/// (`γ = π/2 − half_angle`) versus the plane-axis angle `ψ`:
571/// - Plane perpendicular to axis (`ψ = π/2`) → `Circle3D`
572/// - `ψ > γ` (ellipse) → closed-form `Ellipse3D`
573/// - `ψ ≤ γ` (parabola/hyperbola) → bounded single-branch `Points` (one chain
574///   per branch — a hyperbola's two nappes never share a chain)
575fn exact_plane_cone(
576    cone: &ConicalSurface,
577    normal: Vec3,
578    d: f64,
579    reach: f64,
580) -> Result<Vec<ExactIntersectionCurve>, MathError> {
581    let axis = cone.axis();
582    let cos_theta = normal.dot(axis).abs();
583    let half_angle = cone.half_angle();
584
585    if cos_theta > 1.0 - 1e-10 {
586        // Plane perpendicular to axis → Circle
587        // Find where axis meets the plane
588        let n_dot_axis = normal.dot(axis);
589        let n_dot_apex = dot_np(normal, cone.apex());
590        let t = (d - n_dot_apex) / n_dot_axis;
591
592        // t is the signed distance from apex to plane along the axis.
593        // The real cone is a single nappe; the perpendicular-plane section is a
594        // circle whose radius follows from the axial offset |t|.
595        // |t| ≈ 0 means the plane passes through the apex → degenerate point.
596        if t.abs() < 1e-10 {
597            return Ok(vec![]);
598        }
599
600        let center = Point3::new(
601            cone.apex().x() + t * axis.x(),
602            cone.apex().y() + t * axis.y(),
603            cone.apex().z() + t * axis.z(),
604        );
605        // half_angle is the angle from the radial plane to the surface.
606        // Axial distance t = v * sin(half_angle), so v = t / sin(half_angle).
607        // Radius at v = v * cos(half_angle) = t * cos(half_angle) / sin(half_angle).
608        let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
609        if circle_r < 1e-15 {
610            return Ok(vec![]);
611        }
612
613        let circle = Circle3D::new(center, normal, circle_r)?;
614        return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
615    }
616
617    // Oblique plane. Classify the conic in the plane-aligned frame.
618    //
619    // Decompose the (unit) axis as a = c·n + p·e1, where c = n·a, e1 is the unit
620    // in-plane projection of the axis, and p = |projection| = sqrt(1−c²). Write a
621    // point Q on the plane as Q = apex + e·n + s·e1 + t·e2 (e = d − n·apex,
622    // e2 = n×e1). The cone equation (w·a)² = cos²γ·(w·w) with k = cos²γ =
623    // sin²(half_angle) reduces to (no s·t cross term, since e1/e2 align with the
624    // conic axes):
625    //     (p²−k)·s² + 2ecp·s + e²(c²−k) = k·t²
626    // The s² coefficient A = p²−k = sin²θ − sin²(half_angle) sets the type:
627    // A < 0 → ellipse, A = 0 → parabola, A > 0 → hyperbola.
628    let c = normal.dot(axis);
629    let p2 = (1.0 - c * c).max(0.0);
630    let p = p2.sqrt();
631    let k = half_angle.sin().powi(2);
632    let a_coeff = p2 - k;
633
634    // Build the plane-aligned frame e1 (in-plane axis projection), e2 = n×e1.
635    let m = Vec3::new(
636        axis.x() - c * normal.x(),
637        axis.y() - c * normal.y(),
638        axis.z() - c * normal.z(),
639    );
640    let m_len = m.length();
641    if m_len < 1e-12 {
642        // Axis parallel to normal — handled by the perpendicular branch above;
643        // fall back to sampling for safety.
644        let chains = sample_plane_cone(cone, normal, d, reach)?;
645        return Ok(chains
646            .into_iter()
647            .map(ExactIntersectionCurve::Points)
648            .collect());
649    }
650    let e1 = m * (1.0 / m_len);
651    let e2 = normal.cross(e1);
652    let apex = cone.apex();
653    let e = d - dot_np(normal, apex);
654
655    // Ellipse → closed form. A = p²−k < 0 with a margin to keep the
656    // near-parabolic regime on the robust sampled path.
657    if a_coeff < -1e-9 {
658        let abs_a = -a_coeff; // = k − p² > 0
659        // Real-nappe guard: in the ellipse regime n·g(u) keeps constant sign(c),
660        // so v = e/(n·g) ≥ 0 only when e and c share a sign. When e·c < 0 the
661        // plane is offset to the far side of the apex from the cone's opening —
662        // the section lies entirely on the phantom nappe, so there is no real
663        // curve (RHS below is positive regardless of sign, so it can't catch this).
664        if e * c < 0.0 {
665            return Ok(vec![]);
666        }
667        // |A|(s − s_c)² + k·t² = RHS, with s_c = ecp/|A| and
668        // RHS = e²·k·(1−k)/|A| (always > 0 for a real ellipse).
669        let s_c = e * c * p / abs_a;
670        let rhs = e * e * k * (1.0 - k) / abs_a;
671        if rhs <= 0.0 {
672            return Ok(vec![]);
673        }
674        let semi_s = (rhs / abs_a).sqrt(); // extent along e1
675        let semi_t = (rhs / k).sqrt(); // extent along e2
676        if semi_s < 1e-12 || semi_t < 1e-12 {
677            return Ok(vec![]);
678        }
679        let center = apex + normal * e + e1 * s_c;
680        let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
681            (semi_s, semi_t, e1, e2)
682        } else {
683            (semi_t, semi_s, e2, e1)
684        };
685        let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
686        return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
687    }
688
689    // Parabola / hyperbola (and the near-parabolic ellipse margin): the section
690    // is unbounded, so emit bounded, branch-separated sample chains.
691    let chains = sample_plane_cone(cone, normal, d, reach)?;
692    Ok(chains
693        .into_iter()
694        .map(ExactIntersectionCurve::Points)
695        .collect())
696}
697
698/// The exact arc from `from` to `to` of a plane's parabola or hyperbola
699/// section of a cone, both ends on one branch of it, as a rational quadratic
700/// NURBS.
701///
702/// A hyperbola `x = a cosh φ, y = b sinh φ` (in the plane frame of
703/// `exact_plane_cone`) is cut into pieces of at most one unit of `φ`, each
704/// a conic Bézier: its middle point is where the end tangents meet and its
705/// middle weight is the cosh of half the piece's span. A parabola is one
706/// polynomial quadratic. `None` for an elliptic or circular section, a plane
707/// through the apex, or ends off one branch of the section.
708///
709/// # Errors
710///
711/// Returns an error if the plane normal is zero or the curve cannot be built.
712#[allow(clippy::many_single_char_names)]
713pub fn plane_cone_conic_arc(
714    cone: &ConicalSurface,
715    normal: Vec3,
716    d: f64,
717    from: Point3,
718    to: Point3,
719) -> Result<Option<NurbsCurve>, MathError> {
720    let len = normal.length();
721    if len < 1e-15 {
722        return Err(MathError::ZeroVector);
723    }
724    let (normal, d) = (normal * (1.0 / len), d / len);
725    let axis = cone.axis();
726    let c = normal.dot(axis);
727    let p2 = (1.0 - c * c).max(0.0);
728    let p = p2.sqrt();
729    let k = cone.half_angle().sin().powi(2);
730    let a_coeff = p2 - k;
731    let m = Vec3::new(
732        axis.x() - c * normal.x(),
733        axis.y() - c * normal.y(),
734        axis.z() - c * normal.z(),
735    );
736    let m_len = m.length();
737    if m_len < 1e-12 || a_coeff < -1e-9 {
738        return Ok(None);
739    }
740    let e1 = m * (1.0 / m_len);
741    let e2 = normal.cross(e1);
742    let apex = cone.apex();
743    let e = d - dot_np(normal, apex);
744    let origin = apex + normal * e;
745    let plane_st = |q: Point3| {
746        let w = q - origin;
747        (w.dot(e1), w.dot(e2))
748    };
749    let ((s0, t0), (s1, t1)) = (plane_st(from), plane_st(to));
750    let scale = s0.abs().max(t0.abs()).max(s1.abs()).max(t1.abs()).max(1.0);
751    if e.abs() < 1e-9 * scale || (from - to).length() <= 1e-9 * scale {
752        return Ok(None);
753    }
754    let point = |s: f64, t: f64| origin + e1 * s + e2 * t;
755    let on_curve = |q: Point3, r: Point3| (q - r).length() <= 1e-6 * scale;
756    let (control, weights) = if a_coeff.abs() <= 1e-9 {
757        // (p² − k) s² vanishes: 2ecp·s + e²(c² − k) = k·t², s = α t² + β.
758        let lin = 2.0 * e * c * p;
759        if lin.abs() < 1e-12 * scale {
760            return Ok(None);
761        }
762        let (alpha, beta) = (k / lin, -e * e * (c * c - k) / lin);
763        if !on_curve(point(alpha * t0 * t0 + beta, t0), from)
764            || !on_curve(point(alpha * t1 * t1 + beta, t1), to)
765        {
766            return Ok(None);
767        }
768        let mid = point(alpha * t0 * t1 + beta, 0.5 * (t0 + t1));
769        (vec![from, mid, to], vec![1.0; 3])
770    } else {
771        // A (s − s_c)² − k t² = R with R = e² k (1 − k) / A.
772        let s_c = -e * c * p / a_coeff;
773        let r = e * e * k * (1.0 - k) / a_coeff;
774        if r <= 0.0 {
775            return Ok(None);
776        }
777        let (a, b) = ((r / a_coeff).sqrt(), (r / k).sqrt());
778        let (x0, x1) = (s0 - s_c, s1 - s_c);
779        if x0 * x1 <= 0.0 {
780            return Ok(None);
781        }
782        let side = x0.signum();
783        let hyperbola = |phi: f64| point(s_c + side * a * phi.cosh(), b * phi.sinh());
784        let (phi0, phi1) = ((t0 / b).asinh(), (t1 / b).asinh());
785        if !on_curve(hyperbola(phi0), from) || !on_curve(hyperbola(phi1), to) {
786            return Ok(None);
787        }
788        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
789        let pieces = ((phi1 - phi0).abs().ceil() as usize).max(1);
790        let mut control = vec![from];
791        let mut weights = vec![1.0];
792        for i in 0..pieces {
793            #[allow(clippy::cast_precision_loss)]
794            let (fa, fb) = (i as f64 / pieces as f64, (i + 1) as f64 / pieces as f64);
795            let (pa, pb) = (phi0 + (phi1 - phi0) * fa, phi0 + (phi1 - phi0) * fb);
796            let (mid, half) = (0.5 * (pa + pb), 0.5 * (pb - pa));
797            let w = half.cosh();
798            control.push(point(s_c + side * a * mid.cosh() / w, b * mid.sinh() / w));
799            weights.push(w);
800            control.push(if i + 1 == pieces { to } else { hyperbola(pb) });
801            weights.push(1.0);
802        }
803        (control, weights)
804    };
805    let pieces = (control.len() - 1) / 2;
806    let mut knots = vec![0.0; 3];
807    for i in 1..pieces {
808        #[allow(clippy::cast_precision_loss)]
809        knots.extend([i as f64; 2]);
810    }
811    #[allow(clippy::cast_precision_loss)]
812    knots.extend([pieces as f64; 3]);
813    let curve = NurbsCurve::new(2, knots, control, weights)?;
814    // The closed forms drop terms that vanish only on the exact conic (a
815    // barely elliptic section read as a parabola), so the arc must meet the
816    // cone between its ends too: a point at radius ρ and height h off the
817    // apex lies |ρ sin α − |h| cos α| from it.
818    let (sin_a, cos_a) = cone.half_angle().sin_cos();
819    let off_cone = |q: Point3| {
820        let w = q - apex;
821        let h = w.dot(axis);
822        (w - axis * h)
823            .length()
824            .madd(sin_a, -(h.abs() * cos_a))
825            .abs()
826    };
827    for i in 0..pieces {
828        for f in [0.25, 0.5, 0.75] {
829            #[allow(clippy::cast_precision_loss)]
830            if off_cone(curve.evaluate(i as f64 + f)) > 1e-9 * scale {
831                return Ok(None);
832            }
833        }
834    }
835    Ok(Some(curve))
836}
837
838/// Reference to an analytic surface for intersection dispatch.
839#[derive(Clone, Copy)]
840pub enum AnalyticSurface<'a> {
841    /// Cylindrical surface reference.
842    Cylinder(&'a CylindricalSurface),
843    /// Conical surface reference.
844    Cone(&'a ConicalSurface),
845    /// Spherical surface reference.
846    Sphere(&'a SphericalSurface),
847    /// Toroidal surface reference.
848    Torus(&'a ToroidalSurface),
849}
850
851/// Compute `n . p` treating a `Point3` as a position vector.
852fn dot_np(n: Vec3, p: Point3) -> f64 {
853    n.dot(Vec3::new(p.x(), p.y(), p.z()))
854}
855
856/// Intersect a plane with an analytic surface.
857///
858/// The plane is defined by `dot(normal, p) = d`.
859///
860/// # Errors
861///
862/// Returns an error if the intersection computation fails.
863pub fn intersect_plane_analytic(
864    surface: AnalyticSurface<'_>,
865    normal: Vec3,
866    d: f64,
867) -> Result<Vec<IntersectionCurve>, MathError> {
868    match surface {
869        AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
870        AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
871        AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
872        AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
873    }
874}
875
876/// Sample points on the plane-analytic intersection without NURBS curve fitting.
877///
878/// Returns chains of ordered 3D sample points. Each chain is one connected
879/// component of the intersection curve. This is much faster than
880/// `intersect_plane_analytic` when only sample points are needed (e.g. for
881/// boolean intersection segment generation).
882///
883/// # Errors
884///
885/// Returns an error if the intersection computation fails.
886pub fn sample_plane_analytic(
887    surface: AnalyticSurface<'_>,
888    normal: Vec3,
889    d: f64,
890) -> Result<Vec<Vec<Point3>>, MathError> {
891    match surface {
892        AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
893        AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d, 0.0),
894        AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
895        AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
896    }
897}
898
899/// Sample the plane-cylinder intersection as ordered 3D points.
900#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
901fn sample_plane_cylinder(
902    cyl: &CylindricalSurface,
903    normal: Vec3,
904    d: f64,
905) -> Result<Vec<Vec<Point3>>, MathError> {
906    let n_samples = 64_usize;
907    let mut points = Vec::with_capacity(n_samples + 1);
908
909    for i in 0..=n_samples {
910        let u = TAU * (i as f64) / (n_samples as f64);
911        let base = cyl.evaluate(u, 0.0);
912        let n_dot_axis = normal.dot(cyl.axis());
913        let n_dot_base = dot_np(normal, base);
914
915        if n_dot_axis.abs() < 1e-12 {
916            if (n_dot_base - d).abs() < 1e-6 {
917                points.push(base);
918            }
919        } else {
920            let v = (d - n_dot_base) / n_dot_axis;
921            if v.abs() <= 100.0 {
922                points.push(cyl.evaluate(u, v));
923            }
924        }
925    }
926
927    if points.len() < 2 {
928        Ok(vec![])
929    } else {
930        Ok(vec![points])
931    }
932}
933
934/// Sample the plane-sphere intersection as ordered 3D points.
935#[allow(clippy::cast_precision_loss)]
936fn sample_plane_sphere(
937    sphere: &SphericalSurface,
938    normal: Vec3,
939    d: f64,
940) -> Result<Vec<Vec<Point3>>, MathError> {
941    let h = dot_np(normal, sphere.center()) - d;
942    let r = sphere.radius();
943
944    if h.abs() > r - 1e-10 {
945        return Ok(vec![]);
946    }
947
948    let circle_r = (r.madd(r, -(h * h))).sqrt();
949    let circle_center = Point3::new(
950        h.madd(-normal.x(), sphere.center().x()),
951        h.madd(-normal.y(), sphere.center().y()),
952        h.madd(-normal.z(), sphere.center().z()),
953    );
954
955    let basis = Frame3::from_normal(circle_center, normal)?;
956    let u_dir = basis.x;
957    let v_dir = basis.y;
958
959    let n_samples = 64_usize;
960    let mut points = Vec::with_capacity(n_samples + 1);
961
962    for i in 0..=n_samples {
963        let theta = TAU * (i as f64) / (n_samples as f64);
964        let (sin_t, cos_t) = theta.sin_cos();
965        points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
966    }
967
968    Ok(vec![points])
969}
970
971/// Sample the plane-cone intersection as ordered 3D points.
972///
973/// The cone is the single real nappe `v >= 0` of `P(u,v) = apex + v·g(u)`.
974/// Along each generator `g(u)` the plane `n·P = d` is linear in `v`, so
975/// `v = (d − n·apex) / (n·g(u))`. We keep only `v >= 0` (the phantom `v < 0`
976/// nappe is geometrically absent) and `v` below a finite bound (near an
977/// asymptote `n·g(u) → 0` so `v → ∞` — those points run off the surface and
978/// must be excluded). The angular samples that survive form one contiguous arc
979/// (ellipse) or two (parabola/hyperbola, one per branch); each contiguous run
980/// is returned as a separate ordered chain so the consumer never stitches two
981/// disjoint branches into one curve.
982#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
983fn sample_plane_cone(
984    cone: &ConicalSurface,
985    normal: Vec3,
986    d: f64,
987    reach: f64,
988) -> Result<Vec<Vec<Point3>>, MathError> {
989    let apex = cone.apex();
990    let n_dot_apex = dot_np(normal, apex);
991    let e = d - n_dot_apex;
992
993    // Per-generator solve: along g(u) the plane is linear in v, v = e / (n·g(u)).
994    // Sample u densely; keep only the real nappe (v >= 0) and skip near-asymptote
995    // generators (n·g(u) ≈ 0 → v → ∞).
996    let n_samples = 512_usize;
997    let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
998    let mut v_min = f64::INFINITY;
999    for i in 0..n_samples {
1000        let u = TAU * (i as f64) / (n_samples as f64);
1001        let g = cone.evaluate(u, 1.0) - apex;
1002        let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
1003        if n_dot_g.abs() < 1e-12 {
1004            vs.push(None);
1005            continue;
1006        }
1007        let v = e / n_dot_g;
1008        if v >= -1e-12 {
1009            let v = v.max(0.0);
1010            v_min = v_min.min(v);
1011            vs.push(Some(v));
1012        } else {
1013            vs.push(None);
1014        }
1015    }
1016
1017    if !v_min.is_finite() {
1018        return Ok(Vec::new());
1019    }
1020
1021    // Bound the arc around the conic vertex (closest approach to the apex, at
1022    // v_min). An ellipse is naturally bounded; a parabola/hyperbola is not, so
1023    // cap the cone radius at a generous multiple of the vertex radius. This is
1024    // scale-invariant and centred on where any finite cone face's overlap lies;
1025    // the downstream consumer trims the fitted curve to the actual face AABB, so
1026    // over-coverage is harmless. The floor handles a vertex at the apex (v_min≈0).
1027    // A caller that knows its faces asks for their reach: an open hyperbola
1028    // (a vertex close to the axis) crosses a rim far past eight vertex radii.
1029    let v_max = (8.0 * v_min).max(v_min + 4.0).max(reach);
1030
1031    // Per-sample v within the cap; the raw values stay in `vs` for the
1032    // boundary solve below.
1033    let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
1034
1035    let point_at = |u: f64, v: f64| -> Point3 {
1036        let g = cone.evaluate(u, 1.0) - apex;
1037        apex + g * v
1038    };
1039    #[allow(clippy::cast_precision_loss)]
1040    let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
1041    let n_dot_g_at = |u: f64| -> f64 {
1042        let g = cone.evaluate(u, 1.0) - apex;
1043        normal.dot(Vec3::new(g.x(), g.y(), g.z()))
1044    };
1045
1046    if kept.iter().all(Option::is_some) {
1047        // Closed loop (ellipse regime): emit all points and repeat the first.
1048        let mut pts: Vec<Point3> = kept
1049            .iter()
1050            .enumerate()
1051            .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
1052            .collect();
1053        if let Some(&first) = pts.first() {
1054            pts.push(first);
1055        }
1056        return Ok(vec![pts]);
1057    }
1058
1059    // A hyperbola/parabola tail diverges as 1/(n·g), so between the last kept
1060    // sample and its dropped neighbour v can leap far past `v_max` in one
1061    // uniform-u pitch — and any finite face window inside that leap is lost
1062    // (a taper cone grazed 0.05 by a prism plane lost its entire 0.5-tall
1063    // section to exactly this aliasing). Extend each run end to the exact
1064    // `v_max` boundary: bisect u for `n·g(u) = e/v_max` inside the dropped
1065    // pitch (n·g is monotone there — its extrema sit at the conic vertex,
1066    // far from any asymptote), then fill the tail with uniform-u samples.
1067    let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
1068        let Some(v_end) = kept[i_end] else {
1069            return Vec::new();
1070        };
1071        let u_end = u_of(i_end);
1072        #[allow(clippy::cast_precision_loss)]
1073        let pitch = TAU / (n_samples as f64);
1074        let u_next = if forward {
1075            u_end + pitch
1076        } else {
1077            u_end - pitch
1078        };
1079        let target = e / v_max;
1080        let h_end = n_dot_g_at(u_end) - target;
1081        let h_next = n_dot_g_at(u_next) - target;
1082        if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
1083            return Vec::new();
1084        }
1085        let (mut lo, mut hi) = (u_end, u_next);
1086        for _ in 0..60 {
1087            let mid = f64::midpoint(lo, hi);
1088            if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
1089                lo = mid;
1090            } else {
1091                hi = mid;
1092            }
1093        }
1094        let u_star = f64::midpoint(lo, hi);
1095        let tail_n = 8_usize;
1096        (1..=tail_n)
1097            .filter_map(|k| {
1098                #[allow(clippy::cast_precision_loss)]
1099                let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
1100                let ng = n_dot_g_at(u);
1101                if ng.abs() < 1e-12 {
1102                    return None;
1103                }
1104                let v = e / ng;
1105                (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
1106            })
1107            .collect()
1108    };
1109
1110    // Split into contiguous runs of kept samples, treating the array as
1111    // circular (rotate past a gap) so a branch straddling u=0 stays whole.
1112    let gap = kept.iter().position(Option::is_none).unwrap_or(0);
1113    let mut chains: Vec<Vec<Point3>> = Vec::new();
1114    let mut run: Vec<usize> = Vec::new();
1115    let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
1116        if run.len() >= 2 {
1117            let first = run[0];
1118            let last = run[run.len() - 1];
1119            let mut pts: Vec<Point3> = tail(first, false, &kept);
1120            pts.reverse();
1121            pts.extend(
1122                run.iter()
1123                    .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
1124            );
1125            pts.extend(tail(last, true, &kept));
1126            chains.push(pts);
1127        }
1128        run.clear();
1129    };
1130    for k in 0..n_samples {
1131        let idx = (gap + k) % n_samples;
1132        if kept[idx].is_some() {
1133            run.push(idx);
1134        } else {
1135            flush(&mut run, &mut chains);
1136        }
1137    }
1138    flush(&mut run, &mut chains);
1139    Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
1140}
1141
1142/// Sample the plane-torus intersection as ordered 3D points.
1143///
1144/// Uses the same closed-form loops as `intersect_plane_torus`
1145/// but skips NURBS curve fitting (the callers here only need the points).
1146#[allow(clippy::unnecessary_wraps)] // sibling match-arms and `?` callers need `Result`
1147fn sample_plane_torus(
1148    torus: &ToroidalSurface,
1149    normal: Vec3,
1150    d: f64,
1151) -> Result<Vec<Vec<Point3>>, MathError> {
1152    Ok(plane_torus_loops(torus, normal, d, 128)
1153        .into_iter()
1154        .map(|run| run.into_iter().map(|p| p.point).collect())
1155        .collect())
1156}
1157
1158/// Intersect a plane with a cylindrical surface.
1159///
1160/// For each `u` in `[0, 2pi)`, the cylinder point is linear in `v`,
1161/// so the plane equation `dot(normal, P(u,v)) = d` is linear in `v`
1162/// and can be solved directly.
1163///
1164/// # Errors
1165///
1166/// Returns an error if curve fitting fails.
1167#[allow(clippy::cast_precision_loss)]
1168pub fn intersect_plane_cylinder(
1169    cyl: &CylindricalSurface,
1170    normal: Vec3,
1171    d: f64,
1172) -> Result<Vec<IntersectionCurve>, MathError> {
1173    let n_samples = 64_usize;
1174    let mut points_3d = Vec::new();
1175    let mut ipoints = Vec::new();
1176
1177    for i in 0..=n_samples {
1178        let u = TAU * (i as f64) / (n_samples as f64);
1179        // P(u, v) = origin + r*(cos(u)*x + sin(u)*y) + v*axis
1180        // dot(normal, P) = d  =>  dot(normal, base(u)) + v * dot(normal, axis) = d
1181        let base = cyl.evaluate(u, 0.0);
1182        let n_dot_axis = normal.dot(cyl.axis());
1183        let n_dot_base = dot_np(normal, base);
1184
1185        if n_dot_axis.abs() < 1e-12 {
1186            // Plane parallel to axis -- check if base is on plane.
1187            if (n_dot_base - d).abs() < 1e-6 {
1188                let pt = base;
1189                points_3d.push(pt);
1190                ipoints.push(IntersectionPoint {
1191                    point: pt,
1192                    param1: (u, 0.0),
1193                    param2: (0.0, 0.0),
1194                });
1195            }
1196        } else {
1197            let v = (d - n_dot_base) / n_dot_axis;
1198            // Only keep points within a reasonable v range.
1199            if v.abs() <= 100.0 {
1200                let pt = cyl.evaluate(u, v);
1201                points_3d.push(pt);
1202                ipoints.push(IntersectionPoint {
1203                    point: pt,
1204                    param1: (u, v),
1205                    param2: (0.0, 0.0),
1206                });
1207            }
1208        }
1209    }
1210
1211    build_curves_from_points(&points_3d, ipoints)
1212}
1213
1214/// Intersect a plane with a spherical surface.
1215///
1216/// The intersection of a plane with a sphere is a circle (or empty/point).
1217/// Computes the circle center, radius, and samples points on it.
1218///
1219/// # Errors
1220///
1221/// Returns an error if curve fitting fails.
1222#[allow(clippy::cast_precision_loss)]
1223pub fn intersect_plane_sphere(
1224    sphere: &SphericalSurface,
1225    normal: Vec3,
1226    d: f64,
1227) -> Result<Vec<IntersectionCurve>, MathError> {
1228    let h = dot_np(normal, sphere.center()) - d;
1229    let r = sphere.radius();
1230
1231    // No intersection if plane is too far from center.
1232    if h.abs() > r - 1e-10 {
1233        return Ok(vec![]);
1234    }
1235
1236    let circle_r = (r.madd(r, -(h * h))).sqrt();
1237    let circle_center = Point3::new(
1238        h.madd(-normal.x(), sphere.center().x()),
1239        h.madd(-normal.y(), sphere.center().y()),
1240        h.madd(-normal.z(), sphere.center().z()),
1241    );
1242
1243    // Build a local frame on the plane.
1244    let basis = Frame3::from_normal(circle_center, normal)?;
1245    let u_dir = basis.x;
1246    let v_dir = basis.y;
1247
1248    let n_samples = 64_usize;
1249    let mut points_3d = Vec::new();
1250    let mut ipoints = Vec::new();
1251
1252    for i in 0..=n_samples {
1253        let theta = TAU * (i as f64) / (n_samples as f64);
1254        let (sin_t, cos_t) = theta.sin_cos();
1255        let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
1256        points_3d.push(pt);
1257        ipoints.push(IntersectionPoint {
1258            point: pt,
1259            param1: (theta, 0.0),
1260            param2: (0.0, 0.0),
1261        });
1262    }
1263
1264    build_curves_from_points(&points_3d, ipoints)
1265}
1266
1267/// Intersect a plane with a conical surface.
1268///
1269/// Like a cylinder, the cone is linear along each generatrix, so the plane
1270/// equation is linear in `v` for each fixed `u`.
1271///
1272/// # Errors
1273///
1274/// Returns an error if curve fitting fails.
1275#[allow(clippy::cast_precision_loss)]
1276pub fn intersect_plane_cone(
1277    cone: &ConicalSurface,
1278    normal: Vec3,
1279    d: f64,
1280) -> Result<Vec<IntersectionCurve>, MathError> {
1281    let n_samples = 64_usize;
1282    let mut points_3d = Vec::new();
1283    let mut ipoints = Vec::new();
1284
1285    for i in 0..n_samples {
1286        let u = TAU * (i as f64) / (n_samples as f64);
1287        // P(u, v) = apex + v * dir(u)
1288        // dot(normal, apex) + v * dot(normal, dir(u)) = d
1289        let apex = cone.apex();
1290        let n_dot_apex = dot_np(normal, apex);
1291        // dir(u) = P(u,1) - apex
1292        let p1 = cone.evaluate(u, 1.0);
1293        let dir = p1 - apex;
1294        let n_dot_dir = normal.dot(dir);
1295
1296        if n_dot_dir.abs() < 1e-12 {
1297            continue;
1298        }
1299
1300        let v = (d - n_dot_apex) / n_dot_dir;
1301        // Allow negative v — the cone surface extends in both directions from the apex.
1302        if v.abs() > 1e-10 && v.abs() < 100.0 {
1303            let pt = cone.evaluate(u, v);
1304            points_3d.push(pt);
1305            ipoints.push(IntersectionPoint {
1306                point: pt,
1307                param1: (u, v),
1308                param2: (0.0, 0.0),
1309            });
1310        }
1311    }
1312
1313    build_curves_from_points(&points_3d, ipoints)
1314}
1315
1316/// Intersect a plane with a toroidal surface.
1317///
1318/// The section is a degree-4 curve, but for each `v` the `u` values solve in
1319/// closed form (see `plane_torus_loops`), so it is sampled by a v-scan
1320/// and each loop is fitted to a NURBS curve.
1321///
1322/// # Errors
1323///
1324/// Never returns an error today (curve-fit failures drop the affected loop);
1325/// the `Result` is kept for signature parity with the other plane-analytic
1326/// intersectors.
1327#[allow(clippy::unnecessary_wraps)]
1328pub fn intersect_plane_torus(
1329    torus: &ToroidalSurface,
1330    normal: Vec3,
1331    d: f64,
1332) -> Result<Vec<IntersectionCurve>, MathError> {
1333    // The section satisfies a per-v closed form (see `plane_torus_loops`),
1334    // so scan v and solve u directly instead of a 2D sign-change grid with
1335    // Newton refinement: O(n) rather than O(n²), and every point is exact.
1336    let mut curves = Vec::new();
1337    for ipts in plane_torus_loops(torus, normal, d, 128) {
1338        let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
1339        if let Ok(curve) = fit_plane_torus_section(torus, normal, d, &pts) {
1340            curves.push(IntersectionCurve {
1341                curve,
1342                points: ipts,
1343            });
1344        }
1345    }
1346
1347    Ok(curves)
1348}
1349
1350/// The point of a plane's section of a torus that `p`, a point near it,
1351/// moves to across both surfaces.
1352///
1353/// Newton steps take the point onto the plane and onto the tube nearer `p`,
1354/// both to rounding. Each step is the shortest move that clears both
1355/// first-order distances, so the point moves across the section and not
1356/// along it.
1357///
1358/// `None` where the two surfaces meet at a tangent (their normals within
1359/// about 1e-6 of parallel), where `p` lies on the torus's axis or a tube's
1360/// centre circle, or where the steps do not settle.
1361#[must_use]
1362pub fn plane_torus_section_point(
1363    torus: &ToroidalSurface,
1364    normal: Vec3,
1365    d: f64,
1366    p: Point3,
1367) -> Option<Point3> {
1368    plane_torus_newton(torus, normal, d, p, 0.0)
1369}
1370
1371/// [`plane_torus_section_point`], but where the steps so far have moved `p`
1372/// by less than `short`, the point they reach: the section's point lies
1373/// within about the square of the last step times the section's curvature
1374/// of it.
1375fn plane_torus_newton(
1376    torus: &ToroidalSurface,
1377    normal: Vec3,
1378    d: f64,
1379    p: Point3,
1380    short: f64,
1381) -> Option<Point3> {
1382    let scale = normal.length();
1383    if scale <= 0.0 || !scale.is_finite() {
1384        return None;
1385    }
1386    let n = normal * (1.0 / scale);
1387    let d = d / scale;
1388    let (axis, centre) = (torus.z_axis(), torus.center());
1389    let (big, small) = (torus.major_radius(), torus.minor_radius());
1390    let radial_of = |x: Point3| {
1391        let w = x - centre;
1392        w - axis * axis.dot(w)
1393    };
1394    // The tube is held to the side `p` starts on: a spindle torus's sheet
1395    // across the axis belongs to the far tube circle.
1396    let side = {
1397        let radial = radial_of(p);
1398        let rho = radial.length();
1399        let h = axis.dot(p - centre);
1400        if (rho + big).hypot(h) - small < ((rho - big).hypot(h) - small).abs() {
1401            -1.0
1402        } else {
1403            1.0
1404        }
1405    };
1406    // Each surface's distance from `x` and the torus's normal there.
1407    let residuals = |x: Point3| -> Option<(f64, f64, Vec3)> {
1408        let radial = radial_of(x);
1409        let rho = radial.length();
1410        if rho <= 0.0 {
1411            return None;
1412        }
1413        let to = (x - centre) - radial * (side * big / rho);
1414        let reach = to.length();
1415        if reach <= 0.0 {
1416            return None;
1417        }
1418        Some((dot_np(n, x) - d, reach - small, to * (1.0 / reach)))
1419    };
1420    let rounding = 16.0 * f64::EPSILON * (big + small + (p - centre).length());
1421    let mut x = p;
1422    for _ in 0..16 {
1423        let (f_plane, f_torus, g) = residuals(x)?;
1424        if f_plane.abs() <= rounding && f_torus.abs() <= rounding {
1425            return Some(x);
1426        }
1427        let c = n.dot(g);
1428        let det = c.madd(-c, 1.0);
1429        if det < 1e-12 {
1430            return None;
1431        }
1432        let along_n = c.madd(-f_torus, f_plane) / det;
1433        let along_g = c.madd(-f_plane, f_torus) / det;
1434        x = x - n * along_n - g * along_g;
1435        if (x - p).length() < short {
1436            return Some(x);
1437        }
1438    }
1439    let (f_plane, f_torus, _) = residuals(x)?;
1440    (f_plane.abs() <= 1e3 * rounding && f_torus.abs() <= 1e3 * rounding).then_some(x)
1441}
1442
1443/// How far a fitted plane x torus section may stray from the true section
1444/// between its points, as a fraction of the torus's outer radius.
1445const PLANE_TORUS_FIT: f64 = 1e-9;
1446
1447/// The most points a fitted plane x torus section takes.
1448const PLANE_TORUS_FIT_POINTS: usize = 4096;
1449
1450/// A cubic through `points`, points of a plane's section of a torus in order
1451/// along it, and through more points of the section where it needs them.
1452///
1453/// The cubic meets the section only at its points, and between two of them
1454/// it strays by about the fourth power of their spacing, which a tight turn
1455/// of the section makes large: 25 points along the section of a wall 0.4
1456/// outside the inner equator of a torus of radii 4 and 1.5 leave the cubic
1457/// 8e-5 off it. Each pass checks the cubic halfway between each two points:
1458/// where that point moves onto the section, within half the points'
1459/// spacing, by more than 1e-9 of the torus's outer radius, the section's
1460/// point there goes between them. Where it does not move onto the section
1461/// (on the axis, or where the plane all but touches the torus), it must lie
1462/// on both the plane and the torus within that bound itself.
1463///
1464/// # Errors
1465///
1466/// Returns an error if the interpolation fails (fewer than 2 points, or
1467/// repeated points), if a middle neither moves onto the section nor lies
1468/// on both surfaces, or if the cubic needs more than 4096 points.
1469pub fn fit_plane_torus_section(
1470    torus: &ToroidalSurface,
1471    normal: Vec3,
1472    d: f64,
1473    points: &[Point3],
1474) -> Result<NurbsCurve, MathError> {
1475    let tol = PLANE_TORUS_FIT.madd(
1476        torus.major_radius() + torus.minor_radius(),
1477        64.0 * f64::EPSILON * (torus.center() - Point3::new(0.0, 0.0, 0.0)).length(),
1478    );
1479    // How far a point lies from the plane, or from the torus, whichever is
1480    // farther.
1481    let strays = |p: Point3| {
1482        let w = p - torus.center();
1483        let height = torus.z_axis().dot(w);
1484        let rho = (w - torus.z_axis() * height).length();
1485        let off_torus = [1.0, -1.0]
1486            .into_iter()
1487            .map(|side: f64| {
1488                (side.madd(-torus.major_radius(), rho).hypot(height) - torus.minor_radius()).abs()
1489            })
1490            .fold(f64::INFINITY, f64::min);
1491        ((dot_np(normal, p) - d) / normal.length())
1492            .abs()
1493            .max(off_torus)
1494    };
1495    let mut pts = points.to_vec();
1496    let mut passes = 0;
1497    loop {
1498        passes += 1;
1499        let curve = interpolate(&pts, 3.min(pts.len().saturating_sub(1)))?;
1500        let params = crate::nurbs::fitting::chord_length_params(&pts);
1501        let mut finer = Vec::with_capacity(2 * pts.len());
1502        let mut added = false;
1503        for (i, pair) in pts.windows(2).enumerate() {
1504            finer.push(pair[0]);
1505            let gap = (pair[1] - pair[0]).length();
1506            let middle = curve.evaluate(f64::midpoint(params[i], params[i + 1]));
1507            // A point of the section half a spacing or more away lies on
1508            // another stretch of it (a thin tube's other loop).
1509            let on = plane_torus_newton(torus, normal, d, middle, 0.25 * tol)
1510                .filter(|on| (*on - middle).length() < 0.5 * gap);
1511            match on {
1512                Some(on) if (on - middle).length() <= tol => {}
1513                Some(on) => {
1514                    finer.push(on);
1515                    added = true;
1516                }
1517                None if strays(middle) <= tol => {}
1518                None => return Err(MathError::ConvergenceFailure { iterations: passes }),
1519            }
1520        }
1521        if !added {
1522            return Ok(curve);
1523        }
1524        if let Some(&last) = pts.last() {
1525            finer.push(last);
1526        }
1527        if finer.len() > PLANE_TORUS_FIT_POINTS {
1528            return Err(MathError::ConvergenceFailure { iterations: passes });
1529        }
1530        pts = finer;
1531    }
1532}
1533
1534/// The fewest and most steps along each branch of a loop a plane cuts from
1535/// a torus between its two turns.
1536const PLANE_TORUS_LOOP_SAMPLES: (f64, f64) = (24.0, 512.0);
1537
1538/// The loops a plane cuts from a torus, each as points on the torus in
1539/// order, closed by repeating its first point.
1540///
1541/// In the torus's own frame let `a = n·X`, `b = n·Y`, `c = n·Z`,
1542/// `s = hypot(a, b)`, `phi = atan2(b, a)`. Substituting the torus
1543/// parameterization into `n·P = d` gives
1544///   `(R + r·cos v)·s·cos(u − phi) + r·c·sin v = d − n·center`,
1545/// so at each tube angle `v` where `|rhs(v)| <= 1`, with
1546/// `rhs(v) = (d − n·center − r·c·sin v) / (s·(R + r·cos v))`, the section's
1547/// two branches are `u = phi ± acos(rhs(v))`. Each run of `v` where the
1548/// section exists is one loop: out along one branch to where the run ends
1549/// and the branches meet, and back along the other. A section present at
1550/// every `v` is two loops winding the tube, one per branch. Every point
1551/// comes from the closed form, so the loops need no chaining.
1552///
1553/// Where the branches touch inside a run (a plane tangent to the tube's
1554/// inner side, at a saddle) the section crosses itself: each branch passes
1555/// through that node, and each loop there starts and ends on it.
1556///
1557/// When `s ≈ 0` the plane is perpendicular to the axis and the section is up
1558/// to two full circles at the `v` values solving `r·c·sin v = d − n·center`,
1559/// sampled by scanning `u`.
1560#[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
1561fn plane_torus_loops(
1562    torus: &ToroidalSurface,
1563    normal: Vec3,
1564    d: f64,
1565    n_v: usize,
1566) -> Vec<Vec<IntersectionPoint>> {
1567    let big_r = torus.major_radius();
1568    let small_r = torus.minor_radius();
1569    let a = normal.dot(torus.x_axis());
1570    let b = normal.dot(torus.y_axis());
1571    let c = normal.dot(torus.z_axis());
1572    let s = a.hypot(b);
1573    let phi = b.atan2(a);
1574    let d_local = d - dot_np(normal, torus.center());
1575    let point = |u: f64, v: f64| IntersectionPoint {
1576        point: torus.evaluate(u, v),
1577        param1: (u, v.rem_euclid(TAU)),
1578        param2: (0.0, 0.0),
1579    };
1580    let closed = |mut run: Vec<IntersectionPoint>| {
1581        run.push(run[0]);
1582        run
1583    };
1584
1585    // Plane perpendicular to the axis: the section is up to two full circles.
1586    if s < 1e-12 {
1587        if c.abs() < 1e-12 {
1588            return Vec::new();
1589        }
1590        let sin_v = d_local / (small_r * c);
1591        if sin_v.abs() > 1.0 + 1e-9 {
1592            return Vec::new();
1593        }
1594        let v0 = sin_v.clamp(-1.0, 1.0).asin();
1595        let v1 = std::f64::consts::PI - v0;
1596        let mut vs = vec![v0];
1597        // Skip the mirror circle when the plane is tangent: at the tube's top
1598        // v0 == v1, and at its bottom they differ by a whole turn.
1599        let apart = (v1 - v0).rem_euclid(TAU);
1600        if apart.min(TAU - apart) > 1e-9 {
1601            vs.push(v1);
1602        }
1603        return vs
1604            .into_iter()
1605            .map(|v| {
1606                closed(
1607                    (0..n_v)
1608                        .map(|i| point(TAU * (i as f64) / (n_v as f64), v))
1609                        .collect(),
1610                )
1611            })
1612            .collect();
1613    }
1614
1615    // R + r·cos v > 0 on a ring torus.
1616    let length = normal.length();
1617    TorusSection {
1618        torus,
1619        phi,
1620        num: [d_local, 0.0, -small_r * c],
1621        den: [s * big_r, s * small_r],
1622        clearance: |p: Point3| (dot_np(normal, p) - d) / length,
1623        slack: 64.0 * f64::EPSILON * (big_r + small_r + d_local.abs() / length),
1624    }
1625    .loops(n_v, PLANE_TORUS_LOOP_SAMPLES)
1626}
1627
1628/// A surface's section of a ring torus that holds, at each tube angle `v`,
1629/// the torus's points with `cos(u − phi) = rhs(v)`: the two branches
1630/// `u = phi ± acos(rhs(v))` wherever `|rhs(v)| <= 1`, as for a plane
1631/// ([`plane_torus_loops`]) or a sphere off the axis ([`sphere_torus_section`]).
1632/// For both, `rhs(v) = (n0 + n1·cos v + n2·sin v) / (d0 + d1·cos v)` with a
1633/// positive denominator, so `rhs` meets `±1` where a sum of `cos v` and
1634/// `sin v` vanishes, at up to four tube angles in closed form.
1635struct TorusSection<'a, F> {
1636    torus: &'a ToroidalSurface,
1637    phi: f64,
1638    /// `n0`, `n1`, `n2`.
1639    num: [f64; 3],
1640    /// `d0`, `d1`.
1641    den: [f64; 2],
1642    /// A point's signed distance from the surface cutting the torus.
1643    clearance: F,
1644    /// The distance rounding can make or hide between the two surfaces.
1645    slack: f64,
1646}
1647
1648impl<F: Fn(Point3) -> f64> TorusSection<'_, F> {
1649    fn rhs(&self, v: f64) -> f64 {
1650        let [n0, n1, n2] = self.num;
1651        let [d0, d1] = self.den;
1652        let (sin, cos) = v.sin_cos();
1653        n2.madd(sin, n1.madd(cos, n0)) / d1.madd(cos, d0)
1654    }
1655
1656    fn point(&self, u: f64, v: f64) -> IntersectionPoint {
1657        IntersectionPoint {
1658            point: self.torus.evaluate(u, v),
1659            param1: (u.rem_euclid(TAU), v.rem_euclid(TAU)),
1660            param2: (0.0, 0.0),
1661        }
1662    }
1663
1664    fn branch(&self, v: f64, sign: f64) -> IntersectionPoint {
1665        self.point(sign.madd(self.rhs(v).clamp(-1.0, 1.0).acos(), self.phi), v)
1666    }
1667
1668    /// Where both branches meet at `v`: `acos` is 0 or π there.
1669    fn node(&self, v: f64) -> IntersectionPoint {
1670        let u = if self.rhs(v) >= 0.0 {
1671            self.phi
1672        } else {
1673            self.phi + std::f64::consts::PI
1674        };
1675        self.point(u, v)
1676    }
1677
1678    /// How far the surface lies from the point where the branches would meet
1679    /// at `v`: zero where the section's run ends, and where it only touches.
1680    fn depth(&self, v: f64) -> f64 {
1681        (self.clearance)(self.node(v).point).abs()
1682    }
1683
1684    /// The tube angles in `[0, 2π)` where `rhs` is `±1`, in order. Each solves
1685    /// `α + β·cos v + γ·sin v = 0`, so `cos(v − atan2(γ, β)) = −α / hypot(β, γ)`;
1686    /// a ratio past 1 by rounding alone is a double root, a touch.
1687    fn crossings(&self) -> Vec<f64> {
1688        let [n0, n1, n2] = self.num;
1689        let [d0, d1] = self.den;
1690        let mut roots = Vec::with_capacity(4);
1691        for c in [1.0_f64, -1.0] {
1692            let (alpha, beta, gamma) = (c.madd(-d0, n0), c.madd(-d1, n1), n2);
1693            let m = beta.hypot(gamma);
1694            let ratio = -alpha / m;
1695            if !ratio.is_finite() || ratio.abs() > 1.0 + 1e-12 {
1696                continue;
1697            }
1698            let theta = gamma.atan2(beta);
1699            let delta = ratio.clamp(-1.0, 1.0).acos();
1700            roots.push((theta - delta).rem_euclid(TAU));
1701            roots.push((theta + delta).rem_euclid(TAU));
1702        }
1703        roots.sort_by(f64::total_cmp);
1704        roots
1705    }
1706
1707    /// Each run of `v` where the section lies, from `lo` to `hi` unwrapped,
1708    /// with the node inside it where its branches touch, and whether it
1709    /// takes the whole turn. Between two crossings `|rhs|` stays on one side
1710    /// of 1; a stretch the surface clears or cuts by no more than `slack` is
1711    /// a touch, a node inside a run and nothing between runs.
1712    fn runs(&self) -> Vec<(f64, f64, Option<f64>, bool)> {
1713        let roots = self.crossings();
1714        let n = roots.len();
1715        if n == 0 {
1716            let whole = self.rhs(0.0).abs() <= 1.0 && self.depth(0.0) > self.slack;
1717            return if whole {
1718                vec![(0.0, TAU, None, true)]
1719            } else {
1720                Vec::new()
1721            };
1722        }
1723        let arcs: Vec<(f64, f64)> = (0..n)
1724            .map(|i| {
1725                (
1726                    roots[i],
1727                    if i + 1 < n {
1728                        roots[i + 1]
1729                    } else {
1730                        roots[0] + TAU
1731                    },
1732                )
1733            })
1734            .collect();
1735        let middle = |i: usize| f64::midpoint(arcs[i].0, arcs[i].1);
1736        let inside: Vec<bool> = (0..n).map(|i| self.rhs(middle(i)).abs() <= 1.0).collect();
1737        let shallow: Vec<bool> = (0..n)
1738            .map(|i| self.depth(middle(i)) <= self.slack)
1739            .collect();
1740        let deep_beside = |i: usize, back: bool| {
1741            (1..n)
1742                .map(|j| if back { (i + n - j) % n } else { (i + j) % n })
1743                .find(|&j| !shallow[j])
1744        };
1745        let kept: Vec<bool> = (0..n)
1746            .map(|i| {
1747                if !shallow[i] {
1748                    return inside[i];
1749                }
1750                matches!(
1751                    (deep_beside(i, true), deep_beside(i, false)),
1752                    (Some(a), Some(b)) if inside[a] && inside[b]
1753                )
1754            })
1755            .collect();
1756        let node_in = |from: usize, len: usize| {
1757            (0..len).find_map(|j| {
1758                let i = (from + j) % n;
1759                let wraps = if from + j >= n { TAU } else { 0.0 };
1760                shallow[i].then(|| middle(i) + wraps)
1761            })
1762        };
1763        let Some(first) = (0..n).find(|&i| kept[i] && !kept[(i + n - 1) % n]) else {
1764            return if kept.iter().all(|&k| k) {
1765                let node = node_in(0, n);
1766                let lo = node.unwrap_or(roots[0]);
1767                vec![(lo, lo + TAU, node, true)]
1768            } else {
1769                Vec::new()
1770            };
1771        };
1772        let mut runs = Vec::new();
1773        let mut j = 0;
1774        while j < n {
1775            let i = (first + j) % n;
1776            if !kept[i] {
1777                j += 1;
1778                continue;
1779            }
1780            let len = (0..n - j).take_while(|&k| kept[(i + k) % n]).count();
1781            let last = i + len - 1;
1782            let hi = arcs[last % n].1 + if last >= n { TAU } else { 0.0 };
1783            runs.push((arcs[i].0, hi, node_in(i, len), false));
1784            j += len;
1785        }
1786        runs
1787    }
1788
1789    /// Each run of the section as one loop, out along one branch to where
1790    /// the run ends and back along the other, closed by repeating its first
1791    /// point; a run taking the whole turn is two loops winding the tube.
1792    /// Where the branches touch inside a run the section crosses itself:
1793    /// each branch passes through that node, and each loop there starts and
1794    /// ends on it.
1795    #[allow(
1796        clippy::cast_precision_loss,
1797        clippy::cast_possible_truncation,
1798        clippy::cast_sign_loss
1799    )]
1800    fn loops(&self, n_v: usize, (fewest, most): (f64, f64)) -> Vec<Vec<IntersectionPoint>> {
1801        let closed = |mut run: Vec<IntersectionPoint>| {
1802            run.push(run[0]);
1803            run
1804        };
1805        let step = TAU / (n_v as f64);
1806        let mut loops = Vec::new();
1807        for (t_lo, t_hi, at_node, whole) in self.runs() {
1808            if whole {
1809                for sign in [1.0, -1.0] {
1810                    loops.push(closed(match at_node {
1811                        Some(v_node) => std::iter::once(self.node(v_node))
1812                            .chain(
1813                                (1..n_v).map(|i| self.branch((i as f64).madd(step, v_node), sign)),
1814                            )
1815                            .collect(),
1816                        None => (0..n_v)
1817                            .map(|i| self.branch((i as f64 + 0.5).madd(step, t_lo), sign))
1818                            .collect(),
1819                    }));
1820                }
1821                continue;
1822            }
1823            // `u` moves like the square root of the distance in `v` to a turn,
1824            // so the loop is sampled at `v = t_lo + (t_hi - t_lo) (1 - cos θ) / 2`
1825            // for even steps of `θ`: `v` then moves like `θ²` at each turn and
1826            // the points fall at near-even steps along the curve, turns
1827            // included. A loop that sweeps far round the axis on a short run of
1828            // `v` (a plane through the centre, tilted a little) takes a step per
1829            // half scan step of `u` its branches sweep.
1830            let len = ((t_hi - t_lo) / step).ceil();
1831            let probes = (len as usize).max(8);
1832            let (u_lo, u_hi) = (0..=probes)
1833                .map(|k| (t_hi - t_lo).madd(k as f64 / probes as f64, t_lo))
1834                .map(|v| self.rhs(v).clamp(-1.0, 1.0).acos())
1835                .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), u| {
1836                    (lo.min(u), hi.max(u))
1837                });
1838            let m = len
1839                .max((n_v as f64) * (u_hi - u_lo) / std::f64::consts::PI)
1840                .max(fewest)
1841                .min(most)
1842                .ceil();
1843            let steps = m as usize;
1844            if let Some(v_node) = at_node {
1845                // Out along one branch from the node to a turn and back along
1846                // the other, once each side of the node.
1847                for (from, to) in [(v_node, t_lo), (v_node, t_hi)] {
1848                    let along = |k: usize| {
1849                        let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1850                        (to - from).madd(f, from)
1851                    };
1852                    let mut pts = vec![self.node(v_node)];
1853                    pts.extend((1..=steps).map(|k| self.branch(along(k), 1.0)));
1854                    pts.extend((1..steps).rev().map(|k| self.branch(along(k), -1.0)));
1855                    loops.push(closed(pts));
1856                }
1857            } else {
1858                let at = |k: usize| {
1859                    let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1860                    (t_hi - t_lo).madd(f, t_lo)
1861                };
1862                let mut pts: Vec<IntersectionPoint> =
1863                    (0..=steps).map(|k| self.branch(at(k), 1.0)).collect();
1864                pts.extend((1..steps).rev().map(|k| self.branch(at(k), -1.0)));
1865                loops.push(closed(pts));
1866            }
1867        }
1868        loops
1869    }
1870
1871    /// The section's point halfway in `v` between two of its points, given
1872    /// by their `(u, v)` on the torus, on the branch nearer their middle `u`.
1873    fn between(&self, a: (f64, f64), b: (f64, f64)) -> IntersectionPoint {
1874        let half = |from: f64, to: f64| {
1875            let gap = (to - from + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
1876            0.5_f64.madd(gap, from)
1877        };
1878        let (u, v) = (half(a.0, b.0), half(a.1, b.1));
1879        let off = self.rhs(v).clamp(-1.0, 1.0).acos();
1880        let miss =
1881            |w: f64| ((w - u + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI).abs();
1882        let sign = if miss(self.phi + off) <= miss(self.phi - off) {
1883            1.0
1884        } else {
1885            -1.0
1886        };
1887        self.branch(v, sign)
1888    }
1889}
1890
1891/// The two sections of a plane that crosses every tube cross-section of a
1892/// torus twice (one parallel to the axis within `R − r` of it, or tilted a
1893/// little from that): both branches `u = phi ± acos(rhs(v))` of
1894/// [`plane_torus_loops`] are then defined for every `v`, so each closes
1895/// into a loop that winds once around the tube. Sampled at `n_v` steps from
1896/// `v = 0`, the outer equator, so every such loop on a torus starts on one
1897/// latitude, as the tube cross-sections of a plane through the axis do.
1898/// `None` when a branch lapses somewhere or the two come close to meeting.
1899#[allow(clippy::cast_precision_loss)]
1900fn plane_torus_winding_loops(
1901    torus: &ToroidalSurface,
1902    normal: Vec3,
1903    d: f64,
1904    n_v: usize,
1905) -> Option<Vec<Vec<Point3>>> {
1906    let big_r = torus.major_radius();
1907    let small_r = torus.minor_radius();
1908    let a = normal.dot(torus.x_axis());
1909    let b = normal.dot(torus.y_axis());
1910    let c = normal.dot(torus.z_axis());
1911    let s = a.hypot(b);
1912    if s < 1e-12 * normal.length() || small_r >= big_r {
1913        return None;
1914    }
1915    let phi = b.atan2(a);
1916    let d_local = d - dot_np(normal, torus.center());
1917    let rhs = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.madd(v.cos(), big_r));
1918    let dense = 8 * n_v;
1919    if (0..dense).any(|i| rhs(TAU * i as f64 / dense as f64).abs() > 1.0 - 1e-3) {
1920        return None;
1921    }
1922    let mut loops = [Vec::with_capacity(n_v + 1), Vec::with_capacity(n_v + 1)];
1923    for i in 0..n_v {
1924        let v = TAU * i as f64 / n_v as f64;
1925        let delta = rhs(v).acos();
1926        loops[0].push(torus.evaluate(phi + delta, v));
1927        loops[1].push(torus.evaluate(phi - delta, v));
1928    }
1929    Some(
1930        loops
1931            .into_iter()
1932            .map(|mut run| {
1933                run.push(run[0]);
1934                run
1935            })
1936            .collect(),
1937    )
1938}
1939
1940/// Real intersection parameters `t` of the line `origin + t·dir` with a torus.
1941///
1942/// A line meets a torus in up to four points (degree-4). Substituting the line
1943/// into the torus implicit `(a² + b² + c² + R² − r²)² = 4R²(a² + b²)` — where
1944/// `(a, b, c)` are the line point's coordinates in the torus frame — gives a
1945/// quartic in `t`, solved here for its real roots, each refined by Newton steps
1946/// on the tube it lies nearer (on a spindle torus, the near tube or the one
1947/// swung across the axis). `dir` need not be unit length; `t` is in units of
1948/// `dir`. Returns the roots sorted ascending (0–4 of them).
1949///
1950/// Used by the boolean section trimmer to find where a plane×torus oval exits a
1951/// box face's straight boundary edge — the exact crossing shared by the two
1952/// adjacent faces, which is what makes the notch watertight.
1953#[must_use]
1954pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1955    let c = torus.center();
1956    let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1957    let big_r = torus.major_radius();
1958    let small_r = torus.minor_radius();
1959
1960    // Line point in torus frame: a(t)=a0+a1 t, b(t)=b0+b1 t, c(t)=c0+c1 t.
1961    let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1962    let (a0, a1) = (xa.dot(o), xa.dot(dir));
1963    let (b0, b1) = (ya.dot(o), ya.dot(dir));
1964    let (c0, c1) = (za.dot(o), za.dot(dir));
1965
1966    // G(t) = a² + b² + c² + R² − r²  (quadratic: g2 t² + g1 t + g0)
1967    let g2 = a1.madd(a1, b1.madd(b1, c1 * c1));
1968    let g1 = 2.0 * a1.madd(a0, b1.madd(b0, c1 * c0));
1969    let g0 = a0.madd(
1970        a0,
1971        b0.madd(b0, c0.madd(c0, big_r.madd(big_r, -small_r * small_r))),
1972    );
1973
1974    // H(t) = 4R² (a² + b²)  (quadratic: h2 t² + h1 t + h0)
1975    let four_rr = 4.0 * big_r * big_r;
1976    let h2 = four_rr * a1.madd(a1, b1 * b1);
1977    let h1 = four_rr * (2.0 * a1.madd(a0, b1 * b0));
1978    let h0 = four_rr * a0.madd(a0, b0 * b0);
1979
1980    // Quartic G² − H = 0:  e4 t⁴ + e3 t³ + e2 t² + e1 t + e0.
1981    let e4 = g2 * g2;
1982    let e3 = 2.0 * g2 * g1;
1983    let e2 = g1.madd(g1, 2.0 * g2 * g0) - h2;
1984    let e1 = 2.0f64.madd(g1 * g0, -h1);
1985    let e0 = g0.madd(g0, -h0);
1986
1987    let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1988    // The quartic also holds a spindle torus's tube swung across the axis
1989    // (`G = -sqrt(H)`), whose roots pair up with the tube's own a few hundredths
1990    // apart when `R` is small: the solver leaves them loose, and polishing one
1991    // against the near tube carries it beside the other root. Each root is
1992    // polished on the tube it lies nearer.
1993    let tube = |t: f64, across: bool| -> f64 {
1994        let p = origin + dir * t;
1995        let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1996        let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1997        let centre = if across { -big_r } else { big_r };
1998        (a.hypot(b) - centre).hypot(cc) - small_r
1999    };
2000    for t in &mut roots {
2001        let across = big_r < small_r && tube(*t, true).abs() < tube(*t, false).abs();
2002        for _ in 0..8 {
2003            let eps = 1e-7;
2004            let f = tube(*t, across);
2005            let df = (tube(*t + eps, across) - tube(*t - eps, across)) / (2.0 * eps);
2006            if df.abs() <= 1e-12 {
2007                break;
2008            }
2009            let step = f / df;
2010            *t -= step;
2011            if step.abs() < 1e-14 * (1.0 + t.abs()) {
2012                break;
2013            }
2014        }
2015    }
2016    roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
2017    roots.dedup_by(|a, b| (*a - *b).abs() < 1e-9 * (1.0 + b.abs()));
2018    roots
2019}
2020
2021/// Real roots of `c4 x⁴ + c3 x³ + c2 x² + c1 x + c0` via Durand–Kerner, falling
2022/// back to the lower-degree solvers when the leading coefficients vanish.
2023fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
2024    // Degenerate leading coefficient → lower degree.
2025    if c4.abs() < 1e-14 {
2026        return real_roots_cubic(c3, c2, c1, c0);
2027    }
2028    // Monic: x⁴ + a x³ + b x² + c x + d.
2029    let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
2030    let eval = |z: Complex| -> Complex {
2031        // Horner.
2032        let mut acc = Complex::new(1.0, 0.0);
2033        acc = acc * z + Complex::new(a, 0.0);
2034        acc = acc * z + Complex::new(b, 0.0);
2035        acc = acc * z + Complex::new(c, 0.0);
2036        acc * z + Complex::new(d, 0.0)
2037    };
2038    // Durand–Kerner: four roots seeded on a circle, iterated to convergence.
2039    let seed = Complex::new(0.4, 0.9);
2040    let mut r = [
2041        Complex::new(1.0, 0.0),
2042        seed,
2043        seed * seed,
2044        seed * seed * seed,
2045    ];
2046    for _ in 0..100 {
2047        let mut max_step = 0.0_f64;
2048        for i in 0..4 {
2049            let mut denom = Complex::new(1.0, 0.0);
2050            for j in 0..4 {
2051                if i != j {
2052                    denom = denom * (r[i] - r[j]);
2053                }
2054            }
2055            if denom.norm() < 1e-300 {
2056                continue;
2057            }
2058            let step = eval(r[i]) / denom;
2059            r[i] = r[i] - step;
2060            max_step = max_step.max(step.norm());
2061        }
2062        if max_step < 1e-14 {
2063            break;
2064        }
2065    }
2066    // Keep roots with negligible imaginary part AND a small REAL-polynomial
2067    // residual — Durand–Kerner stops after a fixed iteration cap whether or not
2068    // it converged, so a non-converged iterate could otherwise be returned as a
2069    // spurious root. Evaluate the monic quartic at each candidate (real part) and
2070    // keep only |p(x)| below a magnitude-scaled tolerance; de-dup near-equal
2071    // roots (a double root converges to two near-identical iterates).
2072    let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
2073    let mut out: Vec<f64> = Vec::new();
2074    for z in r {
2075        if z.im.abs() >= 1e-7 {
2076            continue;
2077        }
2078        let x = z.re;
2079        // Residual tolerance scales with the polynomial's coefficient magnitude
2080        // and |x|^4 so large-coefficient quartics are not over-rejected.
2081        let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
2082        if p_real(x).abs() > 1e-6 * scale {
2083            continue;
2084        }
2085        if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
2086            continue;
2087        }
2088        out.push(x);
2089    }
2090    out
2091}
2092
2093/// Real roots of `a x³ + b x² + c x + d` (Cardano), with quadratic fallback.
2094fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
2095    if a.abs() < 1e-14 {
2096        return real_roots_quadratic(b, c, d);
2097    }
2098    // Depressed cubic t³ + p t + q via x = t − b/(3a).
2099    let (b, c, d) = (b / a, c / a, d / a);
2100    let p = c - b * b / 3.0;
2101    let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
2102    let shift = -b / 3.0;
2103    let disc = q * q / 4.0 + p * p * p / 27.0;
2104    if disc > 1e-14 {
2105        let sq = disc.sqrt();
2106        let u = (-q / 2.0 + sq).cbrt();
2107        let v = (-q / 2.0 - sq).cbrt();
2108        vec![u + v + shift]
2109    } else if disc < -1e-14 {
2110        // Three real roots (trigonometric).
2111        let m = 2.0 * (-p / 3.0).sqrt();
2112        let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
2113        (0..3)
2114            .map(|k| {
2115                m.madd(
2116                    (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
2117                    shift,
2118                )
2119            })
2120            .collect()
2121    } else {
2122        // Repeated roots.
2123        let u = (-q / 2.0).cbrt();
2124        vec![2.0 * u + shift, -u + shift]
2125    }
2126}
2127
2128/// Real roots of `a x² + b x + c`, with linear fallback.
2129fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
2130    if a.abs() < 1e-14 {
2131        if b.abs() < 1e-14 {
2132            return Vec::new();
2133        }
2134        return vec![-c / b];
2135    }
2136    let disc = b * b - 4.0 * a * c;
2137    if disc < 0.0 {
2138        Vec::new()
2139    } else {
2140        let sq = disc.sqrt();
2141        vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
2142    }
2143}
2144
2145/// Minimal complex number for the quartic root finder.
2146#[derive(Clone, Copy)]
2147struct Complex {
2148    re: f64,
2149    im: f64,
2150}
2151
2152impl Complex {
2153    const fn new(re: f64, im: f64) -> Self {
2154        Self { re, im }
2155    }
2156    fn norm(self) -> f64 {
2157        self.re.hypot(self.im)
2158    }
2159}
2160
2161impl std::ops::Add for Complex {
2162    type Output = Self;
2163    fn add(self, o: Self) -> Self {
2164        Self::new(self.re + o.re, self.im + o.im)
2165    }
2166}
2167
2168impl std::ops::Sub for Complex {
2169    type Output = Self;
2170    fn sub(self, o: Self) -> Self {
2171        Self::new(self.re - o.re, self.im - o.im)
2172    }
2173}
2174
2175impl std::ops::Mul for Complex {
2176    type Output = Self;
2177    fn mul(self, o: Self) -> Self {
2178        Self::new(
2179            self.re.madd(o.re, -(self.im * o.im)),
2180            self.re.madd(o.im, self.im * o.re),
2181        )
2182    }
2183}
2184
2185impl std::ops::Div for Complex {
2186    type Output = Self;
2187    fn div(self, o: Self) -> Self {
2188        let den = o.re.madd(o.re, o.im * o.im);
2189        Self::new(
2190            self.re.madd(o.re, self.im * o.im) / den,
2191            self.im.madd(o.re, -(self.re * o.im)) / den,
2192        )
2193    }
2194}
2195
2196/// Build intersection curves from a collection of ordered 3D points.
2197///
2198/// If there are enough points, fits a NURBS curve through them.
2199fn build_curves_from_points(
2200    points_3d: &[Point3],
2201    ipoints: Vec<IntersectionPoint>,
2202) -> Result<Vec<IntersectionCurve>, MathError> {
2203    if points_3d.len() < 2 {
2204        return Ok(vec![]);
2205    }
2206
2207    let degree = 3.min(points_3d.len() - 1);
2208    let curve = interpolate(points_3d, degree)?;
2209    Ok(vec![IntersectionCurve {
2210        curve,
2211        points: ipoints,
2212    }])
2213}
2214
2215// -- Analytic-Analytic Intersection -------------------------------------------
2216
2217/// Intersect two analytic surfaces using a general marching approach.
2218///
2219/// Seeds intersection points by sampling both parameter spaces on a grid,
2220/// then marches along the intersection curve using the cross product of
2221/// the two surface normals as the tangent direction.
2222///
2223/// # Errors
2224///
2225/// Returns an error if curve fitting fails.
2226#[allow(
2227    clippy::cast_precision_loss,
2228    clippy::too_many_lines,
2229    clippy::similar_names,
2230    clippy::unnecessary_wraps,
2231    clippy::type_complexity
2232)]
2233pub fn intersect_analytic_analytic(
2234    a: AnalyticSurface<'_>,
2235    b: AnalyticSurface<'_>,
2236    grid_res: usize,
2237) -> Result<Vec<IntersectionCurve>, MathError> {
2238    intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
2239}
2240
2241/// Intersect two analytic surfaces with optional v-range overrides.
2242///
2243/// When `v_range_hint_a` or `v_range_hint_b` is `Some((min, max))`, the
2244/// marching algorithm searches that v-range instead of the hardcoded default.
2245/// This is essential for cylinders and cones whose default v-range is small
2246/// (-1..1 or 0.01..2) but whose actual face may extend much further.
2247///
2248/// # Errors
2249///
2250/// Returns `MathError` if algebraic intersection fails or marching diverges.
2251pub fn intersect_analytic_analytic_bounded(
2252    a: AnalyticSurface<'_>,
2253    b: AnalyticSurface<'_>,
2254    grid_res: usize,
2255    v_range_hint_a: Option<(f64, f64)>,
2256    v_range_hint_b: Option<(f64, f64)>,
2257) -> Result<Vec<IntersectionCurve>, MathError> {
2258    intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, None)
2259}
2260
2261/// [`intersect_analytic_analytic_bounded`] with its general marcher confined
2262/// to `region`.
2263///
2264/// The marcher starts only from seeds that converge into the region (with a
2265/// margin of about two grid cells) and stops where a curve leaves it. Pairs
2266/// solved in closed form are returned whole, as by the unconfined call. Two
2267/// bounded faces meet only inside both their boxes, so their overlap is a
2268/// sound region for a face pair.
2269///
2270/// # Errors
2271///
2272/// Returns `MathError` if algebraic intersection fails or marching diverges.
2273pub fn intersect_analytic_analytic_in_region(
2274    a: AnalyticSurface<'_>,
2275    b: AnalyticSurface<'_>,
2276    grid_res: usize,
2277    v_range_hint_a: Option<(f64, f64)>,
2278    v_range_hint_b: Option<(f64, f64)>,
2279    region: Aabb3,
2280) -> Result<Vec<IntersectionCurve>, MathError> {
2281    intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, Some(region))
2282}
2283
2284fn intersect_analytic_analytic_impl(
2285    a: AnalyticSurface<'_>,
2286    b: AnalyticSurface<'_>,
2287    grid_res: usize,
2288    v_range_hint_a: Option<(f64, f64)>,
2289    v_range_hint_b: Option<(f64, f64)>,
2290    region: Option<Aabb3>,
2291) -> Result<Vec<IntersectionCurve>, MathError> {
2292    // Try algebraic specialization for known surface pairs before falling
2293    // back to the general marching approach.
2294    if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
2295        return Ok(result);
2296    }
2297    marched_sections(a, b, grid_res, v_range_hint_a, v_range_hint_b, region)
2298}
2299
2300/// `x + y t` with one rounding, at the end: Dekker's split product and
2301/// Knuth's two-sum keep the rounding of `y t` and of the sum, and the last
2302/// addition rounds their total once.
2303fn add_product(x: f64, y: f64, t: f64) -> f64 {
2304    let split = |v: f64| {
2305        let c = 134_217_729.0 * v;
2306        let hi = c - (c - v);
2307        (hi, v - hi)
2308    };
2309    let p = y * t;
2310    let ((yh, yl), (th, tl)) = (split(y), split(t));
2311    let p_err = yl.madd(tl, yl.madd(th, yh.madd(tl, yh.madd(th, -p))));
2312    let s = x + p;
2313    let back = s - x;
2314    let s_err = (x - (s - back)) + (p - back);
2315    s + (s_err + p_err)
2316}
2317
2318/// An analytic surface moved by a vector, held while the marcher works on it.
2319enum Moved {
2320    Cylinder(CylindricalSurface),
2321    Cone(ConicalSurface),
2322    Sphere(SphericalSurface),
2323    Torus(ToroidalSurface),
2324}
2325
2326impl Moved {
2327    /// `surface` moved so that `anchor` lies at the origin, how far its `v`
2328    /// moved, and a bound on how far the move's rounding shifted it.
2329    ///
2330    /// A cylinder's frame, which can sit anywhere along its axis, goes to
2331    /// the point of the axis nearest `anchor`, so the surface reads alike
2332    /// wherever its frame sat, and its `v` drops by as much. That point is
2333    /// the old frame plus a multiple of the axis, each coordinate summed with
2334    /// one rounding at the end ([`add_product`]), so it lies within a float
2335    /// step of the axis however far the old frame sat: moved by plain sums,
2336    /// a frame 1e12 along a tilted axis landed 4.7e-6 off it. Each other
2337    /// surface's frame point (an apex or a centre) is fixed by its shape and
2338    /// moves by one subtraction, rounding each coordinate by up to half its
2339    /// float spacing.
2340    fn new(surface: &AnalyticSurface<'_>, anchor: Point3) -> (Self, f64, f64) {
2341        let size = |p: Point3| p.x().abs().max(p.y().abs()).max(p.z().abs());
2342        let shift = Point3::new(0.0, 0.0, 0.0) - anchor;
2343        match surface {
2344            AnalyticSurface::Cylinder(c) => {
2345                let (o, a) = (c.origin(), c.axis());
2346                let along = a.dot(anchor - o);
2347                let foot = Point3::new(
2348                    add_product(o.x(), a.x(), along),
2349                    add_product(o.y(), a.y(), along),
2350                    add_product(o.z(), a.z(), along),
2351                );
2352                let near = foot + shift;
2353                let error = 4.0 * f64::EPSILON * (size(foot) + size(near));
2354                (Self::Cylinder(c.framed_at(near)), along, error)
2355            }
2356            AnalyticSurface::Cone(c) => {
2357                let near = c.translated(shift);
2358                let error = 2.0 * f64::EPSILON * size(near.apex());
2359                (Self::Cone(near), 0.0, error)
2360            }
2361            AnalyticSurface::Sphere(s) => {
2362                let near = s.translated(shift);
2363                let error = 2.0 * f64::EPSILON * size(near.center());
2364                (Self::Sphere(near), 0.0, error)
2365            }
2366            AnalyticSurface::Torus(t) => {
2367                let near = t.translated(shift);
2368                let error = 2.0 * f64::EPSILON * size(near.center());
2369                (Self::Torus(near), 0.0, error)
2370            }
2371        }
2372    }
2373
2374    const fn surface(&self) -> AnalyticSurface<'_> {
2375        match self {
2376            Self::Cylinder(c) => AnalyticSurface::Cylinder(c),
2377            Self::Cone(c) => AnalyticSurface::Cone(c),
2378            Self::Sphere(s) => AnalyticSurface::Sphere(s),
2379            Self::Torus(t) => AnalyticSurface::Torus(t),
2380        }
2381    }
2382}
2383
2384/// The sections of `a` and `b` that the general marcher traces from seeds
2385/// on a grid over `a`, confined to `region` when one is given.
2386///
2387/// The marcher works with both surfaces moved by the same vector to the
2388/// middle of the region, or of `a`'s patch, each cylinder's frame moved
2389/// along its axis to there, and moves its curves back. Far
2390/// from the origin the spacing of floats in one coordinate would otherwise
2391/// decide whether a point lies on both surfaces and whether they cross
2392/// there, and a pair moved there would not read as it does near the origin:
2393/// a touch as a crossing, a shallow crossing as a touch. Moving a curve back
2394/// rounds each coordinate by up to half its spacing there, and moving each
2395/// surface shifts it by a bound [`Moved::new`] gives, so each fit is held
2396/// that much within the linear tolerance; where that leaves less than half
2397/// of it, a traced section is refused before its fit.
2398fn marched_sections(
2399    a: AnalyticSurface<'_>,
2400    b: AnalyticSurface<'_>,
2401    grid_res: usize,
2402    v_range_hint_a: Option<(f64, f64)>,
2403    v_range_hint_b: Option<(f64, f64)>,
2404    region: Option<Aabb3>,
2405) -> Result<Vec<IntersectionCurve>, MathError> {
2406    let size = |p: Point3| p.x().abs().max(p.y().abs()).max(p.z().abs());
2407    let (anchor, reach) = if let Some(r) = region {
2408        (r.min + (r.max - r.min) * 0.5, (r.max - r.min).length())
2409    } else {
2410        let (surf_a, _, (u0, u1), default_v_a) = surface_closures(&a);
2411        let (v0, v1) = v_range_hint_a.unwrap_or(default_v_a);
2412        let (first, last) = (surf_a(u0, v0), surf_a(u1, v1));
2413        let reach = patch_diagonal(surf_a.as_ref(), (u0, u1), (v0, v1));
2414        (first + (last - first) * 0.5, reach)
2415    };
2416    let shift = anchor - Point3::new(0.0, 0.0, 0.0);
2417    let ((near_a, dv_a, moved_a), (near_b, dv_b, moved_b)) =
2418        (Moved::new(&a, anchor), Moved::new(&b, anchor));
2419    let v_range = |surface: &AnalyticSurface<'_>, hint: Option<(f64, f64)>, dv: f64| {
2420        let (lo, hi) = hint.unwrap_or_else(|| surface_closures(surface).3);
2421        Some((lo - dv, hi - dv))
2422    };
2423    let linear = Tolerance::new().linear;
2424    let fit_tol =
2425        ((-f64::EPSILON).madd(size(anchor) + reach, linear) - moved_a - moved_b).min(linear);
2426    let near_region = region.map(|r| Aabb3 {
2427        min: r.min - shift,
2428        max: r.max - shift,
2429    });
2430    let curves = marched_sections_near(
2431        near_a.surface(),
2432        near_b.surface(),
2433        grid_res,
2434        v_range(&a, v_range_hint_a, dv_a),
2435        v_range(&b, v_range_hint_b, dv_b),
2436        near_region,
2437        fit_tol,
2438    )?;
2439    curves
2440        .into_iter()
2441        .map(|c| {
2442            let ctrl = c
2443                .curve
2444                .control_points()
2445                .iter()
2446                .map(|&p| p + shift)
2447                .collect();
2448            let curve = NurbsCurve::new(
2449                c.curve.degree(),
2450                c.curve.knots().to_vec(),
2451                ctrl,
2452                c.curve.weights().to_vec(),
2453            )?;
2454            let points = c
2455                .points
2456                .into_iter()
2457                .map(|ip| IntersectionPoint {
2458                    point: ip.point + shift,
2459                    ..ip
2460                })
2461                .collect();
2462            Ok(IntersectionCurve { curve, points })
2463        })
2464        .collect()
2465}
2466
2467/// [`marched_sections`] on surfaces near the origin, each fit held within
2468/// `fit_tol` of both surfaces. A traced section is refused before its fit
2469/// where `fit_tol` is less than half the linear tolerance.
2470#[allow(clippy::too_many_lines, clippy::similar_names)]
2471fn marched_sections_near(
2472    a: AnalyticSurface<'_>,
2473    b: AnalyticSurface<'_>,
2474    grid_res: usize,
2475    v_range_hint_a: Option<(f64, f64)>,
2476    v_range_hint_b: Option<(f64, f64)>,
2477    region: Option<Aabb3>,
2478    fit_tol: f64,
2479) -> Result<Vec<IntersectionCurve>, MathError> {
2480    let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
2481    let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
2482    let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
2483    let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
2484
2485    // Compute characteristic surface dimensions for adaptive parameters.
2486    let diag_a = patch_diagonal(surf_a.as_ref(), u_range_a, v_range_a);
2487    let diag_b = patch_diagonal(surf_b.as_ref(), u_range_b, v_range_b);
2488    let char_size = diag_a.min(diag_b).max(0.1);
2489
2490    let march_step = (char_size * 0.02).clamp(0.005, 0.5);
2491    let meet = region;
2492    #[allow(clippy::cast_precision_loss)]
2493    let margin = 2.0 * char_size / grid_res as f64;
2494    let region = region.map(|r| r.expanded(margin));
2495
2496    // Seeds: the middle of each cell of a grid over a patch whose distance
2497    // from the other surface is within the cell's reach from its middle (see
2498    // [`cell_reach`]), and the box of those cells. Every point of the section
2499    // lies in a cell of each patch, no farther from its middle than that, so
2500    // each cell it crosses gives a seed. A cell whose distance or reach
2501    // cannot be read (its middle on the other surface's axis, centre or apex)
2502    // may hold the section: it is kept, its middle its seed, and where its
2503    // reach is unknown its box is all of space.
2504    let cells = |surface: &AnalyticSurface<'_>,
2505                 surf: &dyn Fn(f64, f64) -> Point3,
2506                 (u_range, v_range): ((f64, f64), (f64, f64)),
2507                 other: &AnalyticSurface<'_>,
2508                 near: Option<Aabb3>| {
2509        #[allow(clippy::cast_precision_loss)]
2510        let n = grid_res as f64;
2511        let (du, dv) = ((u_range.1 - u_range.0) / n, (v_range.1 - v_range.0) / n);
2512        let mut found = Vec::new();
2513        let mut kept = Vec::new();
2514        let mut held: Option<Aabb3> = None;
2515        for i in 0..grid_res {
2516            for j in 0..grid_res {
2517                #[allow(clippy::cast_precision_loss)]
2518                let (u, v) = (
2519                    du.madd(i as f64 + 0.5, u_range.0),
2520                    dv.madd(j as f64 + 0.5, v_range.0),
2521                );
2522                let middle = surf(u, v);
2523                let reach = cell_reach(surface, (0.5 * du, 0.5 * dv), v);
2524                let placed = reach.is_finite()
2525                    && middle.x().is_finite()
2526                    && middle.y().is_finite()
2527                    && middle.z().is_finite();
2528                if placed && near.is_some_and(|r| !r.expanded(reach).contains_point(middle)) {
2529                    continue;
2530                }
2531                let reading = section_fit::Carrier::distance(other, middle)
2532                    .filter(|(d, n)| d.is_finite() && n.length().is_finite());
2533                // The rounding of the distance, so a cell is dropped only
2534                // where it surely holds no point of the other surface.
2535                let slack = || {
2536                    let size = middle.x().abs().max(middle.y().abs()).max(middle.z().abs());
2537                    128.0
2538                        * f64::EPSILON
2539                        * (section_fit::Carrier::scale(surface, middle)
2540                            + section_fit::Carrier::scale(other, middle)
2541                            + size)
2542                };
2543                let (dist, seed) = match reading {
2544                    Some((d, _))
2545                        if placed
2546                            && d.abs() > reach
2547                            && (d.abs() > 2.0 * reach || d.abs() - slack() > reach) =>
2548                    {
2549                        continue;
2550                    }
2551                    Some((d, n)) => (d.abs(), middle - n * (0.5 * d)),
2552                    None => (f64::INFINITY, middle),
2553                };
2554                found.push((dist, seed));
2555                kept.push((i, j));
2556                let cell = if placed {
2557                    Aabb3 {
2558                        min: middle,
2559                        max: middle,
2560                    }
2561                    .expanded(reach)
2562                } else {
2563                    Aabb3 {
2564                        min: Point3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2565                        max: Point3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2566                    }
2567                };
2568                held = Some(held.map_or(cell, |h| h.union(cell)));
2569            }
2570        }
2571        (found, held, kept)
2572    };
2573    let (mut candidates, held, kept_a) =
2574        cells(&a, surf_a.as_ref(), (u_range_a, v_range_a), &b, region);
2575
2576    // With no seed on A, no point of the section lies on A's patch. A test
2577    // on the nearest cell's distance to B against three cells of the smaller
2578    // patch's size read a rod's shallow crossing of a cone's patch, whose
2579    // cells are each 4900 across, as no crossing.
2580    let Some(held) = held else {
2581        return Ok(vec![]);
2582    };
2583    // The seeds below come from cells' middles, and a cell's seed settles
2584    // on one curve: a second loop in the same cells of both patches had
2585    // none. Cut A's kept cells until each is proved to hold no point of
2586    // the section, or at most one arc of it, or is too small for a fit to
2587    // resolve (see [`cover::Cover`]). Each class of linked cells holds one
2588    // arc of a part of the section: after the march, a marched point lies
2589    // in it, or a seed from it settles on a marched curve or starts a march.
2590    let mut cover = cover::Cover::new(
2591        &a,
2592        &b,
2593        (u_range_a, v_range_a),
2594        v_range_b,
2595        grid_res,
2596        &kept_a,
2597        meet.zip(region),
2598        Tolerance::new().linear,
2599        cover::MOST_LEAVES,
2600    );
2601    // Where the cuts did not all settle, two loops in one cell of one patch
2602    // can lie in two cells of the other, which lie within their reach of
2603    // A's seeds' cells.
2604    if !cover.complete() {
2605        candidates.extend(cells(&b, surf_b.as_ref(), (u_range_b, v_range_b), &a, Some(held)).0);
2606    }
2607    candidates.sort_by(|p, q| p.0.total_cmp(&q.0));
2608
2609    // A seed is only near the intersection; settle it onto the curve before
2610    // asking whether it lies in the region, so a coarse grid point beside a
2611    // short in-region span still starts its march, and march from there, so
2612    // the march does not begin outside the region and stop at once. The
2613    // projections from one surface to the other also settle where the two
2614    // pass closest without meeting, with both normals along the gap: a
2615    // seed there lies on no curve, and a march from it never closes on it.
2616    // Nor does a seed where the two surfaces touch without crossing (their
2617    // normals within about 1e-6 of parallel): the section there can be a
2618    // lone point, and no direction along it is defined.
2619    let settle = |mid: Point3| {
2620        let on = settle_on_section(&a, &b, mid).or_else(|| {
2621            let mut p = mid;
2622            for _ in 0..8 {
2623                let (ua, va) = project_analytic(&a, p, u_range_a, v_range_a);
2624                let pa = surf_a(ua, va);
2625                let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2626                let pb = surf_b(ub, vb);
2627                p = Point3::new(
2628                    (pa.x() + pb.x()) * 0.5,
2629                    (pa.y() + pb.y()) * 0.5,
2630                    (pa.z() + pb.z()) * 0.5,
2631                );
2632                if (pa - pb).length() < 1e-9 {
2633                    break;
2634                }
2635            }
2636            settle_on_section(&a, &b, p)
2637        });
2638        // The steps settle on the section of the whole surfaces, which can
2639        // lie on a part neither patch holds (a cone's other nappe).
2640        let near_patches = |q: Point3| {
2641            let (ua, va) = project_analytic(&a, q, u_range_a, v_range_a);
2642            let (ub, vb) = project_analytic(&b, q, u_range_b, v_range_b);
2643            (q - surf_a(ua, va)).length() <= march_step
2644                && (q - surf_b(ub, vb)).length() <= march_step
2645        };
2646        let Some(on) = on.filter(|&on| {
2647            crosses_at(&a, &b, on)
2648                && near_patches(on)
2649                && region.is_none_or(|r| r.contains_point(on))
2650        }) else {
2651            return Ok(None);
2652        };
2653        // A crossing whose curvature cannot be read cannot be marched; the
2654        // section is refused, not traced without it.
2655        station(&a, &b, on, Vec3::new(0.0, 0.0, 0.0))
2656            .map(Some)
2657            .ok_or(MathError::ConvergenceFailure { iterations: 0 })
2658    };
2659    let off_patch = |q: Point3| {
2660        let (ua, va) = project_analytic(&a, q, u_range_a, v_range_a);
2661        let (ub, vb) = project_analytic(&b, q, u_range_b, v_range_b);
2662        (!is_u_periodic(&a) && (ua <= u_range_a.0 || ua >= u_range_a.1))
2663            || va <= v_range_a.0
2664            || va >= v_range_a.1
2665            || (!is_u_periodic(&b) && (ub <= u_range_b.0 || ub >= u_range_b.1))
2666            || vb <= v_range_b.0
2667            || vb >= v_range_b.1
2668    };
2669
2670    // March from each seed, nearest first, unless it settles on a curve
2671    // already marched. Seeds on both patches march first: one just past a
2672    // patch's edge marches along a curve that one inside may already have
2673    // marched, which its middle then lies on.
2674    // March from a seed on the section and fit what the march traces,
2675    // unless its middle lies on a curve already marched. The march's points
2676    // where its branch is then marched, `None` where it traces no curve. A
2677    // march is kept among the marched only with its curve: a march with no
2678    // curve reaches no part of the section.
2679    let trace = |seed: Point3,
2680                 marched: &mut Vec<Vec<Point3>>,
2681                 curves: &mut Vec<IntersectionCurve>|
2682     -> Result<Option<Vec<Point3>>, MathError> {
2683        let march_result = march_analytic_intersection(
2684            &a,
2685            &b,
2686            surf_a.as_ref(),
2687            norm_a.as_ref(),
2688            surf_b.as_ref(),
2689            norm_b.as_ref(),
2690            seed,
2691            u_range_a,
2692            v_range_a,
2693            u_range_b,
2694            v_range_b,
2695            march_step,
2696            is_u_periodic(&a),
2697            is_u_periodic(&b),
2698            region,
2699        )
2700        .ok_or(MathError::ConvergenceFailure {
2701            iterations: MARCH_STEPS,
2702        })?;
2703        if march_result.len() < 2 {
2704            return Ok(None);
2705        }
2706        let middle = march_result[march_result.len() / 2];
2707        if marched.iter().any(|m| on_march(&a, &b, middle, m)) {
2708            return Ok(Some(march_result));
2709        }
2710
2711        // Two points far closer than a step only crowd the fit.
2712        let crowd = 1e-3 * march_step;
2713        let mut spaced: Vec<Point3> = Vec::with_capacity(march_result.len());
2714        for (k, &p) in march_result.iter().enumerate() {
2715            let last = k + 1 == march_result.len();
2716            match spaced.last() {
2717                Some(&q) if (p - q).length() < crowd => {
2718                    if last && spaced.len() > 1 {
2719                        spaced.pop();
2720                        spaced.push(p);
2721                    }
2722                }
2723                _ => spaced.push(p),
2724            }
2725        }
2726        if spaced.len() < 2 {
2727            // A march shorter than that, clipped to a short piece of the
2728            // section, keeps both its ends.
2729            match (march_result.first(), march_result.last()) {
2730                (Some(&first), Some(&last)) if (last - first).length() > 0.0 => {
2731                    spaced = vec![first, last];
2732                }
2733                _ => return Ok(None),
2734            }
2735        }
2736        if fit_tol < 0.5 * Tolerance::new().linear {
2737            return Err(MathError::ConvergenceFailure { iterations: 0 });
2738        }
2739        let (curve, points) = fit_section(&a, &b, &spaced, fit_tol)?;
2740        let ipts: Vec<IntersectionPoint> = points
2741            .iter()
2742            .map(|&pt| IntersectionPoint {
2743                point: pt,
2744                param1: (0.0, 0.0),
2745                param2: (0.0, 0.0),
2746            })
2747            .collect();
2748        marched.push(march_result.clone());
2749        curves.push(IntersectionCurve {
2750            curve,
2751            points: ipts,
2752        });
2753        Ok(Some(march_result))
2754    };
2755
2756    let mut curves = Vec::new();
2757    let mut marched: Vec<Vec<Point3>> = Vec::new();
2758    let mut past_edges = Vec::new();
2759    let mut k = 0;
2760    while k < candidates.len() + past_edges.len() {
2761        let seed = if k < candidates.len() {
2762            let mid = candidates[k].1;
2763            k += 1;
2764            let Some(seed) = settle(mid)? else {
2765                continue;
2766            };
2767            if off_patch(seed.p) {
2768                past_edges.push(seed);
2769                continue;
2770            }
2771            seed
2772        } else {
2773            k += 1;
2774            past_edges[k - 1 - candidates.len()]
2775        };
2776        if marched.iter().any(|m| on_march(&a, &b, seed.p, m)) {
2777            continue;
2778        }
2779        trace(seed.p, &mut marched, &mut curves)?;
2780    }
2781
2782    for m in &marched {
2783        cover.mark_marched(m);
2784    }
2785    let (marched, curves) = (RefCell::new(marched), RefCell::new(curves));
2786    // A probe whose nearest point on a fitted curve lies, as near as that
2787    // fit's bound, on the class's arc. Near a node a march from the probe
2788    // itself can stall.
2789    let fitted = |cover: &cover::Cover<'_, '_>, class: &[usize], z: Point3| {
2790        curves.borrow().iter().any(|c| {
2791            crate::nurbs::projection::project_point_to_curve(&c.curve, z, 1e-12)
2792                .is_ok_and(|f| cover.holds(class, f.point, fit_tol))
2793        })
2794    };
2795    // A probe settled on the section, on a marched branch or marched from.
2796    let mut seed = |z: Point3| -> Result<Option<Vec<Point3>>, MathError> {
2797        let Some(seed) = settle(z)? else {
2798            return Ok(None);
2799        };
2800        if marched.borrow().iter().any(|m| on_march(&a, &b, seed.p, m)) {
2801            return Ok(Some(vec![seed.p]));
2802        }
2803        let traced = trace(seed.p, &mut marched.borrow_mut(), &mut curves.borrow_mut())?;
2804        Ok(Some(traced.unwrap_or_default()))
2805    };
2806    // Where the cuts did not all settle, the cover proves nothing, and the
2807    // two patches' seeds above stand as they are.
2808    while cover.complete() {
2809        let classes = cover.classes();
2810        if classes.is_empty() {
2811            break;
2812        }
2813        for class in classes {
2814            cover.resolve(&class, &fitted, &mut seed)?;
2815        }
2816    }
2817
2818    Ok(curves.into_inner())
2819}
2820
2821/// How far a point of the patch of `surface` within `du` and `dv` of
2822/// parameter from `(u, v)` can lie from that point: the steps times the
2823/// greatest rates at which the surface moves with each parameter there.
2824fn cell_reach(surface: &AnalyticSurface<'_>, (du, dv): (f64, f64), v: f64) -> f64 {
2825    match surface {
2826        AnalyticSurface::Cylinder(c) => du.madd(c.radius(), dv),
2827        AnalyticSurface::Cone(c) => (du * c.half_angle().cos()).madd(v.abs() + dv, dv),
2828        AnalyticSurface::Sphere(s) => (du + dv) * s.radius(),
2829        AnalyticSurface::Torus(t) => {
2830            du.madd(t.major_radius() + t.minor_radius(), dv * t.minor_radius())
2831        }
2832    }
2833}
2834
2835/// Whether `p`, a point of the section of `a` and `b`, lies on the branch
2836/// a march traced through `points`. The chord of the march nearest `p` must
2837/// pass no farther from it than a fifth of its length, four times the sag
2838/// of an arc that turns as far as a step may (twice [`MARCH_TURN`]). From
2839/// that chord's nearest point, Newton steps move onto the section and along
2840/// its tangent toward `p`, each on the sheets `p` and the chord's ends lie
2841/// on (a cone's nappe, a torus's tube): `p` lies on the branch where they
2842/// come within the linear tolerance of it. A point of another branch,
2843/// however near the chord (another nappe 1e-4 away), stays that far from
2844/// where they settle.
2845fn on_march(
2846    a: &AnalyticSurface<'_>,
2847    b: &AnalyticSurface<'_>,
2848    p: Point3,
2849    points: &[Point3],
2850) -> bool {
2851    use section_fit::Carrier;
2852    let nearest = points
2853        .windows(2)
2854        .map(|w| {
2855            let chord = w[1] - w[0];
2856            let len2 = chord.dot(chord);
2857            let s = if len2 > 0.0 {
2858                ((p - w[0]).dot(chord) / len2).clamp(0.0, 1.0)
2859            } else {
2860                0.0
2861            };
2862            let foot = w[0] + chord * s;
2863            ((p - foot).length(), len2.sqrt(), foot, w)
2864        })
2865        .min_by(|x, y| x.0.total_cmp(&y.0));
2866    let Some((off, len, foot, w)) = nearest else {
2867        return false;
2868    };
2869    let sheets = |q: Point3| (a.sheet(q), b.sheet(q));
2870    if off > MARCH_TURN * len || sheets(w[0]) != sheets(p) || sheets(w[1]) != sheets(p) {
2871        return false;
2872    }
2873    let tol = Tolerance::new().linear;
2874    let mut guess = foot;
2875    for _ in 0..8 {
2876        let Some(q) = settle_on_section(a, b, guess) else {
2877            return false;
2878        };
2879        if sheets(q) != sheets(p) {
2880            return false;
2881        }
2882        let miss = p - q;
2883        if miss.length() <= tol {
2884            return true;
2885        }
2886        let (Some((_, na)), Some((_, nb))) = (a.distance(q), b.distance(q)) else {
2887            return false;
2888        };
2889        let t = na.cross(nb);
2890        let sin = t.length();
2891        if sin <= 0.0 {
2892            return false;
2893        }
2894        let t = t * (1.0 / sin);
2895        guess = q + t * miss.dot(t);
2896    }
2897    false
2898}
2899
2900/// The diagonal of the patch `surf` spans over `u_range` by `v_range`: the
2901/// chord between its first and last corners, or, for a patch closed both
2902/// ways (a whole torus, whose last corner is its first), the chord from its
2903/// first corner to its middle.
2904fn patch_diagonal(
2905    surf: &dyn Fn(f64, f64) -> Point3,
2906    (u0, u1): (f64, f64),
2907    (v0, v1): (f64, f64),
2908) -> f64 {
2909    let corner = (surf(u0, v0) - surf(u1, v1)).length();
2910    let middle = (surf(u0, v0) - surf(f64::midpoint(u0, u1), f64::midpoint(v0, v1))).length();
2911    if corner > 1e-9 * middle {
2912        corner
2913    } else {
2914        middle
2915    }
2916}
2917
2918/// Try algebraic (closed-form or semi-algebraic) intersection for known
2919/// surface pairs before falling back to general marching.
2920///
2921/// Returns `Some(curves)` if a specialized method exists, `None` otherwise.
2922///
2923/// Currently handles:
2924/// - **Sphere-sphere**: intersection is a circle (plane through the two centers)
2925/// - **Coaxial cylinders**: same axis → circle(s) or empty
2926/// - **Sphere-cylinder**: reduce to quadratic in one parameter
2927/// - **Cone-cylinder**: parallel axes in the cone's own `v`, other axes
2928///   along the cylinder's rulings
2929/// - **Cone-sphere**: off the cone's axis, along the cone's generators
2930/// - **Torus-cylinder**: along the cylinder's rulings
2931#[allow(clippy::too_many_lines)]
2932fn try_algebraic_intersection(
2933    a: &AnalyticSurface<'_>,
2934    b: &AnalyticSurface<'_>,
2935    v_range_a: Option<(f64, f64)>,
2936    v_range_b: Option<(f64, f64)>,
2937) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2938    match (a, b) {
2939        (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => Ok(
2940            algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)?
2941                .or_else(|| ruling_cone_cylinder(cone, cyl, true)),
2942        ),
2943        (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => Ok(
2944            algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)?
2945                .or_else(|| ruling_cone_cylinder(cone, cyl, false)),
2946        ),
2947        (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
2948            algebraic_sphere_sphere(s1, s2).map(Some)
2949        }
2950        (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
2951            let axis_dot = c1.axis().dot(c2.axis()).abs();
2952            if axis_dot > 1.0 - 1e-10 {
2953                // Axes are parallel — check if they're the same line.
2954                let delta = c2.origin() - c1.origin();
2955                let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2956                let along = delta_vec.dot(c1.axis());
2957                let perp = (delta_vec - c1.axis() * along).length();
2958                if perp < 1e-8 {
2959                    // Coaxial: same axis, different radii → no intersection
2960                    // (unless equal radius → degenerate overlap, skip)
2961                    if (c1.radius() - c2.radius()).abs() < 1e-8 {
2962                        return Ok(None); // Overlapping — let marcher handle
2963                    }
2964                    return Ok(Some(vec![])); // Coaxial, different radii
2965                }
2966                if let Some(rulings) = parallel_cylinders(c1, c2, v_range_a, v_range_b)? {
2967                    return Ok(Some(rulings));
2968                }
2969            }
2970            // Non-coaxial: algebraic quadratic in v.
2971            algebraic_cylinder_cylinder(c1, c2)
2972        }
2973        // Sphere-cylinder (both orderings).
2974        (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c)) => {
2975            algebraic_sphere_cylinder(s, c, true)
2976        }
2977        (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
2978            algebraic_sphere_cylinder(s, c, false)
2979        }
2980        (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => {
2981            if let Some(rulings) = shared_apex_cones(c1, c2, v_range_a, v_range_b)? {
2982                return Ok(Some(rulings));
2983            }
2984            if let Some(curves) = algebraic_cone_cone(c1, c2)? {
2985                return Ok(Some(curves));
2986            }
2987            Ok(algebraic_parallel_cone_cone(c1, c2, v_range_a, v_range_b))
2988        }
2989        (AnalyticSurface::Cone(cone), AnalyticSurface::Sphere(sphere)) => {
2990            Ok(ruling_cone_sphere(cone, sphere, true))
2991        }
2992        (AnalyticSurface::Sphere(sphere), AnalyticSurface::Cone(cone)) => {
2993            Ok(ruling_cone_sphere(cone, sphere, false))
2994        }
2995        (AnalyticSurface::Torus(t), AnalyticSurface::Cylinder(c)) => {
2996            if let Some(exacts) = exact_cylinder_torus(c, t)? {
2997                return exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p)))
2998                    .map(Some);
2999            }
3000            Ok(parallel_axis_torus_cylinder(t, c, true)
3001                .or_else(|| ruling_torus_cylinder(t, c, true)))
3002        }
3003        (AnalyticSurface::Cylinder(c), AnalyticSurface::Torus(t)) => {
3004            if let Some(exacts) = exact_cylinder_torus(c, t)? {
3005                return exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p)))
3006                    .map(Some);
3007            }
3008            Ok(parallel_axis_torus_cylinder(t, c, false)
3009                .or_else(|| ruling_torus_cylinder(t, c, false)))
3010        }
3011        (AnalyticSurface::Sphere(s), AnalyticSurface::Torus(t)) => {
3012            match exact_sphere_torus(s, t)? {
3013                Some(exacts) => {
3014                    exact_circle_curves(exacts, |p| (s.project_point(p), t.project_point(p)))
3015                        .map(Some)
3016                }
3017                None => Ok(sphere_torus_curves(s, t, true)),
3018            }
3019        }
3020        (AnalyticSurface::Torus(t), AnalyticSurface::Sphere(s)) => {
3021            match exact_sphere_torus(s, t)? {
3022                Some(exacts) => {
3023                    exact_circle_curves(exacts, |p| (t.project_point(p), s.project_point(p)))
3024                        .map(Some)
3025                }
3026                None => Ok(sphere_torus_curves(s, t, false)),
3027            }
3028        }
3029        (AnalyticSurface::Torus(t1), AnalyticSurface::Torus(t2)) => exact_torus_torus(t1, t2)?
3030            .map(|exacts| {
3031                exact_circle_curves(exacts, |p| (t1.project_point(p), t2.project_point(p)))
3032            })
3033            .transpose(),
3034        (AnalyticSurface::Cone(c), AnalyticSurface::Torus(t)) => exact_cone_torus(c, t)?
3035            .map(|exacts| exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p))))
3036            .transpose(),
3037        (AnalyticSurface::Torus(t), AnalyticSurface::Cone(c)) => exact_cone_torus(c, t)?
3038            .map(|exacts| exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p))))
3039            .transpose(),
3040    }
3041}
3042
3043/// A torus and a cylinder whose axes are parallel but distinct (a drill
3044/// through a ring parallel to its axis), traced along the cylinder's
3045/// rulings. A ruling stays at one distance `ρ` from the torus axis, so it
3046/// meets the tube where `(ρ − R)² + z² = r²`: a quadratic in its axial
3047/// parameter. `None` for any other pair (tilted or coaxial axes) and when
3048/// the sampling misses a window narrower than itself.
3049fn parallel_axis_torus_cylinder(
3050    torus: &ToroidalSurface,
3051    cyl: &CylindricalSurface,
3052    torus_first: bool,
3053) -> Option<Vec<IntersectionCurve>> {
3054    let axis = torus.z_axis();
3055    let along = cyl.axis().dot(axis);
3056    if along.abs() < 1.0 - 1e-10 {
3057        return None;
3058    }
3059    let offset = cyl.origin() - torus.center();
3060    if (offset - axis * offset.dot(axis)).length() < Tolerance::new().linear {
3061        return None;
3062    }
3063    let (major, minor) = (torus.major_radius(), torus.minor_radius());
3064    let roots = |u: f64| {
3065        let q = cyl.evaluate(u, 0.0) - torus.center();
3066        let height = q.dot(axis);
3067        let rho = (q - axis * height).length();
3068        let reach = minor * minor - (rho - major) * (rho - major);
3069        ruling_quadratic(1.0, 2.0 * along.signum() * height, height * height - reach)
3070    };
3071    let samples = ruling_samples(cyl, &roots);
3072    let loops = if samples.iter().all(Option::is_some) {
3073        closed_ruling_loops(cyl, &roots, &samples)
3074    } else {
3075        partial_ruling_loops(cyl, &roots, &samples)
3076    };
3077    if loops.is_empty() {
3078        return None;
3079    }
3080    Some(fit_ruling_loops(&loops, |p| {
3081        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
3082    }))
3083}
3084
3085/// Where two circles in a half-plane through an axis cross, as `(rho, z)`
3086/// pairs (distance from the axis, height along it): each sweeps a circle
3087/// about the axis. Two crossings closer than the linear tolerance are the
3088/// one point where the circles touch, side by side or one inside the
3089/// other. `None` (defer to the marcher) when the circles coincide or a
3090/// crossing lands on or past the axis; `Some` of none when they miss.
3091fn meridian_crossings(
3092    first: (f64, f64, f64),
3093    second: (f64, f64, f64),
3094    scale: f64,
3095) -> Option<Vec<(f64, f64)>> {
3096    let ((x1, z1, r1), (x2, z2, r2)) = (first, second);
3097    let (dx, dz) = (x2 - x1, z2 - z1);
3098    let dist = dx.hypot(dz);
3099    let slack = 1e-9 * scale;
3100    if dist < slack {
3101        return None;
3102    }
3103    let rounding = 8.0 * f64::EPSILON * (x1.abs() + x2.abs() + z1.abs() + z2.abs() + r1 + r2);
3104    if dist > r1 + r2 + rounding || dist < (r1 - r2).abs() - rounding {
3105        return Some(Vec::new());
3106    }
3107    let along = r2.madd(-r2, r1.madd(r1, dist * dist)) / (2.0 * dist);
3108    let across = r1.madd(r1, -(along * along)).max(0.0).sqrt();
3109    let (ux, uz) = (dx / dist, dz / dist);
3110    let sides: &[f64] = if 2.0 * across <= Tolerance::new().linear {
3111        &[0.0]
3112    } else {
3113        &[1.0, -1.0]
3114    };
3115    let mut crossings = Vec::with_capacity(sides.len());
3116    for side in sides {
3117        let rho = x1 + along * ux - side * across * uz;
3118        if rho <= slack {
3119            return None;
3120        }
3121        crossings.push((rho, z1 + along * uz + side * across * ux));
3122    }
3123    Some(crossings)
3124}
3125
3126/// Exact circles as intersection curves, each sampled at 33 points that
3127/// carry both surfaces' parameters, and a lone touching point as a curve
3128/// that stays on it.
3129fn exact_circle_curves(
3130    exacts: Vec<ExactIntersectionCurve>,
3131    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3132) -> Result<Vec<IntersectionCurve>, MathError> {
3133    let mut curves = Vec::with_capacity(exacts.len());
3134    for exact in exacts {
3135        match exact {
3136            ExactIntersectionCurve::Circle(circle) => {
3137                let points = (0..=32)
3138                    .map(|i| {
3139                        let point = circle.evaluate(TAU * f64::from(i) / 32.0);
3140                        let (param1, param2) = params(point);
3141                        IntersectionPoint {
3142                            point,
3143                            param1,
3144                            param2,
3145                        }
3146                    })
3147                    .collect();
3148                let r = circle.radius();
3149                let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
3150                curves.push(IntersectionCurve { curve, points });
3151            }
3152            // A lone point is where the surfaces touch.
3153            ExactIntersectionCurve::Points(points) if points.len() == 1 => {
3154                let point = points[0];
3155                let (param1, param2) = params(point);
3156                curves.push(IntersectionCurve {
3157                    curve: interpolate(&[point, point], 1)?,
3158                    points: vec![IntersectionPoint {
3159                        point,
3160                        param1,
3161                        param2,
3162                    }],
3163                });
3164            }
3165            ExactIntersectionCurve::Ellipse(_) | ExactIntersectionCurve::Points(_) => {}
3166        }
3167    }
3168    Ok(curves)
3169}
3170
3171/// Circles about an axis through `base`, at the given `(rho, z)` crossings.
3172fn circles_about_axis(
3173    base: Point3,
3174    axis: Vec3,
3175    crossings: &[(f64, f64)],
3176) -> Result<Vec<ExactIntersectionCurve>, MathError> {
3177    crossings
3178        .iter()
3179        .map(|&(rho, z)| {
3180            Circle3D::new(base + axis * z, axis, rho).map(ExactIntersectionCurve::Circle)
3181        })
3182        .collect()
3183}
3184
3185/// Exact intersection of two tori sharing an axis: their tube cross-sections
3186/// in a half-plane through the axis cross in up to two points, and each sweeps
3187/// a circle about the axis.
3188///
3189/// Cross-sections that touch meet at one point, sweeping one circle. `None`
3190/// (defer to the marcher) unless the axes lie on one line, or when the
3191/// cross-sections coincide.
3192///
3193/// # Errors
3194///
3195/// Returns an error if a section circle cannot be built.
3196pub fn exact_torus_torus(
3197    first: &ToroidalSurface,
3198    second: &ToroidalSurface,
3199) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3200    let axis = first.z_axis();
3201    let scale = first.major_radius() + second.major_radius();
3202    let offset = second.center() - first.center();
3203    // A spindle torus's tube also crosses the far side of the axis.
3204    if first.minor_radius() >= first.major_radius()
3205        || second.minor_radius() >= second.major_radius()
3206        || axis.cross(second.z_axis()).length() > 1e-9
3207        || offset.cross(axis).length() > 1e-9 * scale
3208    {
3209        return Ok(None);
3210    }
3211    let Some(crossings) = meridian_crossings(
3212        (first.major_radius(), 0.0, first.minor_radius()),
3213        (
3214            second.major_radius(),
3215            offset.dot(axis),
3216            second.minor_radius(),
3217        ),
3218        scale,
3219    ) else {
3220        return Ok(None);
3221    };
3222    circles_about_axis(first.center(), axis, &crossings).map(Some)
3223}
3224
3225/// Exact intersection of a torus with a cylinder sharing its axis.
3226///
3227/// The wall line and the tube's cross-section in a half-plane through the
3228/// axis cross in up to two points, each sweeping a circle about the axis. A
3229/// wall touching the tube's outer equator, ring or spindle, or a ring torus's
3230/// inner equator meets it along the one circle at the torus's centre.
3231///
3232/// `None` (defer to the marcher) unless the axes lie on one line, or when
3233/// the wall reaches the part of a spindle torus's tube across the axis.
3234///
3235/// # Errors
3236///
3237/// Returns an error if a section circle cannot be built.
3238pub fn exact_cylinder_torus(
3239    cylinder: &CylindricalSurface,
3240    torus: &ToroidalSurface,
3241) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3242    let axis = torus.z_axis();
3243    let scale = torus.major_radius() + cylinder.radius();
3244    let offset = cylinder.origin() - torus.center();
3245    let linear = crate::tolerance::Tolerance::default().linear;
3246    if axis.cross(cylinder.axis()).length() > 1e-9
3247        || offset.cross(axis).length() > 1e-9 * scale
3248        || cylinder.radius() + torus.major_radius() <= torus.minor_radius() + linear
3249    {
3250        return Ok(None);
3251    }
3252    let gap = cylinder.radius() - torus.major_radius();
3253    let small = torus.minor_radius();
3254    // The equator circle lies on the torus within the wall's distance from
3255    // the tube, so it stands for the section while that distance is within
3256    // the linear tolerance, whatever the scale.
3257    if (gap.abs() - small).abs() <= linear {
3258        return circles_about_axis(torus.center(), axis, &[(cylinder.radius(), 0.0)]).map(Some);
3259    }
3260    if gap.abs() > small {
3261        return Ok(Some(Vec::new()));
3262    }
3263    let height = small.madd(small, -(gap * gap)).sqrt();
3264    circles_about_axis(
3265        torus.center(),
3266        axis,
3267        &[(cylinder.radius(), height), (cylinder.radius(), -height)],
3268    )
3269    .map(Some)
3270}
3271
3272/// Exact intersection of a ring torus with a cone sharing its axis.
3273///
3274/// In a half-plane through the axis, a generator of the cone runs from the
3275/// apex at the half angle `a` from the radial direction, and the tube's
3276/// cross-section is a circle of the minor radius `r` about `(R, h)`: `R` the
3277/// major radius, `h` the torus centre's height above the apex along the
3278/// cone's axis. The generator meets that circle at `v = t ± √(r² − p²)`
3279/// along it, `t = R cos a + h sin a` the foot of the perpendicular from the
3280/// centre and `p = |R sin a − h cos a|` its length. Each root ahead of the
3281/// apex sweeps a circle about the axis. A generator within the linear
3282/// tolerance of tangent to the cross-section touches the tube along the one
3283/// circle at its foot.
3284///
3285/// `None` (defer to the marcher) unless the axes lie on one line, and for a
3286/// horn or spindle torus, whose tube reaches the axis.
3287///
3288/// # Errors
3289///
3290/// Returns an error if a section circle cannot be built.
3291pub fn exact_cone_torus(
3292    cone: &ConicalSurface,
3293    torus: &ToroidalSurface,
3294) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3295    let axis = cone.axis();
3296    let (major, minor) = (torus.major_radius(), torus.minor_radius());
3297    let offset = torus.center() - cone.apex();
3298    // The cone's axis must pass the torus's centre within the torus's own
3299    // scale: an apex far away does not widen the band.
3300    if minor >= major
3301        || axis.cross(torus.z_axis()).length() > 1e-9
3302        || offset.cross(axis).length() > 1e-9 * (major + minor)
3303    {
3304        return Ok(None);
3305    }
3306    let linear = Tolerance::new().linear;
3307    let (sin_a, cos_a) = cone.half_angle().sin_cos();
3308    let height = offset.dot(axis);
3309    let foot = major.madd(cos_a, height * sin_a);
3310    let reach = major.madd(sin_a, -(height * cos_a)).abs();
3311    let roots = if (reach - minor).abs() <= linear {
3312        vec![foot]
3313    } else if reach > minor {
3314        Vec::new()
3315    } else {
3316        let half = ((minor - reach) * (minor + reach)).sqrt();
3317        vec![foot - half, foot + half]
3318    };
3319    let crossings: Vec<(f64, f64)> = roots
3320        .into_iter()
3321        .filter(|&v| v * cos_a > linear)
3322        .map(|v| (v * cos_a, v * sin_a))
3323        .collect();
3324    circles_about_axis(cone.apex(), axis, &crossings).map(Some)
3325}
3326
3327/// Exact intersection of a torus with a sphere centred on its axis.
3328///
3329/// The sphere's great circle and the tube's cross-section in a half-plane
3330/// through the axis cross in up to two points, and each sweeps a circle
3331/// about the axis; where they touch (a ball sitting in the ring's hole or
3332/// on its rim) they meet along one circle. A sphere off the axis that
3333/// touches a ring torus at one point gives that point.
3334///
3335/// `None` (defer to the marcher) for a spindle torus, and for a sphere off
3336/// the axis that does not touch the torus at one point.
3337///
3338/// # Errors
3339///
3340/// Returns an error if a section circle cannot be built.
3341pub fn exact_sphere_torus(
3342    sphere: &SphericalSurface,
3343    torus: &ToroidalSurface,
3344) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3345    let axis = torus.z_axis();
3346    let scale = torus.major_radius() + sphere.radius();
3347    let offset = sphere.center() - torus.center();
3348    // A spindle torus's tube also crosses the far side of the axis.
3349    if torus.minor_radius() >= torus.major_radius() {
3350        return Ok(None);
3351    }
3352    if offset.cross(axis).length() > 1e-9 * scale {
3353        // A sphere centred on the core circle with the tube's own radius
3354        // holds the meridian circle through its centre, and the tube round
3355        // it: they meet along that circle alone. The circle strays from the
3356        // tube by the centre's distance from the core circle and the radii's
3357        // difference, which must both be rounding and within tolerance.
3358        let radial = offset - axis * offset.dot(axis);
3359        let slack = 64.0
3360            * f64::EPSILON
3361            * (torus.major_radius() + torus.minor_radius() + sphere.radius() + offset.length());
3362        let stray = (radial.length() - torus.major_radius()).hypot(offset.dot(axis))
3363            + (sphere.radius() - torus.minor_radius()).abs();
3364        if stray <= slack.min(Tolerance::new().linear) {
3365            let along = axis.cross(radial).normalize()?;
3366            return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
3367                sphere.center(),
3368                along,
3369                sphere.radius(),
3370            )?)]));
3371        }
3372        return Ok(
3373            off_axis_touch(sphere, torus).map(|p| vec![ExactIntersectionCurve::Points(vec![p])])
3374        );
3375    }
3376    let Some(crossings) = meridian_crossings(
3377        (0.0, offset.dot(axis), sphere.radius()),
3378        (torus.major_radius(), 0.0, torus.minor_radius()),
3379        scale,
3380    ) else {
3381        return Ok(None);
3382    };
3383    circles_about_axis(torus.center(), axis, &crossings).map(Some)
3384}
3385
3386/// The fewest and most steps along each branch of a loop a sphere cuts from
3387/// a torus: its curve is fitted through them alone, so a small loop takes
3388/// enough to hold the fit to the section.
3389const SPHERE_TORUS_LOOP_SAMPLES: (f64, f64) = (128.0, 1024.0);
3390
3391/// The section a sphere off a ring torus's axis cuts from it. In the
3392/// torus's frame let the sphere's centre sit at `(a, b, h)`, with
3393/// `s = hypot(a, b)` and `phi = atan2(b, a)`. The torus's point at `(u, v)`,
3394/// with `ρ = R + r·cos v`, lies on the sphere of radius `q` when
3395/// `ρ² − 2ρs·cos(u − phi) + s² + (r·sin v − h)² = q²`, so at each `v`
3396/// `cos(u − phi) = (R² + r² + h² + s² − q² + 2Rr·cos v − 2hr·sin v) / (2s·ρ)`.
3397/// `None` for a spindle torus, whose `ρ` reaches zero, or a sphere on the
3398/// axis, whose sections are circles about it.
3399fn sphere_torus_section<'a>(
3400    sphere: &SphericalSurface,
3401    torus: &'a ToroidalSurface,
3402) -> Option<TorusSection<'a, impl Fn(Point3) -> f64>> {
3403    let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
3404    let offset = sphere.center() - torus.center();
3405    let (a, b, h) = (
3406        offset.dot(torus.x_axis()),
3407        offset.dot(torus.y_axis()),
3408        offset.dot(torus.z_axis()),
3409    );
3410    let s = a.hypot(b);
3411    if small >= big || s <= 1e-9 * (big + radius) {
3412        return None;
3413    }
3414    let centre = sphere.center();
3415    Some(TorusSection {
3416        torus,
3417        phi: b.atan2(a),
3418        num: [
3419            big.madd(
3420                big,
3421                small.madd(small, h.madd(h, s.madd(s, -radius * radius))),
3422            ),
3423            2.0 * big * small,
3424            -2.0 * h * small,
3425        ],
3426        den: [2.0 * s * big, 2.0 * s * small],
3427        clearance: move |p: Point3| (p - centre).length() - radius,
3428        slack: 64.0 * f64::EPSILON * (big + small + radius + offset.length()),
3429    })
3430}
3431
3432/// How many times a loop's fitted curve may be refined where it strays.
3433const SPHERE_TORUS_FIT_ROUNDS: usize = 6;
3434
3435/// The curves a sphere off a ring torus's axis meets it in, each fitted
3436/// through the closed-form points of [`sphere_torus_section`] and every point
3437/// given its parameters on both surfaces, the sphere's first when
3438/// `sphere_first`. Halfway between each pair of points the curve must lie
3439/// within a quarter of the linear tolerance of both surfaces; where it
3440/// strays the section's own point there joins the fit. `None`, deferring to the marcher, for a
3441/// curve that still strays, or whose points do.
3442fn sphere_torus_curves(
3443    sphere: &SphericalSurface,
3444    torus: &ToroidalSurface,
3445    sphere_first: bool,
3446) -> Option<Vec<IntersectionCurve>> {
3447    let section = sphere_torus_section(sphere, torus)?;
3448    let tol = Tolerance::new().linear;
3449    let (big, small) = (torus.major_radius(), torus.minor_radius());
3450    // The centre's least and greatest distance to the torus: the ball meets
3451    // it whenever its radius lies between them. A section that comes out
3452    // empty for such a ball has lost its loops to rounding, so the marcher
3453    // takes it rather than the pair being called apart.
3454    let offset = sphere.center() - torus.center();
3455    let rise = offset.dot(torus.z_axis());
3456    let reach = (offset - torus.z_axis() * rise).length();
3457    let (nearest, farthest) = (
3458        ((reach - big).hypot(rise) - small).abs(),
3459        (reach + big).hypot(rise) + small,
3460    );
3461    let margin = 8.0 * f64::EPSILON * (big + small + offset.length() + sphere.radius());
3462    let crosses = sphere.radius() > nearest + margin && sphere.radius() < farthest - margin;
3463    let off = |p: Point3| {
3464        let local = p - torus.center();
3465        let (x, y, z) = (
3466            local.dot(torus.x_axis()),
3467            local.dot(torus.y_axis()),
3468            local.dot(torus.z_axis()),
3469        );
3470        let on_torus = (x.hypot(y) - big).hypot(z) - small;
3471        on_torus.abs().max((section.clearance)(p).abs())
3472    };
3473    // `acos` of a ratio near 1 loses digits a small ball on a large torus
3474    // needs, so each point steps onto the sphere across the section, along
3475    // the torus, the shortest way in its own measure.
3476    let centre = sphere.center();
3477    let polish = |q: IntersectionPoint| {
3478        let (mut u, mut v) = q.param1;
3479        let mut best = q;
3480        for _ in 0..4 {
3481            let gap = (section.clearance)(best.point);
3482            let (sin_u, cos_u) = u.sin_cos();
3483            let (sin_v, cos_v) = v.sin_cos();
3484            let rho = small.madd(cos_v, big);
3485            let outward = torus.x_axis() * cos_u + torus.y_axis() * sin_u;
3486            let p_u = (torus.y_axis() * cos_u - torus.x_axis() * sin_u) * rho;
3487            let p_v = outward * (-small * sin_v) + torus.z_axis() * (small * cos_v);
3488            let away = best.point - centre;
3489            let normal = away * (1.0 / away.length());
3490            let (g_u, g_v) = (normal.dot(p_u), normal.dot(p_v));
3491            let (w_u, w_v) = (g_u / (rho * rho), g_v / (small * small));
3492            let reach = g_u.madd(w_u, g_v * w_v);
3493            if reach <= f64::MIN_POSITIVE {
3494                break;
3495            }
3496            let next = section.point(gap.madd(-w_u / reach, u), gap.madd(-w_v / reach, v));
3497            if (section.clearance)(next.point).abs() >= gap.abs() {
3498                break;
3499            }
3500            (u, v) = next.param1;
3501            best = next;
3502        }
3503        best
3504    };
3505    let loops = section.loops(256, SPHERE_TORUS_LOOP_SAMPLES);
3506    if loops.is_empty() && crosses {
3507        return None;
3508    }
3509    let mut curves = Vec::new();
3510    for points in loops {
3511        let mut points: Vec<IntersectionPoint> = points.into_iter().map(polish).collect();
3512        if points.iter().any(|q| off(q.point) > tol) {
3513            return None;
3514        }
3515        // Samples past a turn that `acos` clamped onto the same `u` all step
3516        // to the turn itself.
3517        points.dedup_by(|b, a| (b.point - a.point).length() <= 1e-3 * tol);
3518        let mut rounds = 0;
3519        let curve = loop {
3520            let positions: Vec<Point3> = points.iter().map(|q| q.point).collect();
3521            let curve = interpolate(&positions, 3.min(positions.len() - 1)).ok()?;
3522            let params = crate::nurbs::fitting::chord_length_params(&positions);
3523            let strays: Vec<usize> = (0..positions.len() - 1)
3524                .filter(|&k| {
3525                    off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))) > 0.25 * tol
3526                })
3527                .collect();
3528            if strays.is_empty() {
3529                break curve;
3530            }
3531            if rounds == SPHERE_TORUS_FIT_ROUNDS {
3532                return None;
3533            }
3534            rounds += 1;
3535            for &k in strays.iter().rev() {
3536                let mid = polish(section.between(points[k].param1, points[k + 1].param1));
3537                if off(mid.point) > tol {
3538                    return None;
3539                }
3540                points.insert(k + 1, mid);
3541            }
3542        };
3543        for q in &mut points {
3544            let (on_sphere, on_torus) = (sphere.project_point(q.point), q.param1);
3545            (q.param1, q.param2) = if sphere_first {
3546                (on_sphere, on_torus)
3547            } else {
3548                (on_torus, on_sphere)
3549            };
3550        }
3551        curves.push(IntersectionCurve { curve, points });
3552    }
3553    Some(curves)
3554}
3555
3556/// Where a sphere off a ring torus's axis touches it at one point: from
3557/// outside the tube, from inside it, or holding the whole ring. The touch
3558/// sits over the core circle's point nearest the sphere's centre, at
3559/// `d_near`, or farthest from it, at `d_far`, and the sphere's radius is
3560/// then `d_near − r`, `r − d_near` or `d_far + r`. Each is the centre's
3561/// least or greatest distance to the torus, so the point is all the two
3562/// share. `None` unless the radius matches one to rounding.
3563fn off_axis_touch(sphere: &SphericalSurface, torus: &ToroidalSurface) -> Option<Point3> {
3564    let axis = torus.z_axis();
3565    let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
3566    let offset = sphere.center() - torus.center();
3567    let radial = offset - axis * offset.dot(axis);
3568    let out = radial * (1.0 / radial.length());
3569    let near = torus.center() + out * big;
3570    let far = torus.center() - out * big;
3571    let (to_near, to_far) = (sphere.center() - near, sphere.center() - far);
3572    let (d_near, d_far) = (to_near.length(), to_far.length());
3573    let slack = 64.0 * f64::EPSILON * (big + small + radius + offset.length());
3574    // A ball centred on the core circle meets the tube along a whole
3575    // meridian, not at a point.
3576    if d_near > slack
3577        && ((d_near - small - radius).abs() <= slack || (small - d_near - radius).abs() <= slack)
3578    {
3579        return Some(near + to_near * (small / d_near));
3580    }
3581    ((d_far + small - radius).abs() <= slack).then(|| far - to_far * (small / d_far))
3582}
3583
3584/// Exact coaxial cone-cone intersection: returns the shared circle.
3585///
3586/// Two cones that share an axis are concentric circles at every axial
3587/// station, so they meet only where their radii are equal. Each cone's
3588/// radius is linear in the axial coordinate `t` (measured along the shared
3589/// axis from cone 1's apex): `r1 = m1·t` and `r2 = m2·σ·(t − d2)`, where
3590/// `m_i = cot(half_angle_i)`, `σ = sign(axis2·axis1)`, and `d2` is cone 2's
3591/// apex position in that coordinate. Equating gives a single crossing `t*`
3592/// → one circle (the shared rim). The general marcher mishandles this case:
3593/// at the radii-crossing the surfaces are nearly tangent, so a grid-seeded
3594/// march fragments the clean circle into dozens of degenerate micro-curves.
3595///
3596/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
3597/// the cones do not meet (parallel radius lines or a crossing on the wrong
3598/// nappe), and `None` for the identical-cone overlap or a degenerate
3599/// (near-flat) cone — both of which fall through to the general path.
3600/// Parallel-but-offset axes with equal half-angle tangents reduce to a
3601/// radical-plane conic (`offset_parallel_cone_cone`); other offset
3602/// configurations defer to the marcher with `None`.
3603///
3604/// # Errors
3605///
3606/// Returns [`MathError`] if the shared-rim `Circle3D` cannot be constructed
3607/// (e.g. a non-finite center or radius from a malformed cone).
3608pub fn exact_cone_cone(
3609    c1: &ConicalSurface,
3610    c2: &ConicalSurface,
3611) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3612    let axis = c1.axis();
3613    let axis2 = c2.axis();
3614
3615    // Coaxial check: parallel axes and the second apex lies on the first axis.
3616    if axis.dot(axis2).abs() < 1.0 - 1e-10 {
3617        return Ok(None); // Non-coaxial: quartic curve, let the marcher handle.
3618    }
3619    let apex1 = c1.apex();
3620    let apex2 = c2.apex();
3621    let delta = apex2 - apex1;
3622    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3623    let along = delta_v.dot(axis);
3624    if (delta_v - axis * along).length() > 1e-8 {
3625        return offset_parallel_cone_cone(c1, c2);
3626    }
3627
3628    let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3629    if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
3630        return Ok(None); // Degenerate (near-flat) cone.
3631    }
3632    let m1 = c1.half_angle().cos() / s1;
3633    let m2 = c2.half_angle().cos() / s2;
3634    let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
3635    let d2 = along; // apex2 position along `axis`, measured from apex1.
3636
3637    let denom = m1 - m2 * sigma;
3638    if denom.abs() < 1e-12 {
3639        // Parallel radius lines: identical cones (coincident apex, same opening)
3640        // overlap — defer to the general/same-domain path; otherwise no meeting.
3641        if sigma > 0.0 && d2.abs() < 1e-9 {
3642            return Ok(None);
3643        }
3644        return Ok(Some(vec![]));
3645    }
3646
3647    let t_star = (-m2 * sigma * d2) / denom;
3648    let radius = m1 * t_star;
3649    if radius < 1e-12 {
3650        return Ok(Some(vec![])); // Crossing on the wrong nappe / no real circle.
3651    }
3652
3653    let center = Point3::new(
3654        apex1.x() + axis.x() * t_star,
3655        apex1.y() + axis.y() * t_star,
3656        apex1.z() + axis.z() * t_star,
3657    );
3658    let circle = Circle3D::new(center, axis, radius)?;
3659    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3660}
3661
3662/// Parallel-axis (or anti-parallel), offset-apex cones with equal half-angle
3663/// tangents: subtracting the two quadric equations cancels both the radial
3664/// and the axial quadratic terms (their coefficients depend only on
3665/// `tan²(half_angle)`), so every intersection point lies on a plane — the
3666/// degenerate member of the quadric pencil — and plane ∩ cone is an exact
3667/// conic. The gridfinity spacer lip fuse hits this exactly: opposed 45°
3668/// corner cones offset 0.25mm, which the marcher shreds into ~64 closed
3669/// micro-loops per pair (#1570). Unequal angles keep a genuine quadratic
3670/// term, and an unbounded section (hyperbola/parabola) has no closed-form
3671/// win over the marcher — both defer with `None`.
3672fn offset_parallel_cone_cone(
3673    c1: &ConicalSurface,
3674    c2: &ConicalSurface,
3675) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3676    if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
3677        return Ok(None); // Degenerate (near-flat) cone, as in the coaxial path.
3678    }
3679    let t1 = c1.half_angle().tan();
3680    let t2 = c2.half_angle().tan();
3681    if !t1.is_finite() || !t2.is_finite() {
3682        return Ok(None);
3683    }
3684    if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
3685        return Ok(None);
3686    }
3687
3688    let w = c1.axis();
3689    let apex1 = c1.apex();
3690    let apex2 = c2.apex();
3691    let delta = apex2 - apex1;
3692    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3693    let s = delta_v.dot(w);
3694    let tm = 0.5 * (t1 + t2);
3695    let k = 1.0 + tm * tm;
3696
3697    // In the apex1 frame each cone is |P|² − k(P·w)² = 0 (shifted by δ for
3698    // cone 2; the axis SIGN drops out since only (P·w)² appears). Their
3699    // difference: P·(2δ − 2ksw) = |δ|² − ks².
3700    let n = (delta_v - w * (k * s)) * 2.0;
3701    let n_len = n.length();
3702    if n_len < 1e-12 {
3703        return Ok(None);
3704    }
3705    let n_hat = n * (1.0 / n_len);
3706    let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
3707
3708    // `exact_plane_cone` already rejects sections on cone 1's phantom nappe;
3709    // cone 2's nappe must be checked here. A conic on the shared quadric
3710    // pencil cannot cross between nappes except exactly through apex 2, so
3711    // sampled quarter-points either all pass or all fail; a mixed verdict
3712    // means an apex-touching degeneracy — defer to the marcher.
3713    let axis2 = c2.axis();
3714    let scale = 1.0 + delta_v.length();
3715    let mut out = Vec::new();
3716    for curve in exact_plane_cone(c1, n_hat, d, 0.0)? {
3717        let samples: Vec<Point3> = match &curve {
3718            ExactIntersectionCurve::Circle(c) => (0..4)
3719                .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
3720                .collect(),
3721            ExactIntersectionCurve::Ellipse(e) => (0..4)
3722                .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
3723                .collect(),
3724            ExactIntersectionCurve::Points(_) => return Ok(None),
3725        };
3726        let on_real_nappe = |p: &Point3| {
3727            let rel = *p - apex2;
3728            Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
3729        };
3730        let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
3731        match hits {
3732            0 => {}
3733            4 => out.push(curve),
3734            _ => return Ok(None),
3735        }
3736    }
3737    Ok(Some(out))
3738}
3739
3740/// Exact coaxial cone-cylinder intersection: returns the shared circle.
3741///
3742/// A cone and a cylinder sharing an axis are concentric circles at every
3743/// axial station, so they meet only where the cone's radius equals the
3744/// cylinder's. The cone radius is linear in the axial coordinate `t` from its
3745/// apex (`r = m·t`, `m = cot(half_angle)`), the cylinder radius is the
3746/// constant `R`, so `m·t = R` gives a single crossing `t*` → one circle. This
3747/// is the gridfinity lip's top knife edge (inner tapered corner = cone, outer
3748/// corner = cylinder, concentric, radii matching at `Z_PEAK`); the general
3749/// marcher fragments that near-tangent contact into dozens of degenerate
3750/// micro-curves.
3751///
3752/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
3753/// the crossing degenerates to the apex, and `None` (defer to the marcher)
3754/// when the surfaces are not coaxial or the cone is near-flat / near-axial.
3755///
3756/// # Errors
3757///
3758/// Returns [`MathError`] if the shared `Circle3D` cannot be constructed.
3759pub fn exact_cone_cylinder(
3760    cone: &ConicalSurface,
3761    cyl: &CylindricalSurface,
3762) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3763    let axis = cone.axis();
3764    let cyl_axis = cyl.axis();
3765
3766    // Coaxial check: parallel axes and the cone apex on the cylinder's axis.
3767    if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
3768        return Ok(None);
3769    }
3770    let apex = cone.apex();
3771    let delta = apex - cyl.origin();
3772    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3773    let along = delta_v.dot(cyl_axis);
3774    if (delta_v - cyl_axis * along).length() > 1e-8 {
3775        return Ok(None);
3776    }
3777
3778    let s = cone.half_angle().sin();
3779    if s.abs() < 1e-12 {
3780        return Ok(None); // near-flat cone.
3781    }
3782    let m = cone.half_angle().cos() / s; // dr/dt along the cone axis.
3783    if m.abs() < 1e-12 {
3784        return Ok(None); // near-axial cone: radius ~constant.
3785    }
3786
3787    let t_star = cyl.radius() / m; // where the cone radius m·t equals R.
3788    if t_star.abs() < 1e-12 {
3789        return Ok(Some(vec![])); // crossing at the apex — no real circle.
3790    }
3791    let center = Point3::new(
3792        apex.x() + axis.x() * t_star,
3793        apex.y() + axis.y() * t_star,
3794        apex.z() + axis.z() * t_star,
3795    );
3796    let circle = Circle3D::new(center, axis, cyl.radius())?;
3797    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3798}
3799
3800/// The exact rational quadratic NURBS of the full ellipse `centre +
3801/// a·cos(t)·u + b·sin(t)·v` (a circle when `a == b`), starting at
3802/// `centre + a·u`: four quarter arcs, each with its corner weighted by
3803/// cos 45°.
3804fn conic_loop(centre: Point3, u: Vec3, v: Vec3, a: f64, b: f64) -> Result<NurbsCurve, MathError> {
3805    let w = std::f64::consts::FRAC_1_SQRT_2;
3806    let corners: [(f64, f64); 9] = [
3807        (1.0, 0.0),
3808        (1.0, 1.0),
3809        (0.0, 1.0),
3810        (-1.0, 1.0),
3811        (-1.0, 0.0),
3812        (-1.0, -1.0),
3813        (0.0, -1.0),
3814        (1.0, -1.0),
3815        (1.0, 0.0),
3816    ];
3817    let points = corners
3818        .iter()
3819        .map(|&(x, y)| centre + u * (a * x) + v * (b * y))
3820        .collect();
3821    let weights = vec![1.0, w, 1.0, w, 1.0, w, 1.0, w, 1.0];
3822    let knots = vec![
3823        0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3824    ];
3825    NurbsCurve::new(2, knots, points, weights)
3826}
3827
3828/// Two cones sharing an apex meet only along rulings through it. A
3829/// ruling's direction `d` makes each cone's angle with its axis, `d·aᵢ =
3830/// ±sin(half_angleᵢ)` (the half-angle runs from the radial plane), a line
3831/// that crosses the unit sphere twice, touches it where the cones are
3832/// tangent along one ruling, or misses it. Along `apex + t·d` the first
3833/// cone's `v` is `t` and the second's `±t`, so each ruling runs where both
3834/// faces' `v` ranges hold it, as a straight segment cut at the apex. Two
3835/// rulings closer than the linear tolerance across the faces are one.
3836///
3837/// `None` unless both ranges are given, the axes are not parallel (the
3838/// coaxial path's case), and the apexes coincide to rounding.
3839fn shared_apex_cones(
3840    c1: &ConicalSurface,
3841    c2: &ConicalSurface,
3842    v1: Option<(f64, f64)>,
3843    v2: Option<(f64, f64)>,
3844) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3845    let (Some(v1), Some(v2)) = (v1, v2) else {
3846        return Ok(None);
3847    };
3848    let (a1, a2, apex) = (c1.axis(), c2.axis(), c1.apex());
3849    let across = a1.cross(a2);
3850    let sin = across.length();
3851    if sin < 1e-9 {
3852        return Ok(None);
3853    }
3854    let reach = v1.0.abs().max(v1.1.abs()).max(v2.0.abs()).max(v2.1.abs());
3855    let scale = reach.max((apex - Point3::new(0.0, 0.0, 0.0)).length());
3856    if (c2.apex() - apex).length() > 64.0 * f64::EPSILON * scale {
3857        return Ok(None);
3858    }
3859    let normal = across * (1.0 / sin);
3860    let tol = Tolerance::new().linear;
3861    // A ruling's part across the first axis is `(t2 − s1·cos) / sin`, whose
3862    // rounding grows as the axes close up; past a tenth of the tolerance
3863    // over the faces, the pair is left to the marcher.
3864    if f64::EPSILON * reach > 0.1 * tol * sin {
3865        return Ok(None);
3866    }
3867    // The second axis's part across the first, a unit vector.
3868    let toward = normal.cross(a1);
3869    let cos = a1.dot(a2);
3870    let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3871    // `evaluate` turns its radial direction round for negative `v`.
3872    let params = |cone: &ConicalSurface, p: Point3| {
3873        let (u, v) = cone.project_point(p);
3874        if v < 0.0 {
3875            ((u + std::f64::consts::PI).rem_euclid(TAU), v)
3876        } else {
3877            (u, v)
3878        }
3879    };
3880    let mut curves = Vec::new();
3881    for nappe in [1.0, -1.0] {
3882        let t2 = nappe * s2;
3883        let side = cos.madd(-s1, t2) / sin;
3884        let foot = a1 * s1 + toward * side;
3885        let lift_sq = s1.madd(-s1, side.madd(-side, 1.0));
3886        let rounding = 4.0 * f64::EPSILON;
3887        let lifts = if lift_sq.abs() <= rounding {
3888            // Within rounding of touching: the rulings that rounding could
3889            // hide part by up to `√(2·rounding)` radians, taken as one while
3890            // that stays within ten tolerances over the faces, and beyond
3891            // it not settled here.
3892            if (2.0 * rounding).sqrt() * reach > 10.0 * tol {
3893                return Ok(None);
3894            }
3895            vec![0.0]
3896        } else if lift_sq < 0.0 {
3897            Vec::new()
3898        } else if 2.0 * lift_sq.sqrt() * reach <= tol {
3899            vec![0.0]
3900        } else {
3901            vec![lift_sq.sqrt(), -lift_sq.sqrt()]
3902        };
3903        let along2 = if nappe > 0.0 { v2 } else { (-v2.1, -v2.0) };
3904        let (lo, hi) = (v1.0.max(along2.0), v1.1.min(along2.1));
3905        if hi - lo <= tol {
3906            continue;
3907        }
3908        for lift in lifts {
3909            let d = (foot + normal * lift).normalize()?;
3910            let pieces = if lo < 0.0 && hi > 0.0 {
3911                vec![(lo, 0.0), (0.0, hi)]
3912            } else {
3913                vec![(lo, hi)]
3914            };
3915            for (from, to) in pieces {
3916                curves.push(ruling_segment(apex + d * from, apex + d * to, |p| {
3917                    (params(c1, p), params(c2, p))
3918                })?);
3919            }
3920        }
3921    }
3922    Ok(Some(curves))
3923}
3924
3925/// Two cylinders of one radius whose axes cross meet in two ellipses, one
3926/// in each plane through the crossing that bisects the axes: a point lies
3927/// as far from both axes where its offsets along them are equal or
3928/// opposite. Both ellipses have their minor axis, of the radius, along the
3929/// axes' common normal, and meet at its two ends. They come back as two
3930/// closed loops, as the first cylinder's rulings pair them: the halves of
3931/// both ellipses on one side of the crossing along its axis, then on the
3932/// other, each exact, rational, and cornered where its halves meet. One
3933/// loop starts at each end of the common normal.
3934///
3935/// `None` unless the radii match and the axes cross to rounding: axes that
3936/// miss by `δ` part the curves at the crossings by about `√(δ·r)`.
3937fn crossing_equal_cylinders(
3938    c1: &CylindricalSurface,
3939    c2: &CylindricalSurface,
3940) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3941    let (d1, d2, r) = (c1.axis(), c2.axis(), c1.radius());
3942    if (c2.radius() - r).abs() > 8.0 * f64::EPSILON * r {
3943        return Ok(None);
3944    }
3945    // An ellipse's semi-major axis is `2r / |d1 ∓ d2|`. Rounding the axes
3946    // turns its major axis by about `ε / |d1 ∓ d2|`, which moves its far
3947    // vertices by `2rε / |d1 ∓ d2|²`; axes nearer parallel than keeps that
3948    // well inside the tolerance are left to the rulings.
3949    let bisectors = [d1 - d2, d1 + d2];
3950    let tol = Tolerance::new().linear;
3951    if bisectors
3952        .iter()
3953        .any(|b| 2.0 * r * f64::EPSILON > 1e-3 * tol * b.dot(*b))
3954    {
3955        return Ok(None);
3956    }
3957    let across = d1.cross(d2);
3958    let sin = across.length();
3959    let normal = across * (1.0 / sin);
3960    let w = c1.origin() - c2.origin();
3961    let cos = d1.dot(d2);
3962    let along = cos.madd(d2.dot(w), -d1.dot(w)) / (sin * sin);
3963    let centre = c1.origin() + d1 * along;
3964    // The miss is read at the crossing's own scale: origins far along
3965    // their axes leave it more rounding than that, and are left to the
3966    // rulings too.
3967    let scale = r.max((centre - Point3::new(0.0, 0.0, 0.0)).length());
3968    if w.dot(normal).abs() > 64.0 * f64::EPSILON * scale {
3969        return Ok(None);
3970    }
3971    // Each ellipse's major axis, turned to lean along the first axis, and
3972    // its semi-major axis.
3973    let majors = bisectors.map(|bisector| {
3974        let length = bisector.length();
3975        let major = (bisector * (1.0 / length)).cross(normal);
3976        let major = if major.dot(d1) < 0.0 { -major } else { major };
3977        (major, 2.0 * r / length)
3978    });
3979    let corner = std::f64::consts::FRAC_1_SQRT_2;
3980    let half = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)];
3981    let mut curves = Vec::with_capacity(2);
3982    for side in [1.0, -1.0] {
3983        let [(m1, a1), (m2, a2)] = majors;
3984        let out = half
3985            .iter()
3986            .map(|&(x, y)| centre + normal * (side * r * x) + m1 * (side * a1 * y));
3987        let back = half[1..]
3988            .iter()
3989            .map(|&(x, y)| centre - normal * (side * r * x) + m2 * (side * a2 * y));
3990        let curve = NurbsCurve::new(
3991            2,
3992            vec![
3993                0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3994            ],
3995            out.chain(back).collect(),
3996            vec![1.0, corner, 1.0, corner, 1.0, corner, 1.0, corner, 1.0],
3997        )?;
3998        #[allow(clippy::cast_precision_loss)]
3999        let points = (0..=32)
4000            .map(|i| {
4001                let point = curve.evaluate(i as f64 / 32.0);
4002                IntersectionPoint {
4003                    point,
4004                    param1: c1.project_point(point),
4005                    param2: c2.project_point(point),
4006                }
4007            })
4008            .collect();
4009        curves.push(IntersectionCurve { curve, points });
4010    }
4011    Ok(Some(curves))
4012}
4013
4014/// Algebraic cone-cone intersection (NURBS form for the general bounded
4015/// path). Delegates to [`exact_cone_cone`] and returns each exact conic
4016/// (coaxial circle or offset-parallel radical-plane ellipse) as an exact
4017/// rational NURBS `IntersectionCurve` with sample points along it, mirroring
4018/// the sphere-cylinder algebraic path. phase FF prefers the exact circle form
4019/// directly (so the section edge links to the coincident boundary), but a
4020/// caller of `intersect_analytic_analytic_bounded` still gets one clean
4021/// curve instead of the marcher's fragments.
4022fn algebraic_cone_cone(
4023    c1: &ConicalSurface,
4024    c2: &ConicalSurface,
4025) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4026    let Some(exacts) = exact_cone_cone(c1, c2)? else {
4027        return Ok(None);
4028    };
4029    let mut curves = Vec::new();
4030    for exact in exacts {
4031        let n_samples = 33;
4032        let mut points = Vec::with_capacity(n_samples);
4033        #[allow(clippy::cast_precision_loss)]
4034        for i in 0..n_samples {
4035            let theta = TAU * i as f64 / (n_samples - 1) as f64;
4036            let pt = match &exact {
4037                ExactIntersectionCurve::Circle(circle) => {
4038                    crate::traits::ParametricCurve::evaluate(circle, theta)
4039                }
4040                ExactIntersectionCurve::Ellipse(ellipse) => {
4041                    crate::traits::ParametricCurve::evaluate(ellipse, theta)
4042                }
4043                ExactIntersectionCurve::Points(_) => break,
4044            };
4045            points.push(IntersectionPoint {
4046                point: pt,
4047                param1: (0.0, 0.0),
4048                param2: (0.0, 0.0),
4049            });
4050        }
4051        let curve = match &exact {
4052            ExactIntersectionCurve::Circle(c) => {
4053                conic_loop(c.center(), c.u_axis(), c.v_axis(), c.radius(), c.radius())?
4054            }
4055            ExactIntersectionCurve::Ellipse(e) => conic_loop(
4056                e.center(),
4057                e.u_axis(),
4058                e.v_axis(),
4059                e.semi_major(),
4060                e.semi_minor(),
4061            )?,
4062            ExactIntersectionCurve::Points(_) => continue,
4063        };
4064        curves.push(IntersectionCurve { curve, points });
4065    }
4066    Ok(Some(curves))
4067}
4068
4069/// Exact coaxial sphere-cylinder intersection: returns the shared circle(s).
4070///
4071/// A sphere of radius `R` centered at `C` and a cylinder of radius `r` whose
4072/// axis passes through `C` meet in concentric circles of radius `r` at the
4073/// axial stations where `sqrt(R² − z²) = r`, i.e. `z = ±sqrt(R² − r²)`
4074/// measured from `C` along the axis. A proper crossing yields two circles; a
4075/// tangent contact (`r = R`) yields one; a cylinder wider than the sphere, or
4076/// a non-coaxial configuration (quartic curve), yields none/defers.
4077///
4078/// Mirrors [`exact_cone_cylinder`] so phase FF can emit the section as an
4079/// exact `Circle3D` (which the closed-circle split + seam adoption recognise)
4080/// rather than the marcher's NURBS fragments.
4081///
4082/// Returns `Some(vec![..])` (0, 1, or 2 circles) for the coaxial case, and
4083/// `None` (defer to the general marcher) when the axes are not coaxial.
4084///
4085/// # Errors
4086///
4087/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
4088pub fn exact_sphere_cylinder(
4089    sphere: &SphericalSurface,
4090    cyl: &CylindricalSurface,
4091) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
4092    let sc = sphere.center();
4093    let r_sphere = sphere.radius();
4094    let co = cyl.origin();
4095    let axis = cyl.axis();
4096    let r_cyl = cyl.radius();
4097
4098    // Project sphere center onto the cylinder axis.
4099    let delta = sc - co;
4100    let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
4101    let along = delta_vec.dot(axis);
4102    let perp_vec = delta_vec - axis * along;
4103    let d_perp = perp_vec.length();
4104
4105    // Non-coaxial sphere-cylinder intersections produce quartic curves;
4106    // defer those to the general marcher.
4107    if d_perp > 1e-7 {
4108        return Ok(None);
4109    }
4110
4111    // Coaxial: the sphere center lies on the cylinder axis. No real circle
4112    // when the cylinder is wider than the sphere or they are tangent-internal.
4113    if r_cyl > r_sphere + 1e-10 {
4114        return Ok(Some(vec![]));
4115    }
4116    let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
4117    if z_sq < 0.0 {
4118        return Ok(Some(vec![]));
4119    }
4120    let z = z_sq.sqrt();
4121
4122    // The sphere center projected onto the axis is the midpoint of the two
4123    // section circles, each offset by ±z along the axis with radius `r_cyl`.
4124    let center_axis_pt = Point3::new(
4125        co.x() + axis.x() * along,
4126        co.y() + axis.y() * along,
4127        co.z() + axis.z() * along,
4128    );
4129
4130    let mut circles = Vec::new();
4131    let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
4132    for &z_offset in offsets {
4133        let center = Point3::new(
4134            center_axis_pt.x() + axis.x() * z_offset,
4135            center_axis_pt.y() + axis.y() * z_offset,
4136            center_axis_pt.z() + axis.z() * z_offset,
4137        );
4138        let circle = Circle3D::new(center, axis, r_cyl)?;
4139        circles.push(ExactIntersectionCurve::Circle(circle));
4140    }
4141    Ok(Some(circles))
4142}
4143
4144/// Exact coaxial cone-sphere intersection: the shared circles.
4145///
4146/// When the cone's axis runs through the sphere's centre `C`, every generator
4147/// `apex + v g` (`g` a unit direction, `v` the distance from the apex) has
4148/// the same `h = g·(apex − C)`, so all of them meet the sphere at the same
4149/// roots of `v² + 2hv + |apex − C|² − R² = 0`. Each root ahead of the apex is
4150/// a circle of radius `v cos a` at `v sin a` along the axis: two for a ball
4151/// the cone passes through, one for a ball that swallows the apex, passes
4152/// through it or touches the wall, none for a ball the cone misses or that
4153/// sits inside it clear of the wall.
4154///
4155/// Returns `Some(vec![..])` for a coaxial pair and `None` (the ruling trace
4156/// or the marcher) otherwise.
4157///
4158/// # Errors
4159///
4160/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
4161pub fn exact_cone_sphere(
4162    cone: &ConicalSurface,
4163    sphere: &SphericalSurface,
4164) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
4165    let offset = cone.apex() - sphere.center();
4166    let along = offset.dot(cone.axis());
4167    if (offset - cone.axis() * along).length() > 1e-7 {
4168        return Ok(None);
4169    }
4170    let lin_tol = Tolerance::new().linear;
4171    let (sin_a, cos_a) = cone.half_angle().sin_cos();
4172    let (far_sq, radius_sq) = (offset.dot(offset), sphere.radius() * sphere.radius());
4173    let b = 2.0 * sin_a * along;
4174    let (disc, far, near) = ruling_quadratic(1.0, b, far_sq - radius_sq);
4175    // At a tangent ball `b² − 4c` cancels to a few ulps of its terms, which
4176    // can land below zero: that is a touch, not a miss.
4177    let noise = 16.0 * f64::EPSILON * 4.0f64.madd(far_sq + radius_sq, b * b);
4178    if disc < -noise {
4179        return Ok(Some(vec![]));
4180    }
4181    let roots: &[f64] = if far - near < lin_tol {
4182        &[far]
4183    } else {
4184        &[near, far]
4185    };
4186    let mut circles = Vec::new();
4187    for &v in roots {
4188        if v * cos_a > lin_tol {
4189            let centre = cone.apex() + cone.axis() * (v * sin_a);
4190            let circle = Circle3D::new(centre, cone.axis(), v * cos_a)?;
4191            circles.push(ExactIntersectionCurve::Circle(circle));
4192        }
4193    }
4194    Ok(Some(circles))
4195}
4196
4197/// Algebraic sphere-cylinder intersection (NURBS form for the general bounded
4198/// path). A coaxial pair delegates to [`exact_sphere_cylinder`] and returns
4199/// each exact circle as an exact rational NURBS `IntersectionCurve`. phase FF
4200/// prefers the exact circle form directly (so the section edge links to the
4201/// coincident boundary and the closed-circle splitter can carve the spherical
4202/// band), but a caller of `intersect_analytic_analytic_bounded` still gets
4203/// clean curves instead of the marcher's fragments. Any other pair is traced
4204/// along the cylinder's rulings ([`off_axis_sphere_cylinder`]).
4205fn algebraic_sphere_cylinder(
4206    sphere: &SphericalSurface,
4207    cyl: &CylindricalSurface,
4208    sphere_first: bool,
4209) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4210    let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
4211        return Ok(off_axis_sphere_cylinder(sphere, cyl, sphere_first));
4212    };
4213
4214    let mut curves = Vec::new();
4215    for exact in exacts {
4216        let ExactIntersectionCurve::Circle(circle) = exact else {
4217            continue;
4218        };
4219        let n_samples = 33;
4220        let mut points = Vec::with_capacity(n_samples);
4221        #[allow(clippy::cast_precision_loss)]
4222        for i in 0..n_samples {
4223            let theta = TAU * i as f64 / (n_samples - 1) as f64;
4224            let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
4225            let (param1, param2) = in_order(
4226                sphere.project_point(pt),
4227                cyl.project_point(pt),
4228                sphere_first,
4229            );
4230            points.push(IntersectionPoint {
4231                point: pt,
4232                param1,
4233                param2,
4234            });
4235        }
4236        let r = circle.radius();
4237        let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
4238        curves.push(IntersectionCurve { curve, points });
4239    }
4240
4241    Ok(Some(curves))
4242}
4243
4244/// A sphere and a cylinder whose axis misses the sphere's centre (a drill
4245/// entering a ball off its axis), traced along the cylinder's rulings: the
4246/// ruling `c(u) + v·a` meets the sphere where `v² + 2(q·a)·v + |q|² − R² = 0`,
4247/// with `q = c(u) − C`. When every ruling meets the sphere (the cylinder
4248/// passes wholly through it) the roots trace an entry and an exit loop;
4249/// otherwise each window of meeting rulings carries one loop. `Some(empty)`
4250/// when the two cannot meet, `None` when the sampling misses a window
4251/// narrower than itself.
4252fn off_axis_sphere_cylinder(
4253    sphere: &SphericalSurface,
4254    cyl: &CylindricalSurface,
4255    sphere_first: bool,
4256) -> Option<Vec<IntersectionCurve>> {
4257    let (centre, radius) = (sphere.center(), sphere.radius());
4258    let axis = cyl.axis();
4259    let offset = centre - cyl.origin();
4260    let axis_distance = (offset - axis * offset.dot(axis)).length();
4261    let lin_tol = Tolerance::new().linear;
4262    if axis_distance > radius + cyl.radius() + lin_tol
4263        || axis_distance + radius < cyl.radius() - lin_tol
4264    {
4265        return Some(Vec::new());
4266    }
4267    let roots = |u: f64| {
4268        let q = cyl.evaluate(u, 0.0) - centre;
4269        ruling_quadratic(1.0, 2.0 * q.dot(axis), q.dot(q) - radius * radius)
4270    };
4271    let samples = ruling_samples(cyl, &roots);
4272    let loops = if samples.iter().all(Option::is_some) {
4273        closed_ruling_loops(cyl, &roots, &samples)
4274    } else {
4275        partial_ruling_loops(cyl, &roots, &samples)
4276    };
4277    if loops.is_empty() {
4278        return None;
4279    }
4280    Some(fit_ruling_loops(&loops, |p| {
4281        in_order(sphere.project_point(p), cyl.project_point(p), sphere_first)
4282    }))
4283}
4284
4285/// Parameters on the pair's first and second surfaces, from those on `a`
4286/// and `b` and whether `a` came first.
4287const fn in_order(a: (f64, f64), b: (f64, f64), a_first: bool) -> ((f64, f64), (f64, f64)) {
4288    if a_first { (a, b) } else { (b, a) }
4289}
4290
4291/// Two cylinders whose axes are parallel but apart meet along rulings:
4292/// every plane across the axes cuts them in two circles `d` apart, which
4293/// cross in two points, touch in one, or miss, alike in every plane. Each
4294/// crossing sweeps a ruling, cut to the stretch of axis both faces' `v`
4295/// ranges share. Two crossings closer than the linear tolerance are the one
4296/// where the circles touch, side by side or one inside the other. `None`
4297/// (the next solver's case) when neither range is known, since a ruling has
4298/// no ends of its own, or when a ruling's end strays off the second
4299/// cylinder, its axis leaning off the first's by more than the span allows.
4300fn parallel_cylinders(
4301    c1: &CylindricalSurface,
4302    c2: &CylindricalSurface,
4303    v_range_1: Option<(f64, f64)>,
4304    v_range_2: Option<(f64, f64)>,
4305) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4306    let axis = c1.axis();
4307    let delta = c2.origin() - c1.origin();
4308    let along = delta.dot(axis);
4309    let across = delta - axis * along;
4310    let d = across.length();
4311    let (r1, r2) = (c1.radius(), c2.radius());
4312    // The second face's range, measured along the first one's axis.
4313    let flip = c2.axis().dot(axis);
4314    let ranges = [
4315        v_range_1,
4316        v_range_2.map(|(a, b)| (along + a * flip, along + b * flip)),
4317    ];
4318    let (lo, hi) = ranges
4319        .into_iter()
4320        .flatten()
4321        .fold((f64::NEG_INFINITY, f64::INFINITY), |(lo, hi), (a, b)| {
4322            (lo.max(a.min(b)), hi.min(a.max(b)))
4323        });
4324    if !lo.is_finite() || !hi.is_finite() {
4325        return Ok(None);
4326    }
4327    let rounding = 8.0 * f64::EPSILON * (r1 + r2 + d);
4328    if d > r1 + r2 + rounding || d < (r1 - r2).abs() - rounding || hi <= lo {
4329        return Ok(Some(Vec::new()));
4330    }
4331    let toward = across * (1.0 / d);
4332    let side = axis.cross(toward);
4333    let x = r2.madd(-r2, d.madd(d, r1 * r1)) / (2.0 * d);
4334    let y = r1.madd(r1, -(x * x)).max(0.0).sqrt();
4335    let linear = Tolerance::new().linear;
4336    let feet = if 2.0 * y <= linear {
4337        vec![toward * x]
4338    } else {
4339        vec![toward * x + side * y, toward * x - side * y]
4340    };
4341    let on_second = |p: Point3| {
4342        let w = p - c2.origin();
4343        ((w - c2.axis() * w.dot(c2.axis())).length() - r2).abs() <= linear
4344    };
4345    let mut rulings = Vec::with_capacity(feet.len());
4346    for foot in feet {
4347        let base = c1.origin() + foot;
4348        let (from, to) = (base + axis * lo, base + axis * hi);
4349        if !on_second(from) || !on_second(to) {
4350            return Ok(None);
4351        }
4352        rulings.push(ruling_segment(from, to, |p| {
4353            (c1.project_point(p), c2.project_point(p))
4354        })?);
4355    }
4356    Ok(Some(rulings))
4357}
4358
4359/// A straight intersection curve from `from` to `to`, carrying its ends and
4360/// middle as points.
4361fn ruling_segment(
4362    from: Point3,
4363    to: Point3,
4364    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
4365) -> Result<IntersectionCurve, MathError> {
4366    let curve = NurbsCurve::new(1, vec![0.0, 0.0, 1.0, 1.0], vec![from, to], vec![1.0, 1.0])?;
4367    let points = [from, from + (to - from) * 0.5, to]
4368        .into_iter()
4369        .map(|point| {
4370            let (param1, param2) = params(point);
4371            IntersectionPoint {
4372                point,
4373                param1,
4374                param2,
4375            }
4376        })
4377        .collect();
4378    Ok(IntersectionCurve { curve, points })
4379}
4380
4381/// Algebraic cylinder-cylinder intersection for non-coaxial cylinders.
4382///
4383/// For two cylinders with axes that are NOT parallel, the intersection
4384/// consists of up to two closed space curves. These are found by
4385/// parameterizing one cylinder's angular coordinate `u ∈ [0, 2π]` and
4386/// solving a quadratic in the axial parameter `v` to find where each
4387/// "ring" of cylinder A sits on cylinder B.
4388///
4389/// The quadratic is:
4390///   `v²·(1 - α²) + 2v·(q·a₁ - α·q·a₂) + (|q|² - (q·a₂)² - r₂²) = 0`
4391/// where `α = a₁·a₂`, `q(u)` is the radial point on cylinder 1 minus
4392/// cylinder 2's origin, `a₁`/`a₂` are the cylinder axes, and `r₂` is
4393/// cylinder 2's radius.
4394#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
4395fn algebraic_cylinder_cylinder(
4396    c1: &CylindricalSurface,
4397    c2: &CylindricalSurface,
4398) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4399    if let Some(halves) = crossing_equal_cylinders(c1, c2)? {
4400        return Ok(Some(halves));
4401    }
4402    let alpha = c1.axis().dot(c2.axis());
4403    let a_coeff = 1.0 - alpha * alpha;
4404
4405    // Should only be called for non-parallel axes.
4406    if a_coeff.abs() < 1e-12 {
4407        return Ok(None);
4408    }
4409
4410    let r1 = c1.radius();
4411    let r2 = c2.radius();
4412    let o1 = c1.origin();
4413    let o2 = c2.origin();
4414    let a1 = c1.axis();
4415    let a2 = c2.axis();
4416
4417    // Separation check: distance between axes vs sum of radii.
4418    // Closest approach of two skew lines:
4419    let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
4420    let cross = a1.cross(a2);
4421    let cross_len = cross.length();
4422    if cross_len > 1e-12 {
4423        let axis_dist = delta.dot(cross).abs() / cross_len;
4424        if axis_dist > r1 + r2 + Tolerance::new().linear {
4425            return Ok(Some(vec![])); // No intersection
4426        }
4427    }
4428
4429    // Solve every ruling of one cylinder against the other. When EVERY
4430    // ruling of the swept cylinder meets the other (the thinner of two
4431    // crossing tubes), the two roots trace the curve's two closed loops.
4432    // Swept the other way only a window of rulings meets, and each root
4433    // traces an open arc of one loop.
4434    let roots = |sweep: &CylindricalSurface, other: &CylindricalSurface| {
4435        let (o, a, radius) = (other.origin(), other.axis(), other.radius());
4436        let alpha = sweep.axis().dot(a);
4437        let quad = 1.0 - alpha * alpha;
4438        let (axis, sweep) = (sweep.axis(), sweep.clone());
4439        move |u: f64| {
4440            let q = sweep.evaluate(u, 0.0) - o;
4441            let (q_a1, q_a2) = (q.dot(axis), q.dot(a));
4442            let b = 2.0 * (q_a1 - alpha * q_a2);
4443            let c = q.dot(q) - q_a2 * q_a2 - radius * radius;
4444            ruling_quadratic(quad, b, c)
4445        }
4446    };
4447    let (roots1, roots2) = (roots(c1, c2), roots(c2, c1));
4448    let samples1 = ruling_samples(c1, &roots1);
4449    let loops = if samples1.iter().all(Option::is_some) {
4450        closed_ruling_loops(c1, &roots1, &samples1)
4451    } else {
4452        let samples2 = ruling_samples(c2, &roots2);
4453        if samples2.iter().all(Option::is_some) {
4454            closed_ruling_loops(c2, &roots2, &samples2)
4455        } else if samples1.iter().any(Option::is_some) {
4456            partial_ruling_loops(c1, &roots1, &samples1)
4457        } else {
4458            partial_ruling_loops(c2, &roots2, &samples2)
4459        }
4460    };
4461    if loops.is_empty() {
4462        return Ok(None);
4463    }
4464    Ok(Some(fit_ruling_loops(&loops, |p| {
4465        (c1.project_point(p), c2.project_point(p))
4466    })))
4467}
4468
4469/// A cone and a cylinder whose axes are not parallel, traced along the
4470/// cylinder's rulings. A ruling `q + t w` meets the cone's double quadric
4471/// `|p - apex|^2 = h^2 / sin^2(half_angle)`, with `h` the offset along the
4472/// cone's axis, where a quadratic in `t` vanishes. `None` (the marcher's
4473/// case) when a ruling meets the far nappe, where no cone face lies, when
4474/// the rulings run along the cone's generators, or when no ruling meets it.
4475fn ruling_cone_cylinder(
4476    cone: &ConicalSurface,
4477    cyl: &CylindricalSurface,
4478    cone_first: bool,
4479) -> Option<Vec<IntersectionCurve>> {
4480    let (sin_t, cos_t) = cone.half_angle().sin_cos();
4481    if sin_t < 1e-12 || cos_t < 1e-12 {
4482        return None;
4483    }
4484    let (apex, d, w) = (cone.apex(), cone.axis(), cyl.axis());
4485    let s = 1.0 / (sin_t * sin_t);
4486    let alpha = w.dot(d);
4487    let quad = 1.0 - s * alpha * alpha;
4488    if quad.abs() < 1e-9 {
4489        return None;
4490    }
4491    let roots = |u: f64| {
4492        let delta = cyl.evaluate(u, 0.0) - apex;
4493        let (dd, dw) = (delta.dot(d), delta.dot(w));
4494        let b = 2.0 * (dw - s * dd * alpha);
4495        let c = delta.dot(delta) - s * dd * dd;
4496        ruling_quadratic(quad, b, c)
4497    };
4498    let lin_tol = Tolerance::new().linear;
4499    let far_nappe = (0..WINDOW_SCAN * RULING_SAMPLES).any(|k| {
4500        #[allow(clippy::cast_precision_loss)]
4501        let u = TAU * (k as f64 + 0.5) / (WINDOW_SCAN * RULING_SAMPLES) as f64;
4502        let (disc, vp, vm) = roots(u);
4503        disc >= -lin_tol
4504            && [vp, vm]
4505                .iter()
4506                .any(|&t| (cyl.evaluate(u, t) - apex).dot(d) < -lin_tol)
4507    });
4508    if far_nappe {
4509        return None;
4510    }
4511    let samples = ruling_samples(cyl, &roots);
4512    // The samples that truly meet the cone. One that the tolerance alone
4513    // admits lies past its window's end: the end bisected from it, and a
4514    // loop traced from it, lie off the cone.
4515    let meeting: Vec<Option<(Point3, Point3)>> = samples
4516        .iter()
4517        .enumerate()
4518        .map(|(i, &pair)| pair.filter(|_| roots(ruling_u(i)).0 >= 0.0))
4519        .collect();
4520    // A window of meeting rulings that no sample truly meets would vanish
4521    // (a cone's tip just through the wall) while the others still made
4522    // loops; a finer scan finds every window, and one with no such sample
4523    // goes to the marcher. A window with one is sampled afresh between its
4524    // ends, however few samples it holds.
4525    let scan = WINDOW_SCAN * RULING_SAMPLES;
4526    #[allow(clippy::cast_precision_loss)]
4527    let scan_u = |k: usize| TAU * (k as f64 + 0.5) / scan as f64;
4528    let discs: Vec<f64> = (0..scan).map(|k| roots(scan_u(k)).0).collect();
4529    // A window narrower than the scan's step lies between two scan points
4530    // that miss, where the discriminant peaks: each such peak is found, and
4531    // one that reaches the tolerance goes to the marcher.
4532    for k in 0..scan {
4533        let (before, here, after) = (
4534            discs[(k + scan - 1) % scan],
4535            discs[k],
4536            discs[(k + 1) % scan],
4537        );
4538        if here >= -lin_tol || here < before || here < after {
4539            continue;
4540        }
4541        let (mut lo, mut hi) = (scan_u(k) - TAU / scan as f64, scan_u(k) + TAU / scan as f64);
4542        for _ in 0..100 {
4543            let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4544            if roots(a).0 < roots(b).0 {
4545                lo = a;
4546            } else {
4547                hi = b;
4548            }
4549        }
4550        if roots(f64::midpoint(lo, hi)).0 >= -lin_tol {
4551            return None;
4552        }
4553    }
4554    // Ruling sample `i` lies midway between scan points
4555    // `WINDOW_SCAN i + 7` and `WINDOW_SCAN i + 8`.
4556    let meets = |k: usize| discs[k % scan] >= -lin_tol;
4557    if let Some(start) = (0..scan).find(|&k| !meets(k)) {
4558        let mut k = start;
4559        while k < start + scan {
4560            if !meets(k) {
4561                k += 1;
4562                continue;
4563            }
4564            let first = k;
4565            while k < start + scan && meets(k) {
4566                k += 1;
4567            }
4568            let sampled = (first..k).any(|j| {
4569                j % WINDOW_SCAN == WINDOW_SCAN / 2 - 1
4570                    && meeting[(j / WINDOW_SCAN) % RULING_SAMPLES].is_some()
4571            });
4572            if !sampled {
4573                return None;
4574            }
4575        }
4576    }
4577    let loops = if samples.iter().all(Option::is_some) {
4578        closed_ruling_loops(cyl, &roots, &samples)
4579    } else {
4580        partial_ruling_loops(cyl, &roots, &meeting)
4581    };
4582    if loops.is_empty() {
4583        return None;
4584    }
4585    Some(fit_ruling_loops(&loops, |p| {
4586        in_order(cone.project_point(p), cyl.project_point(p), cone_first)
4587    }))
4588}
4589
4590/// A torus and a cylinder whose axes are not parallel, where every ruling
4591/// of the cylinder meets the torus the same nonzero even number of times (a
4592/// rod through the ring's tube): a ruling meets the torus where a quartic in
4593/// its parameter vanishes, and each of its roots, taken in order, sweeps one
4594/// closed loop around the cylinder. `None` (the marcher's case) when the
4595/// count varies between rulings, where the curve turns back between them,
4596/// checked on a scan finer than the sampling so a narrow window of missing
4597/// rulings is not stepped over, and for a spindle torus, whose quartic also
4598/// holds its inner lemon.
4599fn ruling_torus_cylinder(
4600    torus: &ToroidalSurface,
4601    cyl: &CylindricalSurface,
4602    torus_first: bool,
4603) -> Option<Vec<IntersectionCurve>> {
4604    if cyl.axis().dot(torus.z_axis()).abs() > 1.0 - 1e-9
4605        || torus.minor_radius() >= torus.major_radius()
4606    {
4607        return None;
4608    }
4609    let roots = |u: f64| intersect_line_torus(torus, cyl.evaluate(u, 0.0), cyl.axis());
4610    let rows: Vec<Vec<f64>> = (0..RULING_SAMPLES).map(|i| roots(ruling_u(i))).collect();
4611    let count = rows[0].len();
4612    let scan = WINDOW_SCAN * RULING_SAMPLES;
4613    #[allow(clippy::cast_precision_loss)]
4614    if count == 0
4615        || count % 2 == 1
4616        || (0..scan).any(|k| roots(TAU * (k as f64 + 0.5) / scan as f64).len() != count)
4617    {
4618        return None;
4619    }
4620    let loops: Vec<Vec<Point3>> = (0..count)
4621        .map(|j| {
4622            let mut pts: Vec<Point3> = rows
4623                .iter()
4624                .enumerate()
4625                .map(|(i, r)| cyl.evaluate(ruling_u(i), r[j]))
4626                .collect();
4627            pts.push(pts[0]);
4628            pts
4629        })
4630        .collect();
4631    Some(fit_ruling_loops(&loops, |p| {
4632        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
4633    }))
4634}
4635
4636/// A cone and a sphere whose centre is off the cone's axis, where every
4637/// generator of the cone crosses the sphere twice on the cone's nappe (a pin
4638/// through a ball): along a generator `apex + v g` the sphere is a quadratic
4639/// in `v`, and each of its two roots, taken in order, sweeps one closed loop
4640/// around the cone. A ball holding the apex is left once by every generator,
4641/// one loop. `None` when the centre lies on the axis (phase FF takes
4642/// [`exact_cone_sphere`]'s circles there), or the apex on the sphere. A
4643/// sphere only some generators cross goes to [`window_cone_sphere`].
4644fn ruling_cone_sphere(
4645    cone: &ConicalSurface,
4646    sphere: &SphericalSurface,
4647    cone_first: bool,
4648) -> Option<Vec<IntersectionCurve>> {
4649    let (apex, centre, radius) = (cone.apex(), sphere.center(), sphere.radius());
4650    let offset = apex - centre;
4651    let lin_tol = Tolerance::new().linear;
4652    let along = offset.dot(cone.axis());
4653    let across = (offset - cone.axis() * along).length();
4654    if across < lin_tol {
4655        return None;
4656    }
4657    // With the apex inside the ball, `v² + 2hv + K` has roots of opposite
4658    // signs (`K = |offset|² − R² < 0`): every generator leaves the ball once
4659    // ahead of the apex, at `v = √(h² − K) − h`, one loop round the cone.
4660    // Where `h > 0` the root is taken as `−K / (h + √(h² − K))`, free of the
4661    // cancellation.
4662    let k = offset.dot(offset) - radius * radius;
4663    if radius - offset.length() > lin_tol {
4664        let exit = |u: f64| {
4665            let h = (cone.evaluate(u, 1.0) - apex).dot(offset);
4666            let root = h.madd(h, -k).sqrt();
4667            cone.evaluate(u, if h > 0.0 { -k / (h + root) } else { root - h })
4668        };
4669        // A ball that barely holds the apex turns the loop sharply where it
4670        // passes the apex, at the scale of `√−K`: a step whose midpoint
4671        // strays from its chord by a hundredth of the chord (a turn of about
4672        // 0.08 radians) is halved until the turn is resolved.
4673        let mut samples: Vec<(f64, Point3)> = (0..=RULING_SAMPLES)
4674            .map(|i| (ruling_u(i), exit(ruling_u(i))))
4675            .collect();
4676        for _ in 0..10 {
4677            let mut refined = Vec::with_capacity(2 * samples.len());
4678            for pair in samples.windows(2) {
4679                let ((u0, p0), (u1, p1)) = (pair[0], pair[1]);
4680                refined.push(pair[0]);
4681                let um = 0.5 * (u0 + u1);
4682                let pm = exit(um);
4683                let chord = (p1 - p0).length();
4684                if chord > lin_tol && (pm - (p0 + (p1 - p0) * 0.5)).length() > 0.01 * chord {
4685                    refined.push((um, pm));
4686                }
4687            }
4688            refined.extend(samples.last().copied());
4689            if refined.len() == samples.len() {
4690                break;
4691            }
4692            samples = refined;
4693        }
4694        let mut pts: Vec<Point3> = samples.iter().map(|&(_, p)| p).collect();
4695        if let Some(last) = pts.last_mut() {
4696            *last = samples[0].1;
4697        }
4698        return Some(fit_ruling_loops(&[pts], |p| {
4699            in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4700        }));
4701    }
4702    // Both roots along a generator of unit direction `g` (`v` the distance
4703    // from the apex), nearer first, from `h = g·offset`, when it crosses the
4704    // sphere twice ahead of the apex.
4705    let crossing = |h: f64| {
4706        let (disc, vp, vm) = ruling_quadratic(1.0, 2.0 * h, k);
4707        (disc > lin_tol && vm >= lin_tol).then_some((vm, vp))
4708    };
4709    // Around the cone `h` runs between these bounds. Where both roots lie
4710    // ahead of the apex, raising `h` shrinks the discriminant and moves the
4711    // nearer root out, so every generator crosses when the two extreme ones
4712    // do.
4713    let (sin_a, cos_a) = cone.half_angle().sin_cos();
4714    if crossing(sin_a.madd(along, cos_a * across)).is_none()
4715        || crossing(sin_a.madd(along, -cos_a * across)).is_none()
4716    {
4717        return window_cone_sphere(cone, sphere, cone_first);
4718    }
4719    let rows: Vec<(f64, f64)> = (0..RULING_SAMPLES)
4720        .map(|i| crossing((cone.evaluate(ruling_u(i), 1.0) - apex).dot(offset)))
4721        .collect::<Option<_>>()?;
4722    let loops: Vec<Vec<Point3>> = [0, 1]
4723        .iter()
4724        .map(|&j| {
4725            let mut pts: Vec<Point3> = rows
4726                .iter()
4727                .enumerate()
4728                .map(|(i, &(near, far))| {
4729                    cone.evaluate(ruling_u(i), if j == 0 { near } else { far })
4730                })
4731                .collect();
4732            pts.push(pts[0]);
4733            pts
4734        })
4735        .collect();
4736    Some(fit_ruling_loops(&loops, |p| {
4737        in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4738    }))
4739}
4740
4741/// A cone and a sphere off its axis that only some generators cross (a ball
4742/// against the cone's side), with the apex outside the sphere: along the
4743/// generator at `u`, `h(u) = g·(apex − C)` is `c + A cos(u − φ)`, and the
4744/// generator crosses twice ahead of the apex where `h ≤ −√K`, with
4745/// `K = |apex − C|² − R²`. That is one arc of `u`, whose ends are where the
4746/// generator touches the sphere; the section is one loop, the nearer roots
4747/// out along the arc and the farther ones back. Sampled at
4748/// `u = mid − half·cos θ`, the roots' split `±√(h² − K)` changes sign with
4749/// `sin θ` and the loop stays smooth through both touching generators.
4750/// `Some(empty)` when no generator crosses ahead of the apex. `None`, the
4751/// marcher's case, when the apex lies within the sphere, when the centre is
4752/// too near the axis to place the arc, and when every generator reaches the
4753/// sphere (the extremes' test then failed on a touching generator or a root
4754/// at the apex).
4755fn window_cone_sphere(
4756    cone: &ConicalSurface,
4757    sphere: &SphericalSurface,
4758    cone_first: bool,
4759) -> Option<Vec<IntersectionCurve>> {
4760    let offset = cone.apex() - sphere.center();
4761    let lin_tol = Tolerance::new().linear;
4762    if offset.length() - sphere.radius() <= lin_tol {
4763        return None;
4764    }
4765    let k = offset.dot(offset) - sphere.radius() * sphere.radius();
4766    let (sin_a, cos_a) = cone.half_angle().sin_cos();
4767    let (ox, oy) = (offset.dot(cone.x_axis()), offset.dot(cone.y_axis()));
4768    let (c, a) = (sin_a * offset.dot(cone.axis()), cos_a * ox.hypot(oy));
4769    if a < lin_tol {
4770        return None;
4771    }
4772    let reach = (-k.sqrt() - c) / a;
4773    if reach <= -1.0 {
4774        return Some(Vec::new());
4775    }
4776    if reach >= 1.0 {
4777        return None;
4778    }
4779    let (mid, half) = (oy.atan2(ox) + std::f64::consts::PI, reach.acos());
4780    let half = std::f64::consts::PI - half;
4781    let n = RULING_SAMPLES;
4782    let mut pts: Vec<Point3> = (0..n)
4783        .map(|i| {
4784            #[allow(clippy::cast_precision_loss)]
4785            let theta = TAU * i as f64 / n as f64;
4786            let u = half.madd(-theta.cos(), mid);
4787            let h = a.madd((u - mid + std::f64::consts::PI).cos(), c);
4788            let split = h.madd(h, -k).max(0.0).sqrt();
4789            cone.evaluate(u, -h - split.copysign(theta.sin()))
4790        })
4791        .collect();
4792    pts.push(pts[0]);
4793    Some(fit_ruling_loops(&[pts], |p| {
4794        in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4795    }))
4796}
4797
4798/// Scan points per ruling sample when looking for windows of meeting
4799/// rulings.
4800const WINDOW_SCAN: usize = 16;
4801
4802/// Rulings sampled around a swept cylinder, half a step off u = 0 so the
4803/// branches of a self-touching curve (equal crossing cylinders) do not share
4804/// a sample.
4805const RULING_SAMPLES: usize = 128;
4806
4807#[allow(clippy::cast_precision_loss)]
4808fn ruling_u(i: usize) -> f64 {
4809    TAU * (i as f64 + 0.5) / RULING_SAMPLES as f64
4810}
4811
4812/// The discriminant and roots of `quad·v² + b·v + c = 0`.
4813fn ruling_quadratic(quad: f64, b: f64, c: f64) -> (f64, f64, f64) {
4814    let disc = b * b - 4.0 * quad * c;
4815    let root = disc.max(0.0).sqrt();
4816    (disc, (-b + root) / (2.0 * quad), (-b - root) / (2.0 * quad))
4817}
4818
4819/// The two points where each sampled ruling of `sweep` meets the other
4820/// surface, from `roots(u)` (the discriminant and the two axial parameters),
4821/// or `None` for a ruling that misses it.
4822fn ruling_samples(
4823    sweep: &CylindricalSurface,
4824    roots: &impl Fn(f64) -> (f64, f64, f64),
4825) -> Vec<Option<(Point3, Point3)>> {
4826    let lin_tol = Tolerance::new().linear;
4827    (0..RULING_SAMPLES)
4828        .map(|i| {
4829            let u = ruling_u(i);
4830            let (disc, vp, vm) = roots(u);
4831            (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4832        })
4833        .collect()
4834}
4835
4836/// Every ruling meets the other surface: each root traces a closed loop.
4837/// Where the loops pass closest at one ruling they are sampled from it,
4838/// closer together near it, so the fit follows the narrow neck between
4839/// them; where they touch there, they are the two halves of one curve
4840/// crossing itself, each with a corner at that point, which then falls at
4841/// their shared start and end, where the fit keeps it.
4842fn closed_ruling_loops(
4843    sweep: &CylindricalSurface,
4844    roots: &impl Fn(f64) -> (f64, f64, f64),
4845    samples: &[Option<(Point3, Point3)>],
4846) -> Vec<Vec<Point3>> {
4847    let (mut plus, mut minus): (Vec<Point3>, Vec<Point3>) =
4848        if let Some((neck, touching)) = narrowest_ruling(roots) {
4849            let count = 2 * RULING_SAMPLES;
4850            #[allow(clippy::cast_precision_loss)]
4851            (0..count)
4852                .map(|i| {
4853                    let t = i as f64 / count as f64;
4854                    let u = TAU.madd(t - 0.9 * (TAU * t).sin() / TAU, neck);
4855                    let (_, vp, vm) = roots(u);
4856                    if i == 0 && touching {
4857                        let at = sweep.evaluate(u, 0.5 * (vp + vm));
4858                        (at, at)
4859                    } else {
4860                        (sweep.evaluate(u, vp), sweep.evaluate(u, vm))
4861                    }
4862                })
4863                .unzip()
4864        } else {
4865            samples.iter().flatten().copied().unzip()
4866        };
4867    plus.push(plus[0]);
4868    minus.push(minus[0]);
4869    vec![plus, minus]
4870}
4871
4872/// The ruling where the two roots pass closest, when exactly one ruling
4873/// stands out: a local minimum of their gap, scanned finer than the
4874/// sampling and refined, that either closes to within tolerance (the
4875/// roots touch there; the tolerance scales with the widest gap, the loops'
4876/// own size, so the decision does not move with the model) or narrows
4877/// below a quarter of the widest gap while no other minimum does. Equal
4878/// crossing cylinders touch at two rulings and get `None`.
4879fn narrowest_ruling(roots: &impl Fn(f64) -> (f64, f64, f64)) -> Option<(f64, bool)> {
4880    let scan = WINDOW_SCAN * RULING_SAMPLES;
4881    #[allow(clippy::cast_precision_loss)]
4882    let step = TAU / scan as f64;
4883    let gap = |u: f64| {
4884        let (_, vp, vm) = roots(u);
4885        (vp - vm).abs()
4886    };
4887    #[allow(clippy::cast_precision_loss)]
4888    let gaps: Vec<f64> = (0..scan).map(|k| gap(step * k as f64)).collect();
4889    let widest = gaps.iter().copied().fold(0.0, f64::max);
4890    let tol = Tolerance::new().linear * (1.0 + widest);
4891    let mut necks = Vec::new();
4892    for k in 0..scan {
4893        let (before, here, after) = (gaps[(k + scan - 1) % scan], gaps[k], gaps[(k + 1) % scan]);
4894        if here > before || here >= after || here >= 0.25 * widest {
4895            continue;
4896        }
4897        #[allow(clippy::cast_precision_loss)]
4898        let (mut lo, mut hi) = (step * (k as f64 - 1.0), step * (k as f64 + 1.0));
4899        for _ in 0..100 {
4900            let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4901            if gap(a) < gap(b) {
4902                hi = b;
4903            } else {
4904                lo = a;
4905            }
4906        }
4907        let u = 0.5 * (lo + hi);
4908        necks.push((u, gap(u) <= tol));
4909    }
4910    match necks[..] {
4911        [neck] => Some(neck),
4912        _ => None,
4913    }
4914}
4915
4916/// Only windows of rulings meet the other surface: each cyclic window
4917/// carries one loop, out along one root and back along the other, the two
4918/// joined where the discriminant vanishes. Empty when no sample meets it (a
4919/// window narrower than the sampling).
4920///
4921/// Each window is sampled afresh between its two ends, closer together near
4922/// them: a window may hold only a few of the rulings sampled around the whole
4923/// turn, and the roots swing fastest where they join, so a fit through those
4924/// alone strays from the curve by far more than the tolerance (a ball beside a
4925/// wide ring's wall).
4926fn partial_ruling_loops(
4927    sweep: &CylindricalSurface,
4928    roots: &impl Fn(f64) -> (f64, f64, f64),
4929    samples: &[Option<(Point3, Point3)>],
4930) -> Vec<Vec<Point3>> {
4931    let lin_tol = Tolerance::new().linear;
4932    // Where the discriminant vanishes between a meeting ruling and a missing
4933    // one, approached from the meeting side.
4934    let branch_u = |inside: usize, outside: usize| -> f64 {
4935        let (mut lo, mut hi) = (ruling_u(inside), ruling_u(outside));
4936        if (hi - lo).abs() > std::f64::consts::PI {
4937            hi += if hi < lo { TAU } else { -TAU };
4938        }
4939        for _ in 0..60 {
4940            let mid = 0.5 * (lo + hi);
4941            if roots(mid).0 >= 0.0 {
4942                lo = mid;
4943            } else {
4944                hi = mid;
4945            }
4946        }
4947        lo
4948    };
4949    let joint = |u: f64| {
4950        let (_, vp, vm) = roots(u);
4951        sweep.evaluate(u, 0.5 * (vp + vm))
4952    };
4953    let Some(first_gap) = samples.iter().position(Option::is_none) else {
4954        return Vec::new();
4955    };
4956    let mut loops = Vec::new();
4957    let mut k = 0;
4958    while k < RULING_SAMPLES {
4959        let i = (first_gap + k) % RULING_SAMPLES;
4960        if samples[i].is_none() {
4961            k += 1;
4962            continue;
4963        }
4964        let start = i;
4965        let mut run = Vec::new();
4966        while k < RULING_SAMPLES {
4967            let j = (first_gap + k) % RULING_SAMPLES;
4968            let Some(pair) = samples[j] else { break };
4969            run.push(pair);
4970            k += 1;
4971        }
4972        let end = (start + run.len() - 1) % RULING_SAMPLES;
4973        let u_head = branch_u(start, (start + RULING_SAMPLES - 1) % RULING_SAMPLES);
4974        let u_tail = branch_u(end, (end + 1) % RULING_SAMPLES);
4975        let span = (u_tail - u_head).rem_euclid(TAU);
4976        #[allow(clippy::cast_precision_loss)]
4977        let fresh: Option<Vec<(Point3, Point3)>> = (1..RULING_SAMPLES)
4978            .map(|n| {
4979                let t = n as f64 / RULING_SAMPLES as f64;
4980                let u = span.madd(0.5 * (1.0 - (std::f64::consts::PI * t).cos()), u_head);
4981                let (disc, vp, vm) = roots(u);
4982                (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4983            })
4984            .collect();
4985        // A gap inside the window that the sampling stepped over: keep the
4986        // sampled rulings, which stay on one side of it.
4987        let run = fresh.unwrap_or(run);
4988        let (head, tail) = (joint(u_head), joint(u_head + span));
4989        let mut pts = vec![head];
4990        pts.extend(run.iter().map(|p| p.0));
4991        pts.push(tail);
4992        pts.extend(run.iter().rev().map(|p| p.1));
4993        pts.push(head);
4994        loops.push(pts);
4995    }
4996    loops
4997}
4998
4999/// Cubic interpolants through the swept loops, with `params(p)` giving each
5000/// point's parameters on the two surfaces.
5001fn fit_ruling_loops(
5002    loops: &[Vec<Point3>],
5003    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
5004) -> Vec<IntersectionCurve> {
5005    let mut curves = Vec::new();
5006    for pts in loops {
5007        if pts.len() < 4 {
5008            continue;
5009        }
5010        let ipts: Vec<IntersectionPoint> = pts
5011            .iter()
5012            .map(|&p| {
5013                let (param1, param2) = params(p);
5014                IntersectionPoint {
5015                    point: p,
5016                    param1,
5017                    param2,
5018                }
5019            })
5020            .collect();
5021        let degree = 3.min(pts.len() - 1);
5022        if let Ok(curve) = interpolate(pts, degree) {
5023            curves.push(IntersectionCurve {
5024                curve,
5025                points: ipts,
5026            });
5027        }
5028    }
5029    curves
5030}
5031
5032/// Algebraic cone-cylinder intersection for PARALLEL (or antiparallel) axes.
5033///
5034/// When the axes are parallel, every plane perpendicular to them cuts the cone
5035/// in a circle of radius `rho = v * cos(half_angle)` about a FIXED centre and
5036/// the cylinder in a circle of radius `R` about a second FIXED centre, so the
5037/// axis separation `d` is constant in `v`. Two coplanar circles meet at
5038/// `u = phi0 +/- acos((d^2 + rho^2 - R^2) / (2*d*rho))`, giving two branches
5039/// parameterised exactly by the cone's own `v`. The branches exist only where
5040/// `rho` lies in `[|d - R|, d + R]`, which bounds the curve naturally.
5041///
5042/// This replaces the general grid-seeded marcher for the configuration, which
5043/// mis-handles it badly: seeds are accepted anywhere within half the surface
5044/// diagonal of the partner, the march-result dedup only consumes seeds the
5045/// traced polyline passes near, and the survivors are dozens of overlapping
5046/// partial traces of the same curve. Those fragments carry no usable in-face
5047/// span, so a cone corner-round crossed by a boss cylinder never splits (a
5048/// counterbore/countersink meeting a pad — the gridfinity lightweight base).
5049///
5050/// Returns `None` (defer to the caller's other paths) when the axes are not
5051/// parallel, or when they are coaxial — a coaxial pair degenerates to shared
5052/// circles, which [`exact_cone_cylinder`] emits exactly and phase FF calls
5053/// directly. Note that `intersect_analytic_analytic_bounded` does NOT consult
5054/// `exact_cone_cylinder`, so a coaxial pair reaching this path through that
5055/// caller falls through to the marcher; only the FF path gets the exact circles.
5056// Result-wrapped to match the other `try_algebraic_intersection` arms' shape.
5057#[allow(clippy::unnecessary_wraps)]
5058fn algebraic_parallel_cone_cylinder(
5059    cone: &ConicalSurface,
5060    cyl: &CylindricalSurface,
5061    v_range_cone: Option<(f64, f64)>,
5062    v_range_cyl: Option<(f64, f64)>,
5063) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
5064    let axis = cone.axis();
5065    if axis.cross(cyl.axis()).length() > Tolerance::new().angular {
5066        return Ok(None); // Skew or oblique: `ruling_cone_cylinder` traces it.
5067    }
5068
5069    let apex = cone.apex();
5070    let delta = cyl.origin() - apex;
5071    let along = delta.dot(axis);
5072    let perp = delta - axis * along;
5073    let d = perp.length();
5074    if d < 1e-9 {
5075        return Ok(None); // Coaxial — `exact_cone_cylinder` owns this.
5076    }
5077
5078    let (e1, e2) = (cone.x_axis(), cone.y_axis());
5079    let phi0 = perp.dot(e2).atan2(perp.dot(e1));
5080
5081    let (sin_t, cos_t) = cone.half_angle().sin_cos();
5082    if cos_t < 1e-12 || sin_t < 1e-12 {
5083        return Ok(None);
5084    }
5085    let r = cyl.radius();
5086
5087    // Branch existence: |d - R| <= rho <= d + R, with rho = v * cos(half_angle).
5088    let mut v_min = (d - r).abs() / cos_t;
5089    let mut v_max = (d + r) / cos_t;
5090    if v_max <= v_min {
5091        return Ok(Some(vec![]));
5092    }
5093
5094    // Narrow the sampled span to the faces' own extents so the fixed sample
5095    // budget resolves the in-face part of the curve rather than spreading over
5096    // a loop that mostly lies off both patches. A face's crossing can be a
5097    // fraction of a degree of the cone's sweep (the corner-round case above),
5098    // and an unnarrowed sampling puts fewer than one sample across it.
5099    let mut lo = v_min;
5100    let mut hi = v_max;
5101    // Clip EXACTLY to the hints, not to a padded window: an endpoint that lands
5102    // exactly on the face's own v-limit lies ON that boundary rim, so the
5103    // downstream pave machinery anchors it to the rim edge instead of leaving
5104    // the section dangling just past the face.
5105    if let Some((a, b)) = v_range_cone {
5106        let (a, b) = if a <= b { (a, b) } else { (b, a) };
5107        lo = lo.max(a);
5108        hi = hi.min(b);
5109    }
5110    if let Some((a, b)) = v_range_cyl {
5111        // The cylinder's v is a signed distance along its axis from its origin;
5112        // convert both ends to the cone's v via the shared axial direction.
5113        let flip = cyl.axis().dot(axis);
5114        let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
5115        let (a, b) = (to_cone_v(a), to_cone_v(b));
5116        let (a, b) = if a <= b { (a, b) } else { (b, a) };
5117        lo = lo.max(a);
5118        hi = hi.min(b);
5119    }
5120    let (turn_lo, turn_hi) = (v_min, v_max);
5121    v_min = lo.max(v_min);
5122    v_max = hi.min(v_max);
5123    if v_max - v_min <= 1e-12 {
5124        return Ok(Some(vec![]));
5125    }
5126    // A cylinder beside the axis, with both turning points inside both faces,
5127    // meets the cone in a whole loop: traced along the cylinder's rulings,
5128    // each of which meets the nappe once, it comes back as one closed curve,
5129    // which the band split of the cylinder it winds needs. Around the axis
5130    // the loop winds the cone too and stays in two branches, and so does a
5131    // wall passing so near the axis that the loop's bend there, about
5132    // `(d - r) / sqrt(d r)` of a turn wide, spans fewer than a few rulings.
5133    let slack = Tolerance::new().linear;
5134    #[allow(clippy::cast_precision_loss)]
5135    let resolved = d - r > 3.0 * (d * r).sqrt() * TAU / RULING_SAMPLES as f64;
5136    if v_min <= turn_lo + slack && v_max >= turn_hi - slack && resolved {
5137        let mut pts: Vec<Point3> = (0..RULING_SAMPLES)
5138            .map(|i| {
5139                let (sin_u, cos_u) = ruling_u(i).sin_cos();
5140                let foot = cyl.origin() + (cyl.x_axis() * cos_u + cyl.y_axis() * sin_u) * r;
5141                let off = foot - apex;
5142                let across = off - axis * off.dot(axis);
5143                apex + across + axis * (across.length() * sin_t / cos_t)
5144            })
5145            .collect();
5146        pts.push(pts[0]);
5147        return Ok(Some(fit_ruling_loops(&[pts], |p| {
5148            (cone.project_point(p), cyl.project_point(p))
5149        })));
5150    }
5151
5152    let n_samples = 128;
5153    let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
5154    let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
5155    #[allow(clippy::cast_precision_loss)]
5156    for i in 0..=n_samples {
5157        let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
5158        let rho = v * cos_t;
5159        if rho < 1e-12 {
5160            // The apex. `cos_alpha` has rho in its denominator, so it is only
5161            // meaningful in the limit: it tends to 0 (alpha -> pi/2) when the
5162            // cylinder passes exactly through the apex (d == R), and diverges
5163            // otherwise — where the clamp would manufacture a spurious alpha of
5164            // 0 or pi. So keep the apex only in the d == R case, where it is a
5165            // genuine point of the intersection and the shared endpoint at
5166            // which the two branches meet.
5167            if (d - r).abs() < 1e-12 {
5168                let apex = cone.evaluate(phi0, v);
5169                plus.push(apex);
5170                minus.push(apex);
5171            }
5172            continue;
5173        }
5174        let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
5175        let alpha = cos_alpha.acos();
5176        plus.push(cone.evaluate(phi0 + alpha, v));
5177        minus.push(cone.evaluate(phi0 - alpha, v));
5178    }
5179
5180    let mut curves = Vec::new();
5181    for pts in [&plus, &minus] {
5182        // Fewer than four samples in range means this branch does not cross the
5183        // bounded region at all (the other branch may still).
5184        if pts.len() < 4 {
5185            continue;
5186        }
5187        let ipts: Vec<IntersectionPoint> = pts
5188            .iter()
5189            .map(|&p| IntersectionPoint {
5190                point: p,
5191                param1: cone.project_point(p),
5192                param2: cyl.project_point(p),
5193            })
5194            .collect();
5195        let degree = 3.min(pts.len() - 1);
5196        match interpolate(pts, degree) {
5197            Ok(curve) => curves.push(IntersectionCurve {
5198                curve,
5199                points: ipts,
5200            }),
5201            // Emitting only the branch that happened to fit would starve the
5202            // section chain of exactly the piece this path exists to supply —
5203            // the same silent half-answer the marcher's fragments produced.
5204            // Defer the whole pair to the caller's other paths instead.
5205            Err(_) => return Ok(None),
5206        }
5207    }
5208
5209    Ok(Some(curves))
5210}
5211
5212/// How many times a parallel cone-cone branch's fitted curve may be refined
5213/// where it strays.
5214const PARALLEL_CONES_FIT_ROUNDS: usize = 8;
5215
5216/// The distance from `p` to the nappe of `cone` nearest it, for a point near
5217/// the cone's wall: the distance in `p`'s meridian plane to the generator.
5218fn cone_wall_distance(cone: &ConicalSurface, p: Point3) -> f64 {
5219    let rel = p - cone.apex();
5220    let along = rel.dot(cone.axis());
5221    let across = (rel - cone.axis() * along).length();
5222    let (sin, cos) = cone.half_angle().sin_cos();
5223    across.madd(sin, -along * cos)
5224}
5225
5226/// Cone-cone intersection for PARALLEL (or antiparallel) axes that do not
5227/// coincide, with openings of unequal slope (equal slopes give the exact
5228/// conic of [`offset_parallel_cone_cone`]).
5229///
5230/// Every plane across the axes cuts each cone in a circle about a fixed
5231/// centre, the two centres `d` apart, and both radii change linearly with the
5232/// height. Two coplanar circles meet at
5233/// `u = phi0 +/- acos((d^2 + rho1^2 - rho2^2) / (2*d*rho1))` on the first
5234/// cone, which gives two branches parameterised exactly by its own `v`. They
5235/// exist where `|rho1 - rho2| <= d <= rho1 + rho2` on both nappes, conditions
5236/// linear in `v`, and join where one of the first holds with equality, where
5237/// the circles touch. There `u` changes like the square root of the distance
5238/// in `v`, so the samples close in on both ends of the span, and the branches
5239/// end at the one point where the circles touch.
5240///
5241/// Halfway between each pair of points the fitted curve must lie within a
5242/// quarter of the linear tolerance of both cones; where it strays, the
5243/// section's own point there joins the fit.
5244///
5245/// `None` (the marcher's case) when the axes are not parallel to the angular
5246/// tolerance or coincide, when a cone is flat or a line, when a range reaches
5247/// a cone's negative nappe, when nothing bounds the span, or when a fit still
5248/// strays.
5249fn algebraic_parallel_cone_cone(
5250    c1: &ConicalSurface,
5251    c2: &ConicalSurface,
5252    v_range_1: Option<(f64, f64)>,
5253    v_range_2: Option<(f64, f64)>,
5254) -> Option<Vec<IntersectionCurve>> {
5255    let tol = Tolerance::new();
5256    // The span below runs on both cones' positive nappes only.
5257    if [v_range_1, v_range_2]
5258        .into_iter()
5259        .flatten()
5260        .any(|(p, q)| p.min(q) < -tol.linear)
5261    {
5262        return None;
5263    }
5264    let axis = c1.axis();
5265    if axis.cross(c2.axis()).length() > tol.angular {
5266        return None;
5267    }
5268    let sigma = axis.dot(c2.axis()).signum();
5269    let delta = c2.apex() - c1.apex();
5270    let along = delta.dot(axis);
5271    let perp = delta - axis * along;
5272    let d = perp.length();
5273    if d < 1e-9 {
5274        return None;
5275    }
5276    let phi0 = perp.dot(c1.y_axis()).atan2(perp.dot(c1.x_axis()));
5277    let (sin1, cos1) = c1.half_angle().sin_cos();
5278    let (sin2, cos2) = c2.half_angle().sin_cos();
5279    if [sin1, cos1, sin2, cos2].iter().any(|&x| x < 1e-12) {
5280        return None;
5281    }
5282    // The second cone's radius at the first one's `v`, `a + b v`, from the
5283    // height `v sin1` above the first apex.
5284    let slope2 = cos2 / sin2;
5285    let (a, b) = (-sigma * along * slope2, sigma * sin1 * slope2);
5286    // The span, and whether each end is where the circles touch.
5287    let (mut lo, mut hi) = (0.0_f64, f64::INFINITY);
5288    let (mut lo_touch, mut hi_touch) = (false, false);
5289    // Each condition `k v + c >= 0`: the second nappe, then the circles
5290    // meeting (`rho1 + rho2 >= d`, `rho2 - rho1 <= d`, `rho1 - rho2 <= d`).
5291    for (k, c, touch) in [
5292        (b, a, false),
5293        (cos1 + b, a - d, true),
5294        (b - cos1, a + d, true),
5295        (cos1 - b, d - a, true),
5296    ] {
5297        // However small, a slope moves the bound: slopes nearly equal to
5298        // each other hold their condition only far out, past `-c / k`.
5299        if k > 0.0 {
5300            if -c / k > lo {
5301                (lo, lo_touch) = (-c / k, touch);
5302            }
5303        } else if k < 0.0 {
5304            if -c / k < hi {
5305                (hi, hi_touch) = (-c / k, touch);
5306            }
5307        } else if c < 0.0 {
5308            return Some(Vec::new());
5309        }
5310    }
5311    let mut clip = |p: f64, q: f64| {
5312        if p.min(q) > lo {
5313            (lo, lo_touch) = (p.min(q), false);
5314        }
5315        if p.max(q) < hi {
5316            (hi, hi_touch) = (p.max(q), false);
5317        }
5318    };
5319    if let Some((p, q)) = v_range_1 {
5320        clip(p, q);
5321    }
5322    if let Some((p, q)) = v_range_2 {
5323        let to_v1 = |v2: f64| sigma.madd(v2 * sin2, along) / sin1;
5324        clip(to_v1(p), to_v1(q));
5325    }
5326    if !hi.is_finite() {
5327        return None;
5328    }
5329    if hi - lo <= 1e-12 {
5330        return Some(Vec::new());
5331    }
5332
5333    // The two points at `v`, or `None` at the first apex off the second cone.
5334    let at = |v: f64, touch: bool| -> Option<(Point3, Point3)> {
5335        let rho1 = v * cos1;
5336        let rho2 = b.madd(v, a);
5337        if rho1 < 1e-12 {
5338            // `u` means nothing at the apex, a point of the curve only where
5339            // it lies on the second cone.
5340            return ((rho2 - d).abs() < 1e-12).then(|| (c1.apex(), c1.apex()));
5341        }
5342        let cos_alpha = (d.madd(d, rho1 * rho1) - rho2 * rho2) / (2.0 * d * rho1);
5343        if touch {
5344            // Rounding leaves `cos_alpha` off +/-1 there, and `acos` turns
5345            // that into a gap between the branches' ends.
5346            let p = c1.evaluate(
5347                if cos_alpha >= 0.0 {
5348                    phi0
5349                } else {
5350                    phi0 + std::f64::consts::PI
5351                },
5352                v,
5353            );
5354            return Some((p, p));
5355        }
5356        let alpha = cos_alpha.clamp(-1.0, 1.0).acos();
5357        Some((c1.evaluate(phi0 + alpha, v), c1.evaluate(phi0 - alpha, v)))
5358    };
5359    // Samples are spaced evenly in `t`, which runs `v` like a square from
5360    // each end, where `u` runs like the square root of `v`.
5361    let v_at = |t: f64| (hi - lo).madd(0.5 * (1.0 - (std::f64::consts::PI * t).cos()), lo);
5362    let n_samples = 128;
5363    let mut plus: Vec<(f64, Point3)> = Vec::with_capacity(n_samples + 1);
5364    let mut minus: Vec<(f64, Point3)> = Vec::with_capacity(n_samples + 1);
5365    #[allow(clippy::cast_precision_loss)]
5366    for i in 0..=n_samples {
5367        let t = i as f64 / n_samples as f64;
5368        let touch = (i == 0 && lo_touch) || (i == n_samples && hi_touch);
5369        if let Some((p, m)) = at(v_at(t), touch) {
5370            plus.push((t, p));
5371            minus.push((t, m));
5372        }
5373    }
5374
5375    let off = |p: Point3| {
5376        cone_wall_distance(c1, p)
5377            .abs()
5378            .max(cone_wall_distance(c2, p).abs())
5379    };
5380    let mut curves = Vec::new();
5381    for (branch, side) in [(&mut plus, 0), (&mut minus, 1)] {
5382        if branch.len() < 4 {
5383            continue;
5384        }
5385        let mut rounds = 0;
5386        // One branch alone would leave the section chain short of the piece
5387        // this path exists to supply: a branch that fails defers the pair.
5388        let curve = loop {
5389            let positions: Vec<Point3> = branch.iter().map(|&(_, p)| p).collect();
5390            let curve = interpolate(&positions, 3).ok()?;
5391            let params = crate::nurbs::fitting::chord_length_params(&positions);
5392            let errors: Vec<f64> = (0..positions.len() - 1)
5393                .map(|k| off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))))
5394                .collect();
5395            if errors.iter().all(|&e| e <= 0.25 * tol.linear) {
5396                break curve;
5397            }
5398            if rounds == PARALLEL_CONES_FIT_ROUNDS {
5399                return None;
5400            }
5401            rounds += 1;
5402            // Every span within a factor of four of the limit is split, and
5403            // a stray's neighbours too: the fit through new points moves the
5404            // error onto the spans beside them.
5405            let mut split: Vec<usize> = (0..errors.len())
5406                .filter(|&k| errors[k] > 0.0625 * tol.linear)
5407                .flat_map(|k| {
5408                    let stray = errors[k] > 0.25 * tol.linear;
5409                    let (first, last) = if stray {
5410                        (k.saturating_sub(1), k + 1)
5411                    } else {
5412                        (k, k)
5413                    };
5414                    first..=last.min(errors.len() - 1)
5415                })
5416                .collect();
5417            split.sort_unstable();
5418            split.dedup();
5419            for &k in split.iter().rev() {
5420                let t = f64::midpoint(branch[k].0, branch[k + 1].0);
5421                let (p, m) = at(v_at(t), false)?;
5422                branch.insert(k + 1, (t, if side == 0 { p } else { m }));
5423            }
5424        };
5425        let points = branch
5426            .iter()
5427            .map(|&(_, p)| IntersectionPoint {
5428                point: p,
5429                param1: c1.project_point(p),
5430                param2: c2.project_point(p),
5431            })
5432            .collect();
5433        curves.push(IntersectionCurve { curve, points });
5434    }
5435    Some(curves)
5436}
5437
5438/// Algebraic sphere-sphere intersection.
5439///
5440/// Two spheres intersect in a circle lying in the radical plane.
5441/// The radical plane is perpendicular to the line connecting the centers,
5442/// at a distance d1 from center1 where:
5443///   d1 = (D² + R1² - R2²) / (2D)
5444/// and D is the distance between centers.
5445fn algebraic_sphere_sphere(
5446    s1: &SphericalSurface,
5447    s2: &SphericalSurface,
5448) -> Result<Vec<IntersectionCurve>, MathError> {
5449    let c1 = s1.center();
5450    let c2 = s2.center();
5451    let r1 = s1.radius();
5452    let r2 = s2.radius();
5453
5454    let delta = c2 - c1;
5455    let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
5456    let d = d_sq.sqrt();
5457
5458    if d < 1e-12 {
5459        // Concentric spheres: no intersection (unless same radius → degenerate).
5460        return Ok(vec![]);
5461    }
5462
5463    // Check separation conditions.
5464    if d > r1 + r2 + 1e-10 {
5465        return Ok(vec![]); // Too far apart
5466    }
5467    if d + r2.min(r1) + 1e-10 < r1.max(r2) {
5468        return Ok(vec![]); // One inside the other
5469    }
5470
5471    // Distance from c1 to the radical plane along the center line.
5472    let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
5473
5474    // Radius of the intersection circle.
5475    let r_circle_sq = r1 * r1 - d1 * d1;
5476    if r_circle_sq < 0.0 {
5477        // Tangent or no intersection (numerical noise).
5478        if r_circle_sq > -1e-10 {
5479            // Tangent: single point.
5480            let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
5481            let tangent_pt = Point3::new(
5482                c1.x() + axis.x() * d1,
5483                c1.y() + axis.y() * d1,
5484                c1.z() + axis.z() * d1,
5485            );
5486            let ipt = IntersectionPoint {
5487                point: tangent_pt,
5488                param1: (0.0, 0.0),
5489                param2: (0.0, 0.0),
5490            };
5491            // Single-point "curve" — not very useful but correct.
5492            return Ok(vec![IntersectionCurve {
5493                curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
5494                points: vec![ipt],
5495            }]);
5496        }
5497        return Ok(vec![]);
5498    }
5499
5500    let r_circle = r_circle_sq.sqrt();
5501    let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
5502    let center = Point3::new(
5503        c1.x() + axis.x() * d1,
5504        c1.y() + axis.y() * d1,
5505        c1.z() + axis.z() * d1,
5506    );
5507
5508    // Build a reference frame for the circle.
5509    let basis = Frame3::from_normal(center, axis)?;
5510    let u_dir = basis.x;
5511    let v_dir = basis.y;
5512
5513    // Sample points along the circle for the IntersectionCurve.
5514    let n_samples = 33; // Odd for symmetry
5515    let mut points = Vec::with_capacity(n_samples);
5516    #[allow(clippy::cast_precision_loss)]
5517    for i in 0..n_samples {
5518        let theta = TAU * i as f64 / (n_samples - 1) as f64;
5519        let (sin_t, cos_t) = theta.sin_cos();
5520        let pt = Point3::new(
5521            center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
5522            center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
5523            center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
5524        );
5525        points.push(IntersectionPoint {
5526            point: pt,
5527            param1: (0.0, 0.0),
5528            param2: (0.0, 0.0),
5529        });
5530    }
5531
5532    let curve = conic_loop(center, u_dir, v_dir, r_circle, r_circle)?;
5533
5534    Ok(vec![IntersectionCurve { curve, points }])
5535}
5536
5537/// Newton correction: project a point back onto the intersection curve
5538/// of two analytic surfaces. Solves the 3×3 system:
5539///   δ · na = -da  (eliminate distance to surface A)
5540///   δ · nb = -db  (eliminate distance to surface B)
5541///   δ · t  = 0    (minimal correction, perpendicular to tangent)
5542#[allow(clippy::too_many_arguments)]
5543fn correct_to_intersection(
5544    a: &AnalyticSurface<'_>,
5545    b: &AnalyticSurface<'_>,
5546    surf_a: &dyn Fn(f64, f64) -> Point3,
5547    norm_a: &dyn Fn(f64, f64) -> Vec3,
5548    surf_b: &dyn Fn(f64, f64) -> Point3,
5549    norm_b: &dyn Fn(f64, f64) -> Vec3,
5550    point: Point3,
5551    u_range_a: (f64, f64),
5552    v_range_a: (f64, f64),
5553    u_range_b: (f64, f64),
5554    v_range_b: (f64, f64),
5555    max_iters: usize,
5556) -> Point3 {
5557    let mut p = point;
5558    for _ in 0..max_iters {
5559        let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
5560        let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
5561        let pa = surf_a(ua, va);
5562        let pb = surf_b(ub, vb);
5563        let na = norm_a(ua, va);
5564        let nb = norm_b(ub, vb);
5565        let pv = Vec3::new(p.x(), p.y(), p.z());
5566
5567        let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
5568        let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
5569
5570        if da.abs() < 1e-7 && db.abs() < 1e-7 {
5571            break;
5572        }
5573
5574        let t = na.cross(nb);
5575        let t_len = t.length();
5576        if t_len < 1e-10 {
5577            // Surfaces are tangent — fall back to midpoint.
5578            return Point3::new(
5579                (pa.x() + pb.x()) * 0.5,
5580                (pa.y() + pb.y()) * 0.5,
5581                (pa.z() + pb.z()) * 0.5,
5582            );
5583        }
5584        let t_hat = t * (1.0 / t_len);
5585
5586        // Solve [na; nb; t_hat] · δ = [-da, -db, 0] via Cramer's rule.
5587        let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
5588            - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
5589            + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
5590        if det.abs() < 1e-15 {
5591            return Point3::new(
5592                (pa.x() + pb.x()) * 0.5,
5593                (pa.y() + pb.y()) * 0.5,
5594                (pa.z() + pb.z()) * 0.5,
5595            );
5596        }
5597        let inv = 1.0 / det;
5598        // Cramer's rule: replace each column of A with rhs = (-da, -db, 0).
5599        let dx = inv
5600            * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
5601                + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
5602        let dy = inv
5603            * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
5604                - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
5605        let dz = inv
5606            * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
5607                + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
5608        let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
5609
5610        // Divergence guard: if the correction moves farther from both
5611        // surfaces, abandon Newton and return the best point so far.
5612        let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
5613        let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
5614        let pc_a = surf_a(uc, vc);
5615        let pc_b = surf_b(ud, vd);
5616        let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
5617        let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
5618            .dot(norm_a(uc, vc))
5619            .abs();
5620        let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
5621            .dot(norm_b(ud, vd))
5622            .abs();
5623        if da_new > da.abs() && db_new > db.abs() {
5624            return p;
5625        }
5626
5627        p = candidate;
5628    }
5629    p
5630}
5631
5632/// The most a march step turns the section's tangent, in radians.
5633const MARCH_TURN: f64 = 0.2;
5634
5635/// The share of the distance to the section's next branch that a march
5636/// step's guess may miss the section by.
5637const MARCH_BASIN: f64 = 0.25;
5638
5639/// The most steps a march takes each way.
5640const MARCH_STEPS: usize = 4096;
5641
5642/// A point of the section of two surfaces, with what a march step from it
5643/// needs.
5644#[derive(Clone, Copy)]
5645struct Station {
5646    p: Point3,
5647    /// The unit tangent of the section, along the march.
5648    t: Vec3,
5649    /// The curvature of the section.
5650    bend: f64,
5651    /// The distance, across the section, at which the two surfaces' second
5652    /// order models through `p` cross again: a lower estimate of how far
5653    /// the section's next branch lies.
5654    gap: f64,
5655}
5656
5657/// The station at `p`, a point of the section of `a` and `b`, its tangent
5658/// along `toward`; `None` where the two surfaces touch there (their
5659/// normals within about 1e-6 of parallel) or a distance has no gradient.
5660///
5661/// The section's curvature vector `k` lies across it, and the curve's
5662/// normal curvature on each surface, the second derivative of its distance
5663/// along the tangent, is `-k . n` for that surface's normal `n`. Across the
5664/// section, each surface's trace is a curve of the curvature its distance
5665/// gives along the trace; two circles that cross at angle `θ`, of
5666/// curvatures `κa` and `κb`, cross again no nearer than `2 sin θ / (κa + κb)`.
5667fn station(
5668    a: &AnalyticSurface<'_>,
5669    b: &AnalyticSurface<'_>,
5670    p: Point3,
5671    toward: Vec3,
5672) -> Option<Station> {
5673    use section_fit::Carrier;
5674    let (_, na) = a.distance(p)?;
5675    let (_, nb) = b.distance(p)?;
5676    let cross = na.cross(nb);
5677    let sin = cross.length();
5678    if sin < 1e-6 {
5679        return None;
5680    }
5681    let mut t = cross * (1.0 / sin);
5682    if t.dot(toward) < 0.0 {
5683        t = -t;
5684    }
5685    let (ka, kb) = (a.bend(p, t)?, b.bend(p, t)?);
5686    let c = na.dot(nb);
5687    let det = sin * sin;
5688    let along_a = c.madd(kb, -ka) / det;
5689    let along_b = c.madd(ka, -kb) / det;
5690    let bend = (2.0 * along_a * along_b)
5691        .madd(c, along_a.madd(along_a, along_b * along_b))
5692        .max(0.0)
5693        .sqrt();
5694    let (qa, qb) = (a.bend(p, t.cross(na))?, b.bend(p, t.cross(nb))?);
5695    let spread = qa.abs() + qb.abs();
5696    let gap = if spread > 0.0 {
5697        2.0 * sin / spread
5698    } else {
5699        f64::INFINITY
5700    };
5701    bend.is_finite().then_some(Station { p, t, bend, gap })
5702}
5703
5704impl Station {
5705    /// The longest step from here: one that turns the tangent by no more
5706    /// than [`MARCH_TURN`], and whose guess along the tangent misses the
5707    /// section by no more than [`MARCH_BASIN`] of the gap.
5708    fn reach(&self, longest: f64) -> f64 {
5709        if self.bend > 0.0 {
5710            longest
5711                .min(MARCH_TURN / self.bend)
5712                .min((2.0 * MARCH_BASIN * self.gap / self.bend).sqrt())
5713        } else {
5714            longest
5715        }
5716    }
5717}
5718
5719/// A point within `reach` of `p` where both surfaces pass and their normals
5720/// lie parallel, each within the rounding of the point's place: a point
5721/// where the section's branches meet or the surfaces touch. Both distances
5722/// must lie within the rounding of the point against the surfaces' frames,
5723/// `near`. The normals must lie within the rounding each picks up from its
5724/// curvature times its distance from its frame, or, where that is less,
5725/// within the angle whose cosine rounds to one, the square root of the
5726/// float spacing, 1.5e-8: a leg and the bend on its top, turned and moved,
5727/// touch at 4e-9 off parallel, after the rounding of the turn.
5728///
5729/// Gauss-Newton steps find the point near `p` on `a` where `b`'s normal
5730/// lies along `a`'s, from `a`'s distance and the cross product of the
5731/// normals, whose derivative along each axis comes from each distance's
5732/// second derivative (its value along `e + v` less that along `e - v` is
5733/// four times `e . H v`). Each step is taken once, twice or three times,
5734/// whichever misses least: where the touch is of higher order the cross
5735/// product falls as a power of the way left, and a single step covers only
5736/// a share of it, as Newton steps do on a double root, and then moves back
5737/// onto `a` along its normal. The steps run until they stop gaining, and
5738/// the best point is read. `None` where it fails:
5739/// two surfaces that cross at a shallow angle, 2e-6, with no touch near,
5740/// keep their normals that far apart.
5741fn singular_point(
5742    a: &AnalyticSurface<'_>,
5743    b: &AnalyticSurface<'_>,
5744    p: Point3,
5745    reach: f64,
5746) -> Option<Point3> {
5747    use section_fit::Carrier;
5748    let axes = [
5749        Vec3::new(1.0, 0.0, 0.0),
5750        Vec3::new(0.0, 1.0, 0.0),
5751        Vec3::new(0.0, 0.0, 1.0),
5752    ];
5753    let miss = |x: Point3| {
5754        let (Some((da, na)), Some((_, nb))) = (a.distance(x), b.distance(x)) else {
5755            return f64::INFINITY;
5756        };
5757        da.hypot(reach * na.cross(nb).length())
5758    };
5759    let mut best: Option<(f64, Point3, bool)> = None;
5760    let mut q = p;
5761    for _ in 0..32 {
5762        let (da, na) = a.distance(q)?;
5763        let (db, nb) = b.distance(q)?;
5764        let cross = na.cross(nb);
5765        let mut hessians = [[Vec3::new(0.0, 0.0, 0.0); 3]; 2];
5766        for (h, s) in hessians.iter_mut().zip([a, b]) {
5767            for (j, &v) in axes.iter().enumerate() {
5768                let mut row = [0.0; 3];
5769                for (k, &e) in axes.iter().enumerate() {
5770                    row[k] = 0.25 * (s.bend(q, e + v)? - s.bend(q, e - v)?);
5771                }
5772                h[j] = Vec3::new(row[0], row[1], row[2]);
5773            }
5774        }
5775        let curvature = |h: &[Vec3; 3]| h.iter().fold(0.0, |m: f64, v| m.max(v.length()));
5776        let (ka, kb) = (curvature(&hessians[0]), curvature(&hessians[1]));
5777        let near = 64.0 * f64::EPSILON * (a.scale(q) + b.scale(q));
5778        let parallel = (64.0 * f64::EPSILON * ka.madd(a.scale(q), kb.madd(b.scale(q), 2.0)))
5779            .max(f64::EPSILON.sqrt());
5780        let here = cross.length();
5781        let holds = da.abs() <= near && db.abs() <= near && here <= parallel;
5782        if best.is_none_or(|(c, _, _)| here < c) {
5783            best = Some((here, q, holds));
5784        }
5785        // Rows: `a`'s distance, then the cross product's parts, each a
5786        // length once scaled by `reach`.
5787        let mut rows = vec![(na, da)];
5788        for (k, &e) in axes.iter().enumerate() {
5789            let grad = Vec3::new(
5790                (hessians[0][0].cross(nb) + na.cross(hessians[1][0])).dot(e),
5791                (hessians[0][1].cross(nb) + na.cross(hessians[1][1])).dot(e),
5792                (hessians[0][2].cross(nb) + na.cross(hessians[1][2])).dot(e),
5793            );
5794            let value = [cross.x(), cross.y(), cross.z()][k];
5795            rows.push((grad * reach, value * reach));
5796        }
5797        let mut m = [[0.0; 3]; 3];
5798        let mut rhs = [0.0; 3];
5799        for (g, r) in &rows {
5800            let g = [g.x(), g.y(), g.z()];
5801            for i in 0..3 {
5802                rhs[i] -= g[i] * r;
5803                for j in 0..3 {
5804                    m[i][j] = g[i].madd(g[j], m[i][j]);
5805                }
5806            }
5807        }
5808        let damp = 1e-12 * (m[0][0] + m[1][1] + m[2][2]);
5809        for (i, row) in m.iter_mut().enumerate() {
5810            row[i] += damp;
5811        }
5812        let Some(step) = solve3(m, rhs) else {
5813            break;
5814        };
5815        // Each candidate moves back onto `a` along its normal, where a touch
5816        // leaves it on `b` too.
5817        let onto_a = |x: Point3| a.distance(x).map_or(x, |(d, n)| x - n * d);
5818        let next = [1.0, 2.0, 3.0]
5819            .iter()
5820            .map(|&k| onto_a(q + step * k))
5821            .min_by(|x, y| miss(*x).total_cmp(&miss(*y)))?;
5822        if (next - p).length() > reach || miss(next) >= miss(q) {
5823            break;
5824        }
5825        q = next;
5826    }
5827    best.and_then(|(_, x, holds)| holds.then_some(x))
5828}
5829
5830/// The solution of `m x = rhs` for a symmetric 3 by 3 `m`, by Cramer's rule;
5831/// `None` where `m` is singular.
5832fn solve3(m: [[f64; 3]; 3], rhs: [f64; 3]) -> Option<Vec3> {
5833    let det = |c: [[f64; 3]; 3]| {
5834        c[0][0] * c[1][1].madd(c[2][2], -c[1][2] * c[2][1])
5835            - c[0][1] * c[1][0].madd(c[2][2], -c[1][2] * c[2][0])
5836            + c[0][2] * c[1][0].madd(c[2][1], -c[1][1] * c[2][0])
5837    };
5838    let d = det(m);
5839    if d.abs() <= 0.0 || !d.is_finite() {
5840        return None;
5841    }
5842    let mut out = [0.0; 3];
5843    for (k, x) in out.iter_mut().enumerate() {
5844        let mut c = m;
5845        for (row, r) in c.iter_mut().zip(rhs) {
5846            row[k] = r;
5847        }
5848        *x = det(c) / d;
5849    }
5850    Some(Vec3::new(out[0], out[1], out[2]))
5851}
5852
5853/// March along the section of two surfaces from `seed`, a point on it, each
5854/// way, until the march comes back to the seed, leaves a patch or the
5855/// region, or stops by a point where the section's branches meet or the
5856/// surfaces touch (see [`singular_point`]); `None` where it stops anywhere
5857/// else or runs out of steps.
5858///
5859/// Each step goes along the tangent, no farther than [`Station::reach`],
5860/// and moves onto the section by Newton steps. It is taken again at half the
5861/// length unless the move onto the section stays within [`MARCH_BASIN`] of
5862/// the gap at both ends and on the sheets the seed lies on (a cone's nappe,
5863/// a torus's tube), so the step stays on its branch, the tangent turns by
5864/// less than twice [`MARCH_TURN`], and the step goes forward by at least
5865/// half its length (so it does not pass a turn of the section). A march
5866/// closes where the seed lies within its next step, ahead along the
5867/// tangent and near it, and the section there runs the way it ran from the
5868/// seed: the march comes back to the seed along the curve, from the seed's
5869/// own side.
5870#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
5871fn march_analytic_intersection(
5872    a: &AnalyticSurface<'_>,
5873    b: &AnalyticSurface<'_>,
5874    surf_a: &dyn Fn(f64, f64) -> Point3,
5875    norm_a: &dyn Fn(f64, f64) -> Vec3,
5876    surf_b: &dyn Fn(f64, f64) -> Point3,
5877    norm_b: &dyn Fn(f64, f64) -> Vec3,
5878    seed: Point3,
5879    u_range_a: (f64, f64),
5880    v_range_a: (f64, f64),
5881    u_range_b: (f64, f64),
5882    v_range_b: (f64, f64),
5883    initial_step: f64,
5884    u_periodic_a: bool,
5885    u_periodic_b: bool,
5886    region: Option<Aabb3>,
5887) -> Option<Vec<Point3>> {
5888    let h_max = initial_step * 4.0;
5889    let h_min = initial_step * 1e-6;
5890
5891    // Whether `q` lies off either patch, its feet clamped to a patch's edge.
5892    let off_patch = |q: Point3| {
5893        let (ua, va) = project_analytic(a, q, u_range_a, v_range_a);
5894        let (ub, vb) = project_analytic(b, q, u_range_b, v_range_b);
5895        (!u_periodic_a && (ua <= u_range_a.0 || ua >= u_range_a.1))
5896            || va <= v_range_a.0
5897            || va >= v_range_a.1
5898            || (!u_periodic_b && (ub <= u_range_b.0 || ub >= u_range_b.1))
5899            || vb <= v_range_b.0
5900            || vb >= v_range_b.1
5901    };
5902    // The point on the intersection that the step from `from` reaches.
5903    let on_curve = |from: Point3, step: Vec3| {
5904        correct_to_intersection(
5905            a,
5906            b,
5907            surf_a,
5908            norm_a,
5909            surf_b,
5910            norm_b,
5911            from + step,
5912            u_range_a,
5913            v_range_a,
5914            u_range_b,
5915            v_range_b,
5916            5,
5917        )
5918    };
5919    // The last point on the intersection still on both patches along the
5920    // step from `from`, whose end lies off a patch: on the patch's edge the
5921    // step crosses, bisected; `None` when the step leaves at once.
5922    let last_on_patch = |from: Point3, step: Vec3| {
5923        let (mut lo, mut hi) = (0.0, 1.0);
5924        for _ in 0..48 {
5925            let s = f64::midpoint(lo, hi);
5926            if off_patch(on_curve(from, step * s)) {
5927                hi = s;
5928            } else {
5929                lo = s;
5930            }
5931        }
5932        (lo > 0.0).then(|| on_curve(from, step * lo))
5933    };
5934
5935    let start = station(a, b, seed, Vec3::new(0.0, 0.0, 0.0))?;
5936    // The sheets of both surfaces a point lies on: a step stays on its own.
5937    let sheets = |q: Point3| {
5938        use section_fit::Carrier;
5939        (a.sheet(q), b.sheet(q))
5940    };
5941    let home_sheets = sheets(seed);
5942
5943    // March forward from seed, collecting points.
5944    let mut forward = Vec::new();
5945    // March backward from seed, collecting points (reversed at end).
5946    let mut backward = Vec::new();
5947
5948    // A loop the forward march closes is whole: marched back as well, it
5949    // would come round a second time.
5950    let mut looped = false;
5951    for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
5952        if looped {
5953            break;
5954        }
5955        let home = start.t * direction;
5956        let mut here = Station { t: home, ..start };
5957        let mut h = here.reach(h_max.min(initial_step));
5958        let mut ended = false;
5959
5960        for _ in 0..MARCH_STEPS {
5961            h = h.min(here.reach(h_max));
5962            if !points.is_empty() {
5963                let to_seed = seed - here.p;
5964                let ahead = to_seed.dot(here.t);
5965                let aside = (to_seed - here.t * ahead).length();
5966                if ahead > 0.0
5967                    && ahead <= h
5968                    && aside <= MARCH_TURN * ahead
5969                    && aside <= MARCH_BASIN * here.gap.min(start.gap)
5970                    && home.dot(here.t) >= (2.0 * MARCH_TURN).cos()
5971                {
5972                    points.push(seed);
5973                    looped = true;
5974                    ended = true;
5975                    break;
5976                }
5977            }
5978
5979            let next = loop {
5980                if h < h_min {
5981                    break None;
5982                }
5983                let guess = Point3::new(
5984                    h.madd(here.t.x(), here.p.x()),
5985                    h.madd(here.t.y(), here.p.y()),
5986                    h.madd(here.t.z(), here.p.z()),
5987                );
5988                let taken = settle_on_section(a, b, guess)
5989                    .and_then(|q| station(a, b, q, here.t))
5990                    .filter(|next| {
5991                        let missed = (next.p - guess).length();
5992                        missed <= MARCH_BASIN * here.gap.min(next.gap)
5993                            && missed <= 0.5 * h
5994                            && next.t.dot(here.t) >= (2.0 * MARCH_TURN).cos()
5995                            && (next.p - here.p).dot(here.t) >= 0.5 * h
5996                            && sheets(next.p) == home_sheets
5997                    });
5998                match taken {
5999                    Some(next) => break Some(next),
6000                    None => h *= 0.5,
6001                }
6002            };
6003            // A step a millionth of the first that still leaves its branch,
6004            // turns back, or finds no crossing ends the curve only on a
6005            // point near where the section's branches meet or the surfaces
6006            // touch, as at a patch's edge. Anywhere else the march cannot
6007            // follow the section, and the section is refused.
6008            let Some(next) = next else {
6009                let end = singular_point(a, b, here.p, initial_step)?;
6010                points.push(end);
6011                ended = true;
6012                break;
6013            };
6014
6015            if off_patch(next.p) {
6016                // The step crosses a patch's edge. End the curve on that
6017                // edge, neither a step short of it nor past it, where the
6018                // faces' other sections meet it.
6019                points.extend(last_on_patch(here.p, next.p - here.p));
6020                ended = true;
6021                break;
6022            }
6023            if region.is_some_and(|r| !r.contains_point(next.p)) {
6024                points.push(next.p);
6025                ended = true;
6026                break;
6027            }
6028            points.push(next.p);
6029            here = next;
6030            h *= 2.0;
6031        }
6032        if !ended {
6033            return None;
6034        }
6035    }
6036
6037    // Assemble result: backward (reversed) + seed + forward
6038    backward.reverse();
6039    let mut result = backward;
6040    result.push(seed);
6041    result.append(&mut forward);
6042
6043    // A seed settles onto the intersection with its feet clamped to the
6044    // patches, so one can lie just past a patch's edge and end the curve
6045    // there: move that end back onto the edge.
6046    if let [first, second, ..] = result[..]
6047        && off_patch(first)
6048        && !off_patch(second)
6049        && let Some(edge) = last_on_patch(second, first - second)
6050    {
6051        result[0] = edge;
6052    }
6053    if let [.., second, last] = result[..]
6054        && off_patch(last)
6055        && !off_patch(second)
6056        && let Some(edge) = last_on_patch(second, last - second)
6057        && let Some(end) = result.last_mut()
6058    {
6059        *end = edge;
6060    }
6061
6062    // Settle each point onto the intersection curve, to rounding where
6063    // Newton steps on both surfaces' distances converge.
6064    for pt in &mut result {
6065        let from = *pt;
6066        *pt = settle_on_section(a, b, from)
6067            .filter(|on| (*on - from).length() <= initial_step)
6068            .unwrap_or_else(|| {
6069                correct_to_intersection(
6070                    a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b,
6071                    v_range_b, 5,
6072                )
6073            });
6074    }
6075
6076    Some(result)
6077}
6078
6079/// Project a 3D point onto an analytic surface using the surface's
6080/// analytical projection method. Falls back to grid search for surface
6081/// types without analytical projection.
6082fn project_analytic(
6083    surface: &AnalyticSurface<'_>,
6084    point: Point3,
6085    u_range: (f64, f64),
6086    v_range: (f64, f64),
6087) -> (f64, f64) {
6088    match surface {
6089        AnalyticSurface::Cylinder(cyl) => {
6090            let (u, v) = cyl.project_point(point);
6091            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6092        }
6093        AnalyticSurface::Sphere(sphere) => {
6094            let (u, v) = sphere.project_point(point);
6095            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6096        }
6097        // A foot on the negative nappe lies along `-radial(u)` from the apex:
6098        // its `u` is half a turn from the point's own side of the axis.
6099        AnalyticSurface::Cone(cone) => {
6100            let (u, v) = cone.project_point(point);
6101            let v = v.clamp(v_range.0, v_range.1);
6102            let u = if v < 0.0 {
6103                (u + std::f64::consts::PI).rem_euclid(TAU)
6104            } else {
6105                u
6106            };
6107            (u.clamp(u_range.0, u_range.1), v)
6108        }
6109        AnalyticSurface::Torus(torus) => {
6110            let (u, v) = torus.project_point(point);
6111            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6112        }
6113    }
6114}
6115
6116/// Returns `true` if the surface's u-parameter is periodic (wraps around 2π).
6117/// All current `AnalyticSurface` variants have periodic u — this is trivially
6118/// true today but exists as a guard for future non-periodic analytic types.
6119fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
6120    matches!(
6121        surface,
6122        AnalyticSurface::Cylinder(_)
6123            | AnalyticSurface::Cone(_)
6124            | AnalyticSurface::Sphere(_)
6125            | AnalyticSurface::Torus(_)
6126    )
6127}
6128
6129/// Extract closures and parameter ranges for an analytic surface.
6130#[allow(clippy::type_complexity)]
6131fn surface_closures<'a>(
6132    surface: &'a AnalyticSurface<'a>,
6133) -> (
6134    Box<dyn Fn(f64, f64) -> Point3 + 'a>,
6135    Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
6136    (f64, f64),
6137    (f64, f64),
6138) {
6139    match surface {
6140        AnalyticSurface::Cylinder(cyl) => (
6141            Box::new(|u, v| cyl.evaluate(u, v)),
6142            Box::new(|u, v| cyl.normal(u, v)),
6143            (0.0, TAU),
6144            (-1.0, 1.0),
6145        ),
6146        AnalyticSurface::Cone(cone) => (
6147            Box::new(|u, v| cone.evaluate(u, v)),
6148            Box::new(|u, v| cone.normal(u, v)),
6149            (0.0, TAU),
6150            (0.01, 2.0),
6151        ),
6152        AnalyticSurface::Sphere(sphere) => (
6153            Box::new(|u, v| sphere.evaluate(u, v)),
6154            Box::new(|u, v| sphere.normal(u, v)),
6155            (0.0, TAU),
6156            (-FRAC_PI_2, FRAC_PI_2),
6157        ),
6158        AnalyticSurface::Torus(torus) => (
6159            Box::new(|u, v| torus.evaluate(u, v)),
6160            Box::new(|u, v| torus.normal(u, v)),
6161            (0.0, TAU),
6162            (0.0, TAU),
6163        ),
6164    }
6165}
6166
6167#[cfg(test)]
6168#[allow(clippy::unwrap_used, clippy::expect_used)]
6169mod tests {
6170    use super::*;
6171    use crate::tolerance::Tolerance;
6172
6173    /// Arcs of a cone's hyperbola (a plane parallel to the axis) and parabola
6174    /// (a plane parallel to a ruling) between two of their sampled points
6175    /// stay on both the plane and the cone everywhere, not just at samples.
6176    #[test]
6177    fn plane_cone_conic_arcs_lie_on_both_surfaces() {
6178        let half_angle = 1.1_f64;
6179        let cone = ConicalSurface::new(
6180            Point3::new(0.0, 0.0, 0.0),
6181            Vec3::new(0.0, 0.0, 1.0),
6182            half_angle,
6183        )
6184        .unwrap();
6185        let ruling = Vec3::new(half_angle.sin(), 0.0, half_angle.cos());
6186        for (normal, d) in [(Vec3::new(1.0, 0.0, 0.0), 0.5), (ruling, 1.0)] {
6187            let chains =
6188                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, d, 10.0)
6189                    .unwrap();
6190            let chain = chains
6191                .iter()
6192                .find_map(|c| match c {
6193                    ExactIntersectionCurve::Points(chain) => Some(chain),
6194                    _ => None,
6195                })
6196                .expect("a parabola or hyperbola section is sampled");
6197            let (from, to) = (chain[2], chain[chain.len() - 3]);
6198            let arc = plane_cone_conic_arc(&cone, normal, d, from, to)
6199                .unwrap()
6200                .expect("an exact arc");
6201            let (t0, t1) = arc.domain();
6202            assert!((arc.evaluate(t0) - from).length() < 1e-12);
6203            assert!((arc.evaluate(t1) - to).length() < 1e-12);
6204            for i in 0..=200 {
6205                let q = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0);
6206                let w = q - Point3::new(0.0, 0.0, 0.0);
6207                let off_plane = (normal.dot(w) - d).abs();
6208                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
6209                assert!(off_plane < 1e-9, "off the plane by {off_plane}");
6210                assert!(off_cone < 1e-9, "off the cone by {off_cone}");
6211            }
6212        }
6213    }
6214
6215    /// A plane a few 1e-10 short of parallel to a ruling cuts a vast ellipse
6216    /// that the parabola's closed form only approximates: the arc is either
6217    /// declined or on the cone, and an arc with coincident ends is declined.
6218    #[test]
6219    fn plane_cone_conic_arc_declines_a_near_parabolic_ellipse() {
6220        let half_angle = 1.1_f64;
6221        let cone = ConicalSurface::new(
6222            Point3::new(0.0, 0.0, 0.0),
6223            Vec3::new(0.0, 0.0, 1.0),
6224            half_angle,
6225        )
6226        .unwrap();
6227        for shortfall in [1e-10, 3e-10, 8e-10] {
6228            let tilt = half_angle - shortfall / (2.0 * half_angle).sin();
6229            let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
6230            let chains =
6231                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, 1.0, 10.0)
6232                    .unwrap();
6233            let Some(chain) = chains.iter().find_map(|c| match c {
6234                ExactIntersectionCurve::Points(chain) => Some(chain),
6235                _ => None,
6236            }) else {
6237                continue;
6238            };
6239            let (from, to) = (chain[2], chain[chain.len() - 3]);
6240            assert!(
6241                plane_cone_conic_arc(&cone, normal, 1.0, from, from)
6242                    .unwrap()
6243                    .is_none(),
6244                "coincident ends"
6245            );
6246            let Some(arc) = plane_cone_conic_arc(&cone, normal, 1.0, from, to).unwrap() else {
6247                continue;
6248            };
6249            let (t0, t1) = arc.domain();
6250            for i in 0..=200 {
6251                let w = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0)
6252                    - Point3::new(0.0, 0.0, 0.0);
6253                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
6254                assert!(off_cone < 1e-8, "{shortfall}: off the cone by {off_cone}");
6255            }
6256        }
6257    }
6258
6259    #[test]
6260    fn plane_cylinder_perpendicular() {
6261        let cyl =
6262            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
6263                .unwrap();
6264
6265        // Horizontal plane at z=3 -- produces a circle at height 3.
6266        let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
6267        assert!(!curves.is_empty(), "should find intersection curve");
6268        assert!(
6269            curves[0].points.len() > 10,
6270            "should have many sample points"
6271        );
6272
6273        let tol = Tolerance::loose();
6274        for pt in &curves[0].points {
6275            assert!(
6276                tol.approx_eq(pt.point.z(), 3.0),
6277                "z should be ~3.0, got {}",
6278                pt.point.z()
6279            );
6280            let r = pt.point.x().hypot(pt.point.y());
6281            assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
6282        }
6283    }
6284
6285    #[test]
6286    fn plane_sphere_equator() {
6287        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
6288
6289        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
6290        assert!(!curves.is_empty());
6291
6292        let tol = Tolerance::loose();
6293        for pt in &curves[0].points {
6294            assert!(
6295                tol.approx_eq(pt.point.z(), 0.0),
6296                "z should be ~0, got {}",
6297                pt.point.z()
6298            );
6299            let r = pt.point.x().hypot(pt.point.y());
6300            assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
6301        }
6302    }
6303
6304    #[test]
6305    fn plane_sphere_no_intersection() {
6306        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
6307
6308        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
6309        assert!(curves.is_empty());
6310    }
6311
6312    #[test]
6313    fn plane_cone_cross_section() {
6314        let cone = ConicalSurface::new(
6315            Point3::new(0.0, 0.0, 0.0),
6316            Vec3::new(0.0, 0.0, 1.0),
6317            std::f64::consts::FRAC_PI_4,
6318        )
6319        .unwrap();
6320
6321        let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
6322        assert!(!curves.is_empty(), "should find intersection with cone");
6323    }
6324
6325    /// The 1u gridfinity spacer lip fuse corner (#1570): the body's lip
6326    /// recess cone (45 deg, opening downward) meets the tool's lip cone
6327    /// (45 deg, opening upward) with axes offset 0.25mm in x and y. Equal
6328    /// half-angle tangents put the whole intersection on the radical plane,
6329    /// so the section is one exact ellipse; the marcher shredded this into
6330    /// ~64 closed micro-loops per pair.
6331    #[test]
6332    fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
6333        let c1 = ConicalSurface::new(
6334            Point3::new(
6335                -16.999_999_999_999_975,
6336                -16.999_999_999_999_975,
6337                5.849_999_999_999_951,
6338            ),
6339            Vec3::new(0.0, 0.0, -1.0),
6340            0.785_398_163_397_433_5,
6341        )
6342        .unwrap();
6343        let c2 = ConicalSurface::new(
6344            Point3::new(
6345                -16.750_000_000_000_036,
6346                -16.750_000_000_000_018,
6347                0.749_999_999_999_881,
6348            ),
6349            Vec3::new(0.0, 0.0, 1.0),
6350            0.785_398_163_397_467_6,
6351        )
6352        .unwrap();
6353
6354        let curves = exact_cone_cone(&c1, &c2)
6355            .unwrap()
6356            .expect("offset parallel equal-angle cones must take the radical-plane path");
6357        assert_eq!(curves.len(), 1, "expected exactly one section conic");
6358        assert!(
6359            matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
6360            "expected an ellipse section, got {:?}",
6361            curves[0]
6362        );
6363        let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
6364            return;
6365        };
6366
6367        // Every sample must lie on BOTH cones: distance to the axis equals
6368        // tan(half_angle) times the axial distance from the apex, on the
6369        // real nappe of each.
6370        for i in 0..16 {
6371            let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
6372            for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
6373                let rel = p - cone.apex();
6374                let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
6375                let axial = rel_v.dot(cone.axis());
6376                let radial = (rel_v - cone.axis() * axial).length();
6377                assert!(
6378                    axial > 0.0,
6379                    "{label}: sample on phantom nappe (axial {axial})"
6380                );
6381                let expect = cone.half_angle().tan() * axial;
6382                assert!(
6383                    (radial - expect).abs() < 1e-9,
6384                    "{label}: sample off surface by {}",
6385                    (radial - expect).abs()
6386                );
6387            }
6388        }
6389    }
6390
6391    /// Opposed cones whose real nappes occupy disjoint half-spaces share a
6392    /// radical-plane conic only on the phantom nappe — the exact path must
6393    /// report a definitive empty intersection, not defer to the marcher.
6394    #[test]
6395    fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
6396        let c1 = ConicalSurface::new(
6397            Point3::new(0.0, 0.0, 5.0),
6398            Vec3::new(0.0, 0.0, -1.0),
6399            std::f64::consts::FRAC_PI_4,
6400        )
6401        .unwrap();
6402        let c2 = ConicalSurface::new(
6403            Point3::new(0.25, 0.25, 20.0),
6404            Vec3::new(0.0, 0.0, 1.0),
6405            std::f64::consts::FRAC_PI_4,
6406        )
6407        .unwrap();
6408        let curves = exact_cone_cone(&c1, &c2)
6409            .unwrap()
6410            .expect("radical-plane path");
6411        assert!(curves.is_empty(), "disjoint nappes must yield no curves");
6412    }
6413
6414    /// Unequal half-angles keep a quadratic term in the pencil — no plane
6415    /// reduction exists, so the exact path must defer to the marcher.
6416    #[test]
6417    fn offset_parallel_cones_with_unequal_angles_defer() {
6418        let c1 = ConicalSurface::new(
6419            Point3::new(0.0, 0.0, 5.0),
6420            Vec3::new(0.0, 0.0, -1.0),
6421            std::f64::consts::FRAC_PI_4,
6422        )
6423        .unwrap();
6424        let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
6425            .unwrap();
6426        assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
6427    }
6428
6429    /// A 45 degree cone and a radius 0.1 tube tilted 40 degrees that pierces
6430    /// both nappes, so the ruling path declines and the general marcher runs:
6431    /// the tube's axis meets the near nappe at (0.1, -1.368, 1.370).
6432    fn cone_and_tilted_tube() -> (ConicalSurface, CylindricalSurface) {
6433        let cone = ConicalSurface::new(
6434            Point3::new(0.0, 0.0, 0.0),
6435            Vec3::new(0.0, 0.0, 1.0),
6436            std::f64::consts::FRAC_PI_4,
6437        )
6438        .unwrap();
6439        let (s, c) = 40.0_f64.to_radians().sin_cos();
6440        let tube =
6441            CylindricalSurface::new(Point3::new(0.1, 0.0, 3.0), Vec3::new(0.0, s, c), 0.1).unwrap();
6442        (cone, tube)
6443    }
6444
6445    #[test]
6446    fn marcher_keeps_to_its_region() {
6447        let (cone, tube) = cone_and_tilted_tube();
6448        let run = |region: Option<Aabb3>| {
6449            let (a, b) = (
6450                AnalyticSurface::Cone(&cone),
6451                AnalyticSurface::Cylinder(&tube),
6452            );
6453            let (va, vb) = (Some((0.5, 4.0)), Some((-5.0, 5.0)));
6454            match region {
6455                Some(r) => intersect_analytic_analytic_in_region(a, b, 32, va, vb, r),
6456                None => intersect_analytic_analytic_bounded(a, b, 32, va, vb),
6457            }
6458            .unwrap()
6459        };
6460        assert!(!run(None).is_empty());
6461        let near = Aabb3 {
6462            min: Point3::new(-0.5, -2.0, 0.8),
6463            max: Point3::new(0.7, -0.7, 2.0),
6464        };
6465        let curves = run(Some(near));
6466        assert!(!curves.is_empty(), "the loop through the region is kept");
6467        // The region's margin (two grid cells) and one marching step past it.
6468        let reach = near.expanded(0.6);
6469        for curve in &curves {
6470            assert!(curve.points.iter().all(|p| reach.contains_point(p.point)));
6471        }
6472        let away = Aabb3 {
6473            min: Point3::new(5.0, 5.0, 5.0),
6474            max: Point3::new(6.0, 6.0, 6.0),
6475        };
6476        assert!(run(Some(away)).is_empty(), "nothing is marched outside it");
6477    }
6478
6479    #[test]
6480    fn coaxial_cones_cross_at_single_circle() {
6481        // Two coaxial truncated cones (outer base r10->top r8, inner r9->r8
6482        // over height 10) cross where their radii match: z=10, r=8. The
6483        // intersection must be ONE clean circle, not the dozens of degenerate
6484        // micro-curves the general marcher produces at near-tangency.
6485        let outer = ConicalSurface::new(
6486            Point3::new(0.0, 0.0, 50.0),
6487            Vec3::new(0.0, 0.0, -1.0),
6488            5.0_f64.atan(),
6489        )
6490        .unwrap();
6491        let inner = ConicalSurface::new(
6492            Point3::new(0.0, 0.0, 90.0),
6493            Vec3::new(0.0, 0.0, -1.0),
6494            10.0_f64.atan(),
6495        )
6496        .unwrap();
6497
6498        let curves = intersect_analytic_analytic_bounded(
6499            AnalyticSurface::Cone(&outer),
6500            AnalyticSurface::Cone(&inner),
6501            32,
6502            None,
6503            None,
6504        )
6505        .unwrap();
6506
6507        assert_eq!(
6508            curves.len(),
6509            1,
6510            "coaxial cones crossing at one circle must yield exactly one curve, got {}",
6511            curves.len()
6512        );
6513        for p in &curves[0].points {
6514            let r = p.point.x().hypot(p.point.y());
6515            assert!(
6516                (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
6517                "intersection point off the expected z=10,r=8 circle: {:?}",
6518                p.point
6519            );
6520        }
6521    }
6522
6523    #[test]
6524    fn plane_torus_cross_section() {
6525        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
6526
6527        let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
6528        assert!(
6529            !curves.is_empty(),
6530            "should find intersection curves with torus"
6531        );
6532    }
6533
6534    /// A plane resting on a torus's tube touches it along one circle of the
6535    /// torus's own radius, ring or spindle, at the tube's top or bottom.
6536    #[test]
6537    fn plane_tangent_to_a_tube_touches_it_along_one_circle() {
6538        for (major, minor) in [(5.0, 1.0), (0.1, 2.45)] {
6539            let torus = ToroidalSurface::new(Point3::new(1.0, 2.0, 3.0), major, minor).unwrap();
6540            for z in [3.0 - minor, 3.0 + minor] {
6541                let exact = exact_plane_analytic(
6542                    AnalyticSurface::Torus(&torus),
6543                    Vec3::new(0.0, 0.0, 1.0),
6544                    z,
6545                )
6546                .unwrap();
6547                assert_eq!(exact.len(), 1, "R={major} r={minor} z={z}");
6548                let circle = match &exact[0] {
6549                    ExactIntersectionCurve::Circle(c) => Some(c),
6550                    _ => None,
6551                };
6552                let c = circle.expect("a circle");
6553                assert!((c.radius() - major).abs() < 1e-12);
6554                assert!((c.center() - Point3::new(1.0, 2.0, z)).length() < 1e-12);
6555
6556                let sampled = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), z).unwrap();
6557                assert_eq!(sampled.len(), 1, "R={major} r={minor} z={z}");
6558            }
6559            // A tilted plane cuts no single circle of radius R.
6560            let single = |normal: Vec3, d: f64| {
6561                matches!(
6562                    exact_plane_analytic(AnalyticSurface::Torus(&torus), normal, d)
6563                        .unwrap()
6564                        .as_slice(),
6565                    [ExactIntersectionCurve::Circle(_)]
6566                )
6567            };
6568            assert!(!single(Vec3::new(1e-6, 0.0, 1.0), 3.0 + minor));
6569        }
6570    }
6571
6572    /// Tangency is read from the plane's distance to the tube's top, so it
6573    /// survives rounding on a large torus, and a plane further inside than
6574    /// the linear tolerance still cuts its two circles.
6575    #[test]
6576    fn plane_tangent_to_a_large_tube_is_read_through_rounding() {
6577        let torus = ToroidalSurface::new(Point3::new(0.3, -0.7, 3.0), 200.0, 100.1).unwrap();
6578        let level = Vec3::new(0.0, 0.0, 1.0);
6579        let curves =
6580            |d: f64| exact_plane_analytic(AnalyticSurface::Torus(&torus), level, d).unwrap();
6581        assert!(matches!(
6582            curves(3.0 + 100.1).as_slice(),
6583            [ExactIntersectionCurve::Circle(_)]
6584        ));
6585        let inside = curves(3.0 + 100.1 - 4e-7);
6586        assert!(!matches!(
6587            inside.as_slice(),
6588            [ExactIntersectionCurve::Circle(_)]
6589        ));
6590    }
6591
6592    /// Signed distance of a point to a z-axis torus centred at the origin:
6593    /// `sqrt((sqrt(x^2+y^2) - R)^2 + z^2) - r`.
6594    fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
6595        let rho = p.x().hypot(p.y());
6596        ((rho - major).hypot(p.z())) - minor
6597    }
6598
6599    /// The gridfinity lightweight base's failing corner, reduced: a cavity
6600    /// corner-round cone (apex below the floor, 45 deg, axis +z) crossed by a
6601    /// parallel-axis boss cylinder. The general marcher returned ~49 overlapping
6602    /// partial traces of one curve here; the algebraic path must return exactly
6603    /// the two branches, each ON both surfaces and inside the cone's v-hint.
6604    #[test]
6605    fn oblique_cone_cylinder_traces_curves_on_both() {
6606        use crate::traits::ParametricCurve;
6607        // A pointed cone opening down from (0, 0, 3), radius half the depth,
6608        // and a rod along y through (x0, ., 1): one loop through the wall
6609        // when the rod pokes out, two when every ruling meets the cone.
6610        let cone = ConicalSurface::new(
6611            Point3::new(0.0, 0.0, 3.0),
6612            Vec3::new(0.0, 0.0, -1.0),
6613            2.0_f64.atan(),
6614        )
6615        .unwrap();
6616        for (x0, loops) in [(0.5, 1), (0.0, 2)] {
6617            let cyl =
6618                CylindricalSurface::new(Point3::new(x0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6619                    .unwrap();
6620            for cone_first in [true, false] {
6621                let (a, b) = if cone_first {
6622                    (
6623                        AnalyticSurface::Cone(&cone),
6624                        AnalyticSurface::Cylinder(&cyl),
6625                    )
6626                } else {
6627                    (
6628                        AnalyticSurface::Cylinder(&cyl),
6629                        AnalyticSurface::Cone(&cone),
6630                    )
6631                };
6632                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6633                assert_eq!(curves.len(), loops, "x0 {x0}: loops");
6634                for c in &curves {
6635                    let (t0, t1) = c.curve.domain();
6636                    for k in 0..=64 {
6637                        let t = (t1 - t0).madd(f64::from(k) / 64.0, t0);
6638                        let p = ParametricCurve::evaluate(&c.curve, t);
6639                        // A cubic through the ruling samples, bent most at the
6640                        // loop's branch points.
6641                        let rod = (p.x() - x0).hypot(p.z() - 1.0);
6642                        assert!(
6643                            (rod - 0.6).abs() < 1e-4,
6644                            "x0 {x0}: off the rod by {}",
6645                            rod - 0.6
6646                        );
6647                        let cone_r = p.x().hypot(p.y());
6648                        assert!(
6649                            (cone_r - 0.5 * (3.0 - p.z())).abs() < 1e-4,
6650                            "x0 {x0}: off the cone at {p:?}"
6651                        );
6652                    }
6653                }
6654            }
6655        }
6656    }
6657
6658    #[test]
6659    fn a_rod_through_a_rings_tube_traces_four_loops() {
6660        use crate::traits::ParametricCurve;
6661        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6662        // Along y through (0.5, ., 0.3): every ruling enters and leaves the
6663        // tube on either side of the hole, four roots, four loops.
6664        let rod =
6665            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.3), Vec3::new(0.0, 1.0, 0.0), 0.6)
6666                .unwrap();
6667        let curves = ruling_torus_cylinder(&ring, &rod, true).unwrap();
6668        assert_eq!(curves.len(), 4);
6669        for c in &curves {
6670            let (t0, t1) = c.curve.domain();
6671            for k in 0..=64 {
6672                let p =
6673                    ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 64.0, t0));
6674                let on_rod = (p.x() - 0.5).hypot(p.z() - 0.3) - 0.6;
6675                let on_ring = (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
6676                assert!(
6677                    on_rod.abs() < 1e-4 && on_ring.abs() < 1e-4,
6678                    "off by {on_rod}, {on_ring}"
6679                );
6680            }
6681        }
6682        // Higher, the rod's top rulings pass over the tube: the count varies.
6683        let high =
6684            CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6685                .unwrap();
6686        assert!(ruling_torus_cylinder(&ring, &high, true).is_none());
6687        // Its top clears the tube only between two sampled rulings.
6688        let grazing =
6689            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.9001), Vec3::new(0.0, 1.0, 0.0), 0.6)
6690                .unwrap();
6691        assert!(ruling_torus_cylinder(&ring, &grazing, true).is_none());
6692        // A spindle torus's quartic also holds its inner lemon.
6693        let spindle = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap();
6694        let thin =
6695            CylindricalSurface::new(Point3::new(0.3, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 0.2)
6696                .unwrap();
6697        assert!(ruling_torus_cylinder(&spindle, &thin, true).is_none());
6698    }
6699
6700    #[test]
6701    fn a_pin_through_a_ball_traces_two_loops() {
6702        use crate::traits::ParametricCurve;
6703        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
6704        // A pin tapering from radius 1.2 at (1, 0.5, -5) to 0.4 at 10 up:
6705        // radial 0.08 per unit of height.
6706        let half = 0.08_f64.atan();
6707        let apex = Point3::new(1.0, 0.5, -5.0 + 1.2 / 0.08);
6708        let pin = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, -1.0), FRAC_PI_2 - half).unwrap();
6709        for cone_first in [true, false] {
6710            let (a, b) = if cone_first {
6711                (AnalyticSurface::Cone(&pin), AnalyticSurface::Sphere(&ball))
6712            } else {
6713                (AnalyticSurface::Sphere(&ball), AnalyticSurface::Cone(&pin))
6714            };
6715            let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6716            assert_eq!(curves.len(), 2, "entry and exit loops");
6717            for c in &curves {
6718                let (t0, t1) = c.curve.domain();
6719                for k in 0..=64 {
6720                    let p = ParametricCurve::evaluate(
6721                        &c.curve,
6722                        (t1 - t0).madd(f64::from(k) / 64.0, t0),
6723                    );
6724                    let on_ball = (p - Point3::new(0.0, 0.0, 0.0)).length() - 3.0;
6725                    let axial = apex.z() - p.z();
6726                    let on_pin = (p.x() - 1.0).hypot(p.y() - 0.5) - axial * half.tan();
6727                    assert!(
6728                        on_ball.abs() < 1e-4 && on_pin.abs() < 1e-4,
6729                        "off by {on_ball}, {on_pin}"
6730                    );
6731                }
6732            }
6733        }
6734        // On the ball's axis the loops are circles, which defer. A pin whose
6735        // apex is inside the ball leaves it once along every generator, and
6736        // one only partly through the ball meets it over the generators that
6737        // reach it: one loop each. One that opens away meets it not at all.
6738        let coaxial =
6739            ConicalSurface::new(Point3::new(0.0, 0.0, 10.0), Vec3::new(0.0, 0.0, -1.0), 1.4)
6740                .unwrap();
6741        assert!(ruling_cone_sphere(&coaxial, &ball, true).is_none());
6742        let aside = ConicalSurface::new(
6743            Point3::new(2.8, 0.0, 10.0),
6744            Vec3::new(0.0, 0.0, -1.0),
6745            FRAC_PI_2 - half,
6746        )
6747        .unwrap();
6748        assert_eq!(ruling_cone_sphere(&aside, &ball, true).unwrap().len(), 1);
6749        let holding = ConicalSurface::new(
6750            Point3::new(1.0, 0.5, 1.0),
6751            Vec3::new(0.0, 0.0, -1.0),
6752            FRAC_PI_2 - half,
6753        )
6754        .unwrap();
6755        assert_eq!(ruling_cone_sphere(&holding, &ball, true).unwrap().len(), 1);
6756        let away = ConicalSurface::new(
6757            Point3::new(1.0, 0.5, 10.0),
6758            Vec3::new(0.0, 0.0, 1.0),
6759            FRAC_PI_2 - half,
6760        )
6761        .unwrap();
6762        assert!(ruling_cone_sphere(&away, &ball, true).unwrap().is_empty());
6763        // Grazing: the generators that miss span about 0.002 radians,
6764        // narrower than a 2048-angle scan's step, and the near and far
6765        // roots join into one loop across them.
6766        let step = TAU / 2048.0;
6767        let grazed =
6768            SphericalSurface::new(Point3::new(step.cos(), step.sin(), 10.0), 9.255_250_971_8)
6769                .unwrap();
6770        let wide =
6771            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5).unwrap();
6772        assert_eq!(ruling_cone_sphere(&wide, &grazed, true).unwrap().len(), 1);
6773    }
6774
6775    #[test]
6776    fn a_ball_beside_a_cone_meets_it_in_one_loop() {
6777        use crate::traits::ParametricCurve;
6778        // Apex 3 up, opening downward, the radius half the depth below it.
6779        let cone = ConicalSurface::new(
6780            Point3::new(0.0, 0.0, 3.0),
6781            Vec3::new(0.0, 0.0, -1.0),
6782            2.0_f64.atan(),
6783        )
6784        .unwrap();
6785        for (centre, radius) in [
6786            (Point3::new(1.0, 0.8, 1.2), 1.1),
6787            (Point3::new(1.5, 0.0, 0.0), 0.8),
6788        ] {
6789            let ball = SphericalSurface::new(centre, radius).unwrap();
6790            let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
6791            assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
6792            let (t0, t1) = curves[0].curve.domain();
6793            for k in 0..=64 {
6794                let p = ParametricCurve::evaluate(
6795                    &curves[0].curve,
6796                    (t1 - t0).madd(f64::from(k) / 64.0, t0),
6797                );
6798                let on_ball = (p - centre).length() - radius;
6799                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6800                assert!(
6801                    on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5,
6802                    "ball at {centre:?}: off by {on_ball}, {on_cone}"
6803                );
6804            }
6805        }
6806        // A ball the nappe's generators miss, and one on the apex.
6807        let clear = SphericalSurface::new(Point3::new(4.0, 0.0, 0.0), 0.5).unwrap();
6808        assert!(ruling_cone_sphere(&cone, &clear, true).unwrap().is_empty());
6809        let on_apex = SphericalSurface::new(Point3::new(0.6, 0.0, 3.8), 1.0).unwrap();
6810        assert!(ruling_cone_sphere(&cone, &on_apex, true).is_none());
6811    }
6812
6813    #[test]
6814    fn a_ball_holding_a_cones_apex_meets_it_in_one_loop() {
6815        use crate::traits::ParametricCurve;
6816        let cone = ConicalSurface::new(
6817            Point3::new(0.0, 0.0, 3.0),
6818            Vec3::new(0.0, 0.0, -1.0),
6819            2.0_f64.atan(),
6820        )
6821        .unwrap();
6822        // Off the axis, and barely holding the apex: the generators pointing
6823        // away from the centre leave it just past the apex.
6824        for (centre, radius) in [
6825            (Point3::new(0.5, 0.0, 2.5), 2.0),
6826            (Point3::new(-0.4, 0.3, 2.0), 1.5),
6827            (Point3::new(0.0, 0.8, 3.0), 0.8001),
6828            (Point3::new(0.0, 0.8, 3.0), 0.800_001),
6829        ] {
6830            let ball = SphericalSurface::new(centre, radius).unwrap();
6831            let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
6832            assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
6833            let (t0, t1) = curves[0].curve.domain();
6834            for k in 0..=4096 {
6835                let p = ParametricCurve::evaluate(
6836                    &curves[0].curve,
6837                    (t1 - t0).madd(f64::from(k) / 4096.0, t0),
6838                );
6839                let on_ball = (p - centre).length() - radius;
6840                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6841                assert!(
6842                    on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5 && p.z() < 3.0,
6843                    "ball at {centre:?}: off by {on_ball}, {on_cone} at {p:?}"
6844                );
6845            }
6846        }
6847    }
6848
6849    /// A pin whose tip just pierces a rod's wall meets the rulings within
6850    /// 2.2e-4 of the wall's top, between two of the 128 samples. The
6851    /// sample nearest them misses the pin, its discriminant -5.9e-8 within
6852    /// the tolerance alone: a loop traced from it would lie 3e-5 off the
6853    /// pin. The window lies between two scan points too, and the rulings
6854    /// leave the pin to the marcher.
6855    #[test]
6856    fn a_pin_tip_between_two_samples_is_not_traced_from_a_miss() {
6857        use std::f64::consts::{FRAC_PI_2, PI};
6858        let slope = 0.04375_f64;
6859        let pin = ConicalSurface::new(
6860            Point3::new(0.0, 5.005, 10.0),
6861            Vec3::new(0.0, -1.0, 0.0),
6862            (1.0 / slope).atan(),
6863        )
6864        .unwrap();
6865        let turn = FRAC_PI_2 + 5e-5 - PI / 128.0;
6866        let rod = CylindricalSurface::with_ref_dir(
6867            Point3::new(0.0, 0.0, 0.0),
6868            Vec3::new(0.0, 0.0, 1.0),
6869            5.0,
6870            Vec3::new(turn.cos(), turn.sin(), 0.0),
6871        )
6872        .unwrap();
6873        assert!(ruling_cone_cylinder(&pin, &rod, true).is_none());
6874    }
6875
6876    /// A taper pin through a rod, the rod turned about its axis: the pin's
6877    /// narrow end meets fewer than 8 of the rod's 128 sampled rulings in
6878    /// some turns, and the rulings still trace both of its loops there.
6879    #[test]
6880    fn a_taper_pin_through_a_turned_rod_traces_both_loops() {
6881        use crate::traits::ParametricCurve;
6882        let slope = 0.7_f64 / 16.0;
6883        let half = (1.0 / slope).atan();
6884        for flip in [false, true] {
6885            let (apex_y, axis_y) = if flip {
6886                (-8.0 - 0.8 / slope, 1.0)
6887            } else {
6888                (-8.0 + 1.5 / slope, -1.0)
6889            };
6890            let pin = ConicalSurface::new(
6891                Point3::new(0.0, apex_y, 10.0),
6892                Vec3::new(0.0, axis_y, 0.0),
6893                half,
6894            )
6895            .unwrap();
6896            for spin in [0.0_f64, 0.3, 0.9, 1.4, 2.0, 2.6, 3.0, 3.6] {
6897                let rod = CylindricalSurface::with_ref_dir(
6898                    Point3::new(0.0, 0.0, 0.0),
6899                    Vec3::new(0.0, 0.0, 1.0),
6900                    5.0,
6901                    Vec3::new(spin.cos(), spin.sin(), 0.0),
6902                )
6903                .unwrap();
6904                let curves = ruling_cone_cylinder(&pin, &rod, true);
6905                assert!(curves.is_some(), "spin {spin} flip {flip}: no trace");
6906                let curves = curves.unwrap();
6907                assert_eq!(curves.len(), 2, "spin {spin} flip {flip}: loops");
6908                for c in &curves {
6909                    let (t0, t1) = c.curve.domain();
6910                    for k in 0..=1000 {
6911                        let p = ParametricCurve::evaluate(
6912                            &c.curve,
6913                            (t1 - t0).madd(f64::from(k) / 1000.0, t0),
6914                        );
6915                        let on_rod = p.x().hypot(p.y()) - 5.0;
6916                        let on_pin = p.x().hypot(p.z() - 10.0) - slope * (p.y() - apex_y).abs();
6917                        assert!(
6918                            on_rod.abs() < 1e-7 && on_pin.abs() < 1e-7,
6919                            "spin {spin} flip {flip}: off by {on_rod:.2e}, {on_pin:.2e}"
6920                        );
6921                    }
6922                }
6923            }
6924        }
6925    }
6926
6927    #[test]
6928    fn oblique_cone_cylinder_defers_where_rulings_cannot_trace_it() {
6929        let t = 2.0_f64.atan();
6930        let cone =
6931            ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 0.0, -1.0), t).unwrap();
6932        // A rod through the apex meets the far nappe.
6933        let through_apex =
6934            CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6935                .unwrap();
6936        assert!(ruling_cone_cylinder(&cone, &through_apex, true).is_none());
6937        // A rod along a generator meets each ruling once.
6938        let generator = Vec3::new(t.cos(), 0.0, -t.sin());
6939        let along = CylindricalSurface::new(Point3::new(0.0, 0.3, 0.0), generator, 0.2).unwrap();
6940        assert!(ruling_cone_cylinder(&cone, &along, true).is_none());
6941        // A pin's tip just through a tube's wall: the tube's rulings that
6942        // meet it span a window narrower than the sampling.
6943        let pin =
6944            ConicalSurface::new(Point3::new(20.5, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), t).unwrap();
6945        let tube =
6946            CylindricalSurface::new(Point3::new(0.0, 0.0, -10.0), Vec3::new(0.0, 0.0, 1.0), 20.0)
6947                .unwrap();
6948        assert!(ruling_cone_cylinder(&pin, &tube, true).is_none());
6949    }
6950
6951    #[test]
6952    fn parallel_cone_cylinder_gives_two_exact_branches() {
6953        use crate::traits::ParametricCurve;
6954        let cone = ConicalSurface::new(
6955            Point3::new(-5.45, -36.55, -4.85),
6956            Vec3::new(0.0, 0.0, 1.0),
6957            std::f64::consts::FRAC_PI_4,
6958        )
6959        .unwrap();
6960        let cyl = CylindricalSurface::new(
6961            Point3::new(-8.0, -34.0, -5.0),
6962            Vec3::new(0.0, 0.0, 1.0),
6963            4.45,
6964        )
6965        .unwrap();
6966        // The cone face spans z in [-3.8, -3.0]; v = (z - apex_z) / sin(45 deg).
6967        let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
6968        let curves = intersect_analytic_analytic_bounded(
6969            AnalyticSurface::Cone(&cone),
6970            AnalyticSurface::Cylinder(&cyl),
6971            32,
6972            Some(v_hint),
6973            Some((0.0, 2.5)),
6974        )
6975        .unwrap();
6976
6977        assert_eq!(curves.len(), 2, "expected exactly the two branches");
6978        for c in &curves {
6979            let (t0, t1) = c.curve.domain();
6980            for k in 0..=32 {
6981                let t = (t1 - t0).madd(f64::from(k) / 32.0, t0);
6982                let p = ParametricCurve::evaluate(&c.curve, t);
6983                // On the cylinder: radial distance from its axis is the radius.
6984                let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
6985                assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
6986                // On the cone: radial distance from its axis is z - apex_z.
6987                let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
6988                assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
6989                // Inside the cone face's own v-window (the hint is respected).
6990                assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
6991            }
6992        }
6993    }
6994
6995    #[test]
6996    fn parallel_rod_through_a_cones_wall_closes_one_loop() {
6997        use crate::traits::ParametricCurve;
6998        // Apex 3 up, opening downward, the radius half the depth below it.
6999        let cone = ConicalSurface::new(
7000            Point3::new(0.0, 0.0, 3.0),
7001            Vec3::new(0.0, 0.0, -1.0),
7002            2.0_f64.atan(),
7003        )
7004        .unwrap();
7005        // Beside the axis: each ruling meets the nappe once.
7006        for (x, y) in [(0.0, 1.3), (1.2, 0.5)] {
7007            let rod =
7008                CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
7009                    .unwrap();
7010            let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7011                .unwrap()
7012                .unwrap();
7013            assert_eq!(curves.len(), 1, "one closed loop at ({x}, {y})");
7014            let (t0, t1) = curves[0].curve.domain();
7015            let (first, last) = (
7016                ParametricCurve::evaluate(&curves[0].curve, t0),
7017                ParametricCurve::evaluate(&curves[0].curve, t1),
7018            );
7019            assert!((first - last).length() < 1e-9, "open at ({x}, {y})");
7020            for k in 0..=64 {
7021                let p = ParametricCurve::evaluate(
7022                    &curves[0].curve,
7023                    (t1 - t0).madd(f64::from(k) / 64.0, t0),
7024                );
7025                let on_rod = (p.x() - x).hypot(p.y() - y) - 0.6;
7026                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
7027                assert!(
7028                    on_rod.abs() < 1e-5 && on_cone.abs() < 1e-5,
7029                    "({x}, {y}): off by {on_rod}, {on_cone}"
7030                );
7031            }
7032        }
7033        // Around the axis, and beside it by less than the bend the rulings
7034        // resolve: two branches.
7035        for (x, y) in [(0.3, 0.2), (0.65, 0.0)] {
7036            let rod =
7037                CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
7038                    .unwrap();
7039            let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7040                .unwrap()
7041                .unwrap();
7042            assert_eq!(curves.len(), 2, "two branches at ({x}, {y})");
7043        }
7044    }
7045
7046    /// A frustum (radius 72 to 50 over 84) and a smaller one standing beside
7047    /// its axis on the same base (radius 10 to 5 over 44, axis 70 away): the
7048    /// smaller one notches the base rim, and the section is an arch from the
7049    /// rim up to where the two circles at one height touch, in two branches
7050    /// that meet there. Each lies on both cones, between its samples too.
7051    #[test]
7052    fn parallel_cones_give_two_exact_branches() {
7053        use crate::traits::ParametricCurve;
7054        let frustum = |x: f64, r_big: f64, r_small: f64, h: f64| {
7055            let apex = h + r_small * h / (r_big - r_small);
7056            let cone = ConicalSurface::new(
7057                Point3::new(x, 0.0, apex),
7058                Vec3::new(0.0, 0.0, -1.0),
7059                apex.atan2(r_big),
7060            )
7061            .unwrap();
7062            // `v` at height `z`, from the apex down the wall.
7063            let v = move |z: f64| (apex - z) / apex.atan2(r_big).sin();
7064            (cone, v(h), v(0.0))
7065        };
7066        let (big, big_top, big_base) = frustum(0.0, 72.0, 50.0, 84.0);
7067        for (x, flip) in [(-70.0_f64, false), (70.0, true)] {
7068            let (small, small_top, small_base) = frustum(x, 10.0, 5.0, 44.0);
7069            let (first, second) = if flip {
7070                (AnalyticSurface::Cone(&small), AnalyticSurface::Cone(&big))
7071            } else {
7072                (AnalyticSurface::Cone(&big), AnalyticSurface::Cone(&small))
7073            };
7074            let (hint_first, hint_second) = if flip {
7075                ((small_top, small_base), (big_top, big_base))
7076            } else {
7077                ((big_top, big_base), (small_top, small_base))
7078            };
7079            let curves = intersect_analytic_analytic_bounded(
7080                first,
7081                second,
7082                32,
7083                Some(hint_first),
7084                Some(hint_second),
7085            )
7086            .unwrap();
7087            assert_eq!(curves.len(), 2, "x = {x}: the two branches");
7088            // The circles touch where 72 - 22 z / 84 + 10 - 5 z / 44 = 70.
7089            let touch = 12.0 / (22.0 / 84.0 + 5.0 / 44.0);
7090            let mut tops = Vec::new();
7091            for c in &curves {
7092                let (t0, t1) = c.curve.domain();
7093                let ends = [
7094                    ParametricCurve::evaluate(&c.curve, t0),
7095                    ParametricCurve::evaluate(&c.curve, t1),
7096                ];
7097                let (low, high) = if ends[0].z() < ends[1].z() {
7098                    (ends[0], ends[1])
7099                } else {
7100                    (ends[1], ends[0])
7101                };
7102                assert!(low.z().abs() < 1e-9, "x = {x}: starts at z = {}", low.z());
7103                assert!((high.z() - touch).abs() < 1e-9, "x = {x}: tops at {high:?}");
7104                tops.push(high);
7105                for k in 0..=256 {
7106                    let p = ParametricCurve::evaluate(
7107                        &c.curve,
7108                        (t1 - t0).madd(f64::from(k) / 256.0, t0),
7109                    );
7110                    let on_big = p.x().hypot(p.y()) - (72.0 - 22.0 * p.z() / 84.0);
7111                    let on_small = (p.x() - x).hypot(p.y()) - (10.0 - 5.0 * p.z() / 44.0);
7112                    assert!(
7113                        on_big.abs() < 1e-6 && on_small.abs() < 1e-6,
7114                        "x = {x}: {p:?} off by {on_big}, {on_small}"
7115                    );
7116                }
7117            }
7118            assert!((tops[0] - tops[1]).length() < 1e-9, "x = {x}: {tops:?}");
7119        }
7120    }
7121
7122    /// Apices 1 apart, radii `z` and `1.001 z` at the height `z`: the circles
7123    /// meet from `z = 1 / 2.001` up to `z = 1000`, and the two branches, fitted
7124    /// over that long span, lie on both cones between their points and meet
7125    /// at both ends.
7126    #[test]
7127    fn parallel_cones_of_nearly_equal_slope_trace_on_both() {
7128        use crate::traits::ParametricCurve;
7129        let up = Vec3::new(0.0, 0.0, 1.0);
7130        let first =
7131            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7132                .unwrap();
7133        let second =
7134            ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, (1.0 / 1.001_f64).atan()).unwrap();
7135        let curves = algebraic_parallel_cone_cone(&first, &second, None, None).unwrap();
7136        assert_eq!(curves.len(), 2, "the two branches");
7137        let mut ends = Vec::new();
7138        for c in &curves {
7139            let (t0, t1) = c.curve.domain();
7140            ends.push(ParametricCurve::evaluate(&c.curve, t0));
7141            ends.push(ParametricCurve::evaluate(&c.curve, t1));
7142            for k in 0..=4096 {
7143                let p =
7144                    ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 4096.0, t0));
7145                let on_first = p.x().hypot(p.y()) - p.z();
7146                let on_second = (p.x() - 1.0).hypot(p.y()) - 1.001 * p.z();
7147                assert!(
7148                    on_first.abs() < 1e-7 && on_second.abs() < 1e-7,
7149                    "{p:?} off by {on_first}, {on_second}"
7150                );
7151            }
7152        }
7153        let (low, high) = (1.0 / 2.001, 1000.0);
7154        for (k, z) in [(0, low), (1, high)] {
7155            let (a, b) = (ends[k], ends[2 + k]);
7156            assert!(
7157                (a.z() - z).abs() < 1e-6 * z,
7158                "branch end at {a:?}, not z = {z}"
7159            );
7160            assert!((a - b).length() < 1e-9, "branches part at {a:?} and {b:?}");
7161        }
7162    }
7163
7164    /// Two cones of one axis direction whose slopes differ by about `5e-13`:
7165    /// the narrower circle starts inside the wider one, a unit clear of its
7166    /// rim, and reaches it only near `v = 2e12`. Within a span out to `4e12`
7167    /// the cones meet, so the path does not call them apart.
7168    #[test]
7169    fn nearly_equal_slopes_meet_far_out() {
7170        let up = Vec3::new(0.0, 0.0, 1.0);
7171        let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7172            .unwrap();
7173        let (sin1, cos1) = std::f64::consts::FRAC_PI_4.sin_cos();
7174        // `rho2 - rho1 = (b - cos1) v + a`, with `b - cos1 = 5e-13` and
7175        // `a = -(d + 1)` for axes `d = 1` apart.
7176        let slope = (cos1 + 5e-13) / sin1;
7177        let along = 2.0 / slope;
7178        let narrow =
7179            ConicalSurface::new(Point3::new(1.0, 0.0, along), up, (1.0 / slope).atan()).unwrap();
7180        let curves = algebraic_parallel_cone_cone(&wide, &narrow, Some((0.0, 4e12)), None);
7181        assert!(
7182            !curves.as_ref().is_some_and(Vec::is_empty),
7183            "called apart: {:?}",
7184            curves.map(|c| c.len())
7185        );
7186    }
7187
7188    /// Two cones of one axis direction, a unit apart, bounded on their
7189    /// negative nappes: both hold `(0.125, sqrt(15)/8, -0.5)`, at `v` about
7190    /// -0.707 on the first and -1.118 on the second. The path traces positive
7191    /// nappes only, so it leaves the pair to the marcher and does not call the
7192    /// cones apart.
7193    #[test]
7194    fn parallel_cones_bounded_on_their_negative_nappes_go_to_the_marcher() {
7195        let up = Vec3::new(0.0, 0.0, 1.0);
7196        let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7197            .unwrap();
7198        let narrow = ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, 0.5_f64.atan()).unwrap();
7199        let shared = Point3::new(0.125, 15.0_f64.sqrt() / 8.0, -0.5);
7200        for cone in [&wide, &narrow] {
7201            assert!(off_cone(cone, shared).0 < 1e-12);
7202        }
7203        let (r1, r2) = (std::f64::consts::SQRT_2, 5.0_f64.sqrt());
7204        let curves = algebraic_parallel_cone_cone(
7205            &wide,
7206            &narrow,
7207            Some((-r1, -r1 / 3.0)),
7208            Some((-r2, -r2 / 3.0)),
7209        );
7210        assert!(curves.is_none(), "{:?} curves", curves.map(|c| c.len()));
7211    }
7212
7213    /// Axes `1e-5` radians apart, which a dot product within `1e-10` of one
7214    /// read as parallel: the parallel cone-cone and cone-cylinder paths both
7215    /// decline them.
7216    #[test]
7217    fn nearly_parallel_axes_take_neither_parallel_path() {
7218        let tilt = 1e-5_f64;
7219        let down = Vec3::new(0.0, 0.0, -1.0);
7220        let tilted = Vec3::new(tilt.sin(), 0.0, -tilt.cos());
7221        let big = ConicalSurface::new(
7222            Point3::new(0.0, 0.0, 274.909_090_909),
7223            down,
7224            274.909_090_909_f64.atan2(72.0),
7225        )
7226        .unwrap();
7227        let small =
7228            ConicalSurface::new(Point3::new(-70.0, 0.0, 88.0), tilted, 88.0_f64.atan2(10.0))
7229                .unwrap();
7230        assert!(algebraic_parallel_cone_cone(&big, &small, None, None).is_none());
7231        let cone = ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), down, 2.0_f64.atan()).unwrap();
7232        let rod = CylindricalSurface::new(Point3::new(1.2, 0.5, -10.0), tilted, 0.6).unwrap();
7233        assert!(
7234            algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7235                .unwrap()
7236                .is_none()
7237        );
7238    }
7239
7240    /// A coaxial pair has no radical line; the algebraic path must defer rather
7241    /// than divide by a zero axis separation.
7242    #[test]
7243    fn coaxial_cone_cylinder_defers_to_other_paths() {
7244        let cone = ConicalSurface::new(
7245            Point3::new(0.0, 0.0, 0.0),
7246            Vec3::new(0.0, 0.0, 1.0),
7247            std::f64::consts::FRAC_PI_4,
7248        )
7249        .unwrap();
7250        let cyl =
7251            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
7252                .unwrap();
7253        assert!(
7254            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
7255                .unwrap()
7256                .is_none()
7257        );
7258    }
7259
7260    #[test]
7261    fn oblique_cone_cylinder_defers_to_other_paths() {
7262        let cone = ConicalSurface::new(
7263            Point3::new(0.0, 0.0, 0.0),
7264            Vec3::new(0.0, 0.0, 1.0),
7265            std::f64::consts::FRAC_PI_4,
7266        )
7267        .unwrap();
7268        let cyl =
7269            CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7270                .unwrap();
7271        assert!(
7272            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
7273                .unwrap()
7274                .is_none()
7275        );
7276    }
7277
7278    #[test]
7279    fn plane_torus_lobe_closes_and_stays_on_surface() {
7280        use crate::traits::ParametricCurve;
7281        let (major, minor) = (10.0, 3.0);
7282        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7283
7284        // The census cutting planes (y=-4, x=6) each cut the +x and -x tube lobes
7285        // in a CLOSED oval. The greedy marcher stops one grid step short of
7286        // closing; the wrap-close must make every fitted lobe close exactly.
7287        for (n, d) in [
7288            (Vec3::new(0.0, -1.0, 0.0), 4.0),  // y = -4
7289            (Vec3::new(-1.0, 0.0, 0.0), -6.0), // x = 6
7290            (Vec3::new(0.0, 0.0, 1.0), 0.0),   // z = 0 -> two concentric circles
7291        ] {
7292            let curves = intersect_plane_torus(&torus, n, d).unwrap();
7293            assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
7294            for c in &curves {
7295                let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
7296                let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
7297                assert!(
7298                    (p0 - p1).length() < 1e-7,
7299                    "lobe not closed: gap={} (n={n:?} d={d})",
7300                    (p0 - p1).length()
7301                );
7302                // Every fitted sample stays on the torus (shape-preserving).
7303                for k in 0..=64 {
7304                    let t = f64::from(k) / 64.0;
7305                    let p = ParametricCurve::evaluate(&c.curve, t);
7306                    assert!(
7307                        torus_implicit(p, major, minor).abs() < 1e-2,
7308                        "off-surface point {p:?} implicit={}",
7309                        torus_implicit(p, major, minor)
7310                    );
7311                }
7312            }
7313        }
7314    }
7315
7316    /// A wall 0.4 outside the inner equator turns its loops tightly there.
7317    /// Between its points, each fitted loop stays on the torus and on the
7318    /// plane within the fit's bound.
7319    #[test]
7320    fn plane_torus_fits_stay_on_the_section_where_it_turns_tightly() {
7321        use crate::traits::ParametricCurve;
7322        let (major, minor) = (4.0, 1.5);
7323        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7324        for (n, d) in [
7325            (Vec3::new(0.0, 1.0, 0.0), 2.1),
7326            (Vec3::new(1.0, 0.0, 0.0), -1.9),
7327            (Vec3::new(0.0, 0.6, 0.8), 3.5),
7328        ] {
7329            let curves = intersect_plane_torus(&torus, n, d).unwrap();
7330            assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
7331            for c in &curves {
7332                for k in 0..=4000 {
7333                    let p = ParametricCurve::evaluate(&c.curve, f64::from(k) / 4000.0);
7334                    let off = ((p.x().hypot(p.y()) - major).hypot(p.z()) - minor).abs();
7335                    assert!(off <= 1e-8, "{off} off the torus at {p:?} (n={n:?} d={d})");
7336                    let off_plane = (n.dot(Vec3::new(p.x(), p.y(), p.z())) - d).abs();
7337                    assert!(off_plane <= 1e-12, "{off_plane} off the plane at {p:?}");
7338                }
7339            }
7340        }
7341    }
7342
7343    /// The plane `z = 0`'s section of the torus of radii 4 and 1.5 read
7344    /// from two of its points across the axis: the line between them strays
7345    /// 2.5 off the torus at its middle, on the axis, where no point moves onto
7346    /// the section. The fit cannot check that span, and is refused.
7347    #[test]
7348    fn a_plane_torus_fit_it_cannot_check_is_refused() {
7349        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7350        let across = [Point3::new(5.5, 0.0, 0.0), Point3::new(-5.5, 0.0, 0.0)];
7351        assert!(fit_plane_torus_section(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0, &across).is_err());
7352    }
7353
7354    /// The fit's check stops its Newton steps once they have moved a middle
7355    /// by less than a quarter of the bound. A middle it then reads as within
7356    /// the bound is within it, and a middle farther off moves onto the same
7357    /// point of the section as before, so the fit keeps the same points.
7358    #[test]
7359    fn a_short_newton_check_reads_each_middle_as_the_full_one_does() {
7360        let torus = ToroidalSurface::new(Point3::new(1.0, -2.0, 0.5), 4.0, 1.5).unwrap();
7361        let (n, d) = (Vec3::new(0.0, 2.0, 0.0), 2.0 * (2.1 - 2.0));
7362        let tol = PLANE_TORUS_FIT * 5.5;
7363        for ipts in plane_torus_loops(&torus, n, d, 128) {
7364            for (ip, power) in ipts.iter().zip((0..10).cycle()) {
7365                let off = Vec3::new(0.3, -0.7, 0.2) * (1e-13 * 10f64.powi(power));
7366                let p = ip.point + off;
7367                let full = plane_torus_section_point(&torus, n, d, p).unwrap();
7368                let short = plane_torus_newton(&torus, n, d, p, 0.25 * tol).unwrap();
7369                if (short - p).length() < 0.25 * tol {
7370                    assert!((full - p).length() <= tol, "{:.2e}", (full - p).length());
7371                    assert!((full - short).length() < 1e-15);
7372                } else {
7373                    assert_eq!(full, short);
7374                }
7375            }
7376        }
7377    }
7378
7379    /// Points near a plane's section of a torus move onto it, on the plane
7380    /// and the tube to rounding.
7381    #[test]
7382    fn plane_torus_section_points_lie_on_both_surfaces() {
7383        let torus = ToroidalSurface::new(Point3::new(1.0, -2.0, 0.5), 4.0, 1.5).unwrap();
7384        let (n, d) = (Vec3::new(0.0, 2.0, 0.0), 2.0 * (2.1 - 2.0));
7385        for ipts in plane_torus_loops(&torus, n, d, 128) {
7386            for ip in ipts.iter().step_by(5) {
7387                let near = ip.point + Vec3::new(1e-4, -2e-4, 3e-4);
7388                let on = plane_torus_section_point(&torus, n, d, near).unwrap();
7389                let w = on - torus.center();
7390                let off = ((w.x().hypot(w.y()) - 4.0).hypot(w.z()) - 1.5).abs();
7391                assert!(off <= 1e-14, "{off} off the torus");
7392                assert!(
7393                    (on.y() - 0.1).abs() <= 1e-14,
7394                    "{} off the plane",
7395                    on.y() - 0.1
7396                );
7397                assert!((on - near).length() < 1e-3);
7398            }
7399        }
7400    }
7401
7402    /// A plane tangent to the inner equator (x = major - minor = 7) cuts a
7403    /// figure-eight that crosses itself on that equator. It comes out as its
7404    /// two lobes, each a loop that starts and ends on the node, one either
7405    /// side of the plane y = 0, never as one loop sealed across the node.
7406    #[test]
7407    fn plane_torus_inner_tangent_figure_eight_is_two_loops_through_its_node() {
7408        let (major, minor) = (10.0, 3.0);
7409        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7410        let curves =
7411            intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
7412        assert_eq!(curves.len(), 2, "one loop per lobe");
7413        let node = Point3::new(major - minor, 0.0, 0.0);
7414        let mut sides = Vec::new();
7415        for c in &curves {
7416            let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7417            assert!((first - node).length() < 1e-6, "starts at {first:?}");
7418            assert_eq!(first, last, "closes on the node");
7419            for p in c.points.iter().map(|p| p.point) {
7420                assert!((p.x() - node.x()).abs() < 1e-9, "off the plane at {p:?}");
7421                assert!(
7422                    torus_implicit(p, major, minor).abs() < 1e-6,
7423                    "off the torus at {p:?}"
7424                );
7425            }
7426            let y: f64 = c.points.iter().map(|p| p.point.y()).sum();
7427            sides.push(y > 0.0);
7428            assert!(
7429                c.points.iter().all(|p| p.point.y() * y >= -1e-9),
7430                "a lobe crosses y = 0"
7431            );
7432        }
7433        assert_ne!(sides[0], sides[1], "the lobes lie either side of y = 0");
7434    }
7435
7436    /// A wall just off the inner tangent has no node. Just past it the
7437    /// section has a gap 0.028 wide in tube angle about the inner equator,
7438    /// between two samples inside it, and is one loop turning either side of
7439    /// the gap; just short of it the section winds the tube twice. Every
7440    /// point lies on the wall.
7441    #[test]
7442    fn a_wall_just_off_the_inner_tangent_cuts_no_node() {
7443        let (major, minor) = (3.0, 1.0);
7444        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7445        for (x, loops) in [(2.0001, 1), (1.9999, 2)] {
7446            let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), x).unwrap();
7447            assert_eq!(curves.len(), loops, "x = {x}");
7448            for c in &curves {
7449                let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7450                assert_eq!(first, last, "x = {x}: the loop closes");
7451                for p in c.points.iter().map(|p| p.point) {
7452                    assert!((p.x() - x).abs() < 1e-9, "x = {x}: off the wall at {p:?}");
7453                    assert!(
7454                        torus_implicit(p, major, minor).abs() < 1e-6,
7455                        "x = {x}: off the torus at {p:?}"
7456                    );
7457                }
7458            }
7459        }
7460        // The loop past the tangent turns either side of the gap, 0.028 apart.
7461        let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), 2.0001).unwrap();
7462        let low = curves[0]
7463            .points
7464            .iter()
7465            .map(|p| p.point)
7466            .filter(|p| p.y().abs() < 1e-6)
7467            .map(Point3::z)
7468            .collect::<Vec<_>>();
7469        let gap = (2.0001_f64 - 2.0)
7470            .madd(2.0, -(2.0001_f64 - 2.0).powi(2))
7471            .sqrt();
7472        assert!(
7473            low.iter().any(|z| (z - gap).abs() < 1e-6)
7474                && low.iter().any(|z| (z + gap).abs() < 1e-6),
7475            "turns at {low:?}, not at z = ±{gap}"
7476        );
7477    }
7478
7479    /// A plane tangent to the tube's inner side off its equator, at a saddle,
7480    /// cuts a figure-eight that crosses itself where it touches. Its lobes
7481    /// come out as two loops, each starting and ending on that node.
7482    #[test]
7483    fn a_tilted_plane_tangent_inside_the_tube_cuts_two_loops_through_its_node() {
7484        let (major, minor) = (3.0, 1.0);
7485        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7486        for v0 in [1.7_f64, 2.0, 2.5, 4.0] {
7487            let normal = Vec3::new(v0.cos(), 0.0, v0.sin());
7488            let node = torus.evaluate(0.0, v0);
7489            let d = normal.dot(Vec3::new(node.x(), node.y(), node.z()));
7490            let curves = intersect_plane_torus(&torus, normal, d).unwrap();
7491            assert_eq!(curves.len(), 2, "v0 {v0}: one loop per lobe");
7492            for c in &curves {
7493                let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7494                assert!(
7495                    (first - node).length() < 1e-6,
7496                    "v0 {v0}: starts at {first:?}, not {node:?}"
7497                );
7498                assert_eq!(first, last, "v0 {v0}: closes on the node");
7499                for p in c.points.iter().map(|p| p.point) {
7500                    let off = normal.dot(Vec3::new(p.x(), p.y(), p.z())) - d;
7501                    assert!(off.abs() < 1e-9, "v0 {v0}: off the plane at {p:?}");
7502                    assert!(
7503                        torus_implicit(p, major, minor).abs() < 1e-6,
7504                        "v0 {v0}: off the torus at {p:?}"
7505                    );
7506                }
7507            }
7508        }
7509    }
7510
7511    /// A wall parallel to the axis cuts one loop from the ring past the
7512    /// inner equator (its two turns where the branches meet), and two loops
7513    /// winding the tube inside it; each closes, at any scale, however near
7514    /// the wall runs to an equator.
7515    #[test]
7516    fn plane_torus_wall_sections_close_into_their_loops() {
7517        for (major, minor) in [(4.0, 1.5), (100.0, 30.0), (0.05, 0.01)] {
7518            let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7519            for k in 1..200 {
7520                let (d, want) = match k.cmp(&100) {
7521                    // Within the inner equator: two loops winding the tube.
7522                    std::cmp::Ordering::Less => ((major - minor) * f64::from(k) / 100.0, 2),
7523                    // Past it, short of the outer equator: one loop.
7524                    std::cmp::Ordering::Greater => (
7525                        2.0f64.madd(minor * f64::from(k - 100) / 100.0, major - minor),
7526                        1,
7527                    ),
7528                    std::cmp::Ordering::Equal => continue,
7529                };
7530                let loops = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), d, 128);
7531                let closed = loops
7532                    .iter()
7533                    .filter(|l| (l[0].point - l[l.len() - 1].point).length() < 1e-12)
7534                    .count();
7535                assert_eq!(
7536                    (loops.len(), closed),
7537                    (want, want),
7538                    "R {major} r {minor}, wall at {d}"
7539                );
7540            }
7541        }
7542    }
7543
7544    /// A plane through the centre tilted a little from the equator cuts two
7545    /// loops that each run all the way round the axis on a short run of `v`;
7546    /// their fitted curves stay on the torus.
7547    #[test]
7548    fn plane_torus_sections_round_the_axis_stay_on_the_torus() {
7549        let (major, minor) = (4.0, 1.5);
7550        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7551        for tilt in [0.03_f64, 0.08, 0.2] {
7552            let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
7553            let curves = intersect_plane_torus(&torus, normal, 0.0).unwrap();
7554            assert_eq!(curves.len(), 2, "tilt {tilt}");
7555            for c in &curves {
7556                let (t0, t1) = c.curve.domain();
7557                let off = (0..=400)
7558                    .map(|k| {
7559                        let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 400.0, t0));
7560                        (p.x().hypot(p.y()) - major).hypot(p.z()) - minor
7561                    })
7562                    .fold(0.0_f64, |m, e| m.max(e.abs()));
7563                assert!(
7564                    off < 1e-6,
7565                    "tilt {tilt}: fitted section {off} off the torus"
7566                );
7567            }
7568        }
7569    }
7570
7571    #[test]
7572    fn line_torus_box_edge_crossing_is_exact() {
7573        // The census box edge x=6, y=-4 (z varying) crosses the torus (R=10,r=3)
7574        // at z = ±sqrt(r² − (rho−R)²), rho = hypot(6,4) ≈ 7.2111 → z ≈ ±1.1055.
7575        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
7576        let ts = intersect_line_torus(
7577            &torus,
7578            Point3::new(6.0, -4.0, -5.0),
7579            Vec3::new(0.0, 0.0, 1.0),
7580        );
7581        // Vertical line through (6,-4) meets the tube twice.
7582        assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
7583        let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
7584        let rho = 6.0_f64.hypot(4.0);
7585        let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
7586        assert!(
7587            (zs[0] - (-z_exp)).abs() < 1e-9,
7588            "z0={} exp={}",
7589            zs[0],
7590            -z_exp
7591        );
7592        assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
7593        // Each crossing lies on the torus.
7594        for &t in &ts {
7595            let p = Point3::new(6.0, -4.0, -5.0 + t);
7596            let rho = p.x().hypot(p.y());
7597            let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
7598            assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
7599        }
7600    }
7601
7602    /// A ray out of a pocket corner's spindle torus (major 0.1, minor 2.45)
7603    /// meets the tube swung across the axis at t 0.124 and its own tube at
7604    /// 0.398: each root lies on one of the two tubes, not polished off the
7605    /// first onto a point beside the second.
7606    #[test]
7607    fn line_spindle_torus_roots_lie_on_their_tubes() {
7608        let torus = ToroidalSurface::new(Point3::new(41.0, 17.0, 4.7), 0.1, 2.45).unwrap();
7609        let origin = Point3::new(42.36, 18.31, 3.4);
7610        let dir = Vec3::new(
7611            0.573_576_436_351_046,
7612            0.740_535_693_464_567_5,
7613            0.350_889_803_483_932_2,
7614        );
7615        let ts = intersect_line_torus(&torus, origin, dir);
7616        let tube = |t: f64, across: f64| {
7617            let q = origin + dir * t;
7618            ((q.x() - 41.0).hypot(q.y() - 17.0) - across * 0.1).hypot(q.z() - 4.7) - 2.45
7619        };
7620        for &t in &ts {
7621            assert!(
7622                tube(t, 1.0).abs().min(tube(t, -1.0).abs()) < 1e-9,
7623                "root {t} off both tubes in {ts:?}"
7624            );
7625        }
7626        for want in [0.124, 0.398] {
7627            assert!(
7628                ts.iter().any(|&t| (t - want).abs() < 1e-3),
7629                "no root near {want} in {ts:?}"
7630            );
7631        }
7632    }
7633
7634    #[test]
7635    fn line_torus_miss_and_tangent() {
7636        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
7637        // A vertical line at rho beyond the outer rim (x=20) misses entirely.
7638        let miss = intersect_line_torus(
7639            &torus,
7640            Point3::new(20.0, 0.0, 0.0),
7641            Vec3::new(0.0, 0.0, 1.0),
7642        );
7643        assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
7644        // The z-axis (rho=0) passes through the hole — no intersection.
7645        let axis =
7646            intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
7647        assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
7648    }
7649
7650    #[test]
7651    fn dispatch_via_analytic_surface() {
7652        let cyl =
7653            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7654                .unwrap();
7655        let curves = intersect_plane_analytic(
7656            AnalyticSurface::Cylinder(&cyl),
7657            Vec3::new(0.0, 0.0, 1.0),
7658            0.0,
7659        )
7660        .unwrap();
7661        assert!(!curves.is_empty());
7662    }
7663
7664    #[test]
7665    fn perpendicular_cylinders_intersect() {
7666        let cyl_z =
7667            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7668                .unwrap();
7669        let cyl_x =
7670            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7671                .unwrap();
7672
7673        let curves = intersect_analytic_analytic(
7674            AnalyticSurface::Cylinder(&cyl_z),
7675            AnalyticSurface::Cylinder(&cyl_x),
7676            16,
7677        )
7678        .unwrap();
7679
7680        assert!(
7681            !curves.is_empty(),
7682            "perpendicular cylinders should intersect"
7683        );
7684
7685        for c in &curves {
7686            assert!(
7687                c.points.len() >= 2,
7688                "intersection curve should have >= 2 points, got {}",
7689                c.points.len()
7690            );
7691        }
7692    }
7693
7694    /// Neither cylinder's rulings all meet the other: the curve is one loop
7695    /// joined at its two branch points.
7696    #[test]
7697    fn partially_overlapping_cylinders_meet_in_one_closed_loop() {
7698        let cyl_z =
7699            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7700                .unwrap();
7701        let cyl_x =
7702            CylindricalSurface::new(Point3::new(0.0, 1.2, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7703                .unwrap();
7704        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
7705            .unwrap()
7706            .unwrap();
7707        assert_eq!(curves.len(), 1);
7708        let curve = &curves[0].curve;
7709        let (t0, t1) = curve.domain();
7710        assert!((curve.evaluate(t0) - curve.evaluate(t1)).length() < 1e-9);
7711        let off = |p: Point3| {
7712            let on_z = (p.x().hypot(p.y()) - 1.0).abs();
7713            let on_x = ((p.y() - 1.2).hypot(p.z()) - 1.0).abs();
7714            on_z.max(on_x)
7715        };
7716        let worst = (0..=400)
7717            .map(|k| off(curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0)))
7718            .fold(0.0, f64::max);
7719        assert!(worst < 2e-4, "curve leaves the cylinders by {worst}");
7720    }
7721
7722    /// Near tangency the thick cylinder's window of rulings (0.02 either side
7723    /// of a quarter turn) falls between its samples; the thin one's sweep
7724    /// finds the loop.
7725    #[test]
7726    fn near_tangent_cylinders_find_their_loop_on_the_thinner_sweep() {
7727        let cyl_z =
7728            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7729                .unwrap();
7730        let cyl_x =
7731            CylindricalSurface::new(Point3::new(0.0, 1.1998, 0.0), Vec3::new(1.0, 0.0, 0.0), 0.2)
7732                .unwrap();
7733        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
7734            .unwrap()
7735            .expect("the thin cylinder's sweep finds the loop");
7736        assert_eq!(curves.len(), 1);
7737    }
7738
7739    /// Cylinders of radius 1.5 whose axes cross at 60° meet in two ellipses
7740    /// crossing at the ends of the axes' common normal: two exact loops,
7741    /// one from each end, each the halves of both ellipses on one side of
7742    /// the crossing along the first axis, on both cylinders to rounding.
7743    #[test]
7744    fn equal_cylinders_with_crossing_axes_meet_in_two_cornered_loops() {
7745        let crossing = Point3::new(1.0, 2.0, 3.0);
7746        let (s, c) = 60.0_f64.to_radians().sin_cos();
7747        let (d1, d2) = (Vec3::new(0.0, 0.0, 1.0), Vec3::new(s, 0.0, c));
7748        let c1 = CylindricalSurface::new(crossing - d1 * 2.0, d1, 1.5).unwrap();
7749        let c2 = CylindricalSurface::new(crossing + d2 * 0.7, d2, 1.5).unwrap();
7750        let curves = algebraic_cylinder_cylinder(&c1, &c2).unwrap().unwrap();
7751        assert_eq!(curves.len(), 2);
7752        let off = |p: Point3, cyl: &CylindricalSurface| {
7753            let q = p - cyl.origin();
7754            ((q - cyl.axis() * q.dot(cyl.axis())).length() - 1.5).abs()
7755        };
7756        let ends = [
7757            crossing + Vec3::new(0.0, 1.5, 0.0),
7758            crossing - Vec3::new(0.0, 1.5, 0.0),
7759        ];
7760        let mut vertices: Vec<Point3> = Vec::new();
7761        for (ic, (end, side)) in curves.iter().zip([(ends[0], 1.0), (ends[1], -1.0)]) {
7762            let (t0, t1) = ic.curve.domain();
7763            for k in 0..=400 {
7764                let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
7765                assert!(off(p, &c1).max(off(p, &c2)) < 1e-13);
7766                assert!(side * (p - crossing).dot(d1) > -1e-13);
7767            }
7768            assert!((ic.curve.evaluate(t0) - end).length() < 1e-14);
7769            assert!((ic.curve.evaluate(t1) - end).length() < 1e-14);
7770            let other = ends[usize::from(side > 0.0)];
7771            assert!((ic.curve.evaluate(0.5) - other).length() < 1e-14);
7772            for t in [0.25, 0.75] {
7773                let vertex = ic.curve.evaluate(t);
7774                assert!(vertices.iter().all(|&v| (v - vertex).length() > 1.0));
7775                vertices.push(vertex);
7776            }
7777        }
7778    }
7779
7780    /// Axes that miss each other by 1e-9, or radii that differ by as much,
7781    /// part the curves where the ellipses would cross; neither is taken for
7782    /// a pair of ellipses, nor a miss of 1e-6 read between origins 1e8
7783    /// apart along an axis.
7784    #[test]
7785    fn nearly_crossing_equal_cylinders_are_not_ellipses() {
7786        let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7787            .unwrap();
7788        let x = |(x0, y): (f64, f64), r: f64| {
7789            CylindricalSurface::new(Point3::new(x0, y, 0.0), Vec3::new(1.0, 0.0, 0.0), r).unwrap()
7790        };
7791        let taken = |c: &CylindricalSurface| crossing_equal_cylinders(&z, c).unwrap().is_some();
7792        assert!(taken(&x((-2.0, 0.0), 1.0)));
7793        assert!(!taken(&x((-2.0, 1e-9), 1.0)));
7794        assert!(!taken(&x((-2.0, 0.0), 1.0 + 1e-9)));
7795        assert!(!taken(&x((-1e8, 1e-6), 1.0)));
7796    }
7797
7798    /// Axes 1e-8 and 1.5e-5 apart in angle cross in ellipses whose far
7799    /// vertices rounding alone would move past the tolerance; they are
7800    /// left to the rulings.
7801    #[test]
7802    fn nearly_parallel_equal_cylinders_are_not_ellipses() {
7803        let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 10.0)
7804            .unwrap();
7805        for slope in [1e-8, 1.5e-5] {
7806            let tilted = CylindricalSurface::new(
7807                Point3::new(0.0, 0.0, 0.0),
7808                Vec3::new(slope, 0.0, 1.0),
7809                10.0,
7810            )
7811            .unwrap();
7812            assert!(crossing_equal_cylinders(&z, &tilted).unwrap().is_none());
7813        }
7814    }
7815
7816    #[test]
7817    fn sphere_cylinder_intersect() {
7818        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
7819        let cyl =
7820            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7821                .unwrap();
7822
7823        let curves = intersect_analytic_analytic(
7824            AnalyticSurface::Sphere(&sphere),
7825            AnalyticSurface::Cylinder(&cyl),
7826            16,
7827        )
7828        .unwrap();
7829
7830        // A sphere of radius 2 and a cylinder of radius 1, both centered
7831        // at the origin, should intersect (the cylinder passes through
7832        // the sphere).
7833        assert!(!curves.is_empty(), "sphere and cylinder should intersect");
7834    }
7835
7836    #[test]
7837    fn exact_sphere_cylinder_coaxial_two_circles() {
7838        // Sphere r=6 at origin, coaxial cylinder r=3 along z: two latitude
7839        // circles at z = ±sqrt(36-9) = ±sqrt(27), each of radius 3.
7840        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
7841        let cyl =
7842            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
7843                .unwrap();
7844        let circles = exact_sphere_cylinder(&sphere, &cyl)
7845            .unwrap()
7846            .expect("coaxial case returns Some");
7847        assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
7848        let mut zs: Vec<f64> = circles
7849            .iter()
7850            .filter_map(|c| match c {
7851                ExactIntersectionCurve::Circle(circle) => {
7852                    assert!(
7853                        (circle.radius() - 3.0).abs() < 1e-9,
7854                        "rim radius == cyl radius"
7855                    );
7856                    Some(circle.center().z())
7857                }
7858                _ => None,
7859            })
7860            .collect();
7861        assert_eq!(zs.len(), 2, "both sections must be exact circles");
7862        zs.sort_by(f64::total_cmp);
7863        let z = 27.0_f64.sqrt();
7864        assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
7865    }
7866
7867    #[test]
7868    fn exact_sphere_cylinder_non_coaxial_defers() {
7869        // Cylinder axis offset from the sphere center → quartic curve, deferred.
7870        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
7871        let cyl =
7872            CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
7873                .unwrap();
7874        assert!(
7875            exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
7876            "non-coaxial sphere/cylinder defers to the marcher"
7877        );
7878    }
7879
7880    #[test]
7881    fn a_ball_on_a_cones_axis_meets_it_in_circles() {
7882        // Apex 3 up, opening downward, the radius half the depth below it.
7883        let cone = ConicalSurface::new(
7884            Point3::new(0.0, 0.0, 3.0),
7885            Vec3::new(0.0, 0.0, -1.0),
7886            2.0_f64.atan(),
7887        )
7888        .unwrap();
7889        for (height, radius, count) in [
7890            (0.0, 2.0, 2), // through the cone's middle
7891            (2.5, 1.3, 1), // swallowing the apex
7892            (2.5, 0.5, 1), // through the apex: the apex root is no circle
7893            (0.0, 1.0, 0), // inside, clear of the wall
7894            (5.0, 1.0, 0), // on the other nappe's side
7895        ] {
7896            let centre = Point3::new(0.0, 0.0, height);
7897            let ball = SphericalSurface::new(centre, radius).unwrap();
7898            let curves = exact_cone_sphere(&cone, &ball).unwrap().unwrap();
7899            let circles = circles_of(&curves);
7900            assert_eq!(circles.len(), count, "ball at {height}, radius {radius}");
7901            for circle in circles {
7902                for k in 0..16 {
7903                    let p = circle.evaluate(TAU * f64::from(k) / 16.0);
7904                    let on_ball = (p - centre).length() - radius;
7905                    let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
7906                    assert!(
7907                        on_ball.abs() < 1e-9 && on_cone.abs() < 1e-9,
7908                        "ball at {height}: off by {on_ball}, {on_cone}"
7909                    );
7910                }
7911            }
7912        }
7913        let aside = SphericalSurface::new(Point3::new(0.5, 0.0, 0.0), 2.0).unwrap();
7914        assert!(exact_cone_sphere(&cone, &aside).unwrap().is_none());
7915        // A ball touching a wide cone a million units out, where the
7916        // discriminant cancels to a few ulps below zero.
7917        let wide =
7918            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.3).unwrap();
7919        let far = SphericalSurface::new(Point3::new(0.0, 0.0, 1e6), 1e6 * 0.3_f64.cos()).unwrap();
7920        let curves = exact_cone_sphere(&wide, &far).unwrap().unwrap();
7921        let circles = circles_of(&curves);
7922        assert_eq!(circles.len(), 1, "the touch");
7923        let touch = 1e6 * 0.3_f64.sin() * 0.3_f64.cos();
7924        assert!(
7925            (circles[0].radius() - touch).abs() < 1e-3,
7926            "{}",
7927            circles[0].radius()
7928        );
7929    }
7930
7931    /// The circles among exact section curves.
7932    fn circles_of(curves: &[ExactIntersectionCurve]) -> Vec<&Circle3D> {
7933        curves
7934            .iter()
7935            .filter_map(|c| match c {
7936                ExactIntersectionCurve::Circle(circle) => Some(circle),
7937                _ => None,
7938            })
7939            .collect()
7940    }
7941
7942    /// Worst distance of a circle's points from a torus and from a second
7943    /// surface given by its own distance function.
7944    fn worst_off(
7945        circles: &[&Circle3D],
7946        torus: &ToroidalSurface,
7947        other: impl Fn(Point3) -> f64,
7948    ) -> f64 {
7949        let mut worst = 0.0_f64;
7950        for circle in circles {
7951            for k in 0..16 {
7952                let p = circle.evaluate(TAU * f64::from(k) / 16.0);
7953                let q = p - torus.center();
7954                let along = q.dot(torus.z_axis());
7955                let rho = (q - torus.z_axis() * along).length();
7956                let off = ((rho - torus.major_radius()).hypot(along) - torus.minor_radius()).abs();
7957                worst = worst.max(off).max(other(p).abs());
7958            }
7959        }
7960        worst
7961    }
7962
7963    #[test]
7964    fn exact_sphere_torus_meets_a_ball_on_the_axis_in_circles() {
7965        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7966        for height in [0.0, 1.0] {
7967            let centre = Point3::new(0.0, 0.0, height);
7968            let sphere = SphericalSurface::new(centre, 3.0).unwrap();
7969            let curves = exact_sphere_torus(&sphere, &torus).unwrap().unwrap();
7970            let circles = circles_of(&curves);
7971            assert_eq!((curves.len(), circles.len()), (2, 2), "height {height}");
7972            let worst = worst_off(&circles, &torus, |p| (p - centre).length() - 3.0);
7973            assert!(worst < 1e-9, "height {height}: {worst}");
7974        }
7975    }
7976
7977    /// Balls off a ring torus's axis, one poking out of the tube's top, one
7978    /// wider than the tube on its core circle, one anywhere, and one just past
7979    /// the tube's outside, in a loop narrower than the scan's step, meet the
7980    /// torus in curves whose points lie on both surfaces, given either way
7981    /// round, where the marcher found nothing with the torus first.
7982    #[test]
7983    fn a_ball_off_a_torus_axis_meets_it_in_its_closed_form_loops() {
7984        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7985        let on_torus = |p: Point3| (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
7986        for (centre, radius, loops) in [
7987            (Point3::new(4.0, 0.0, 1.0), 1.0, 1),
7988            (Point3::new(4.0, 0.0, 0.0), 2.0, 2),
7989            (Point3::new(2.0, 1.0, 0.5), 1.2, 1),
7990            (Point3::new(6.4999, 0.0, 0.0), 1.0, 1),
7991        ] {
7992            let ball = SphericalSurface::new(centre, radius).unwrap();
7993            let on_ball = |p: Point3| (p - centre).length() - radius;
7994            for ball_first in [true, false] {
7995                let (a, b) = if ball_first {
7996                    (
7997                        AnalyticSurface::Sphere(&ball),
7998                        AnalyticSurface::Torus(&torus),
7999                    )
8000                } else {
8001                    (
8002                        AnalyticSurface::Torus(&torus),
8003                        AnalyticSurface::Sphere(&ball),
8004                    )
8005                };
8006                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8007                let case = format!("ball {radius} at {centre:?}, ball first {ball_first}");
8008                assert_eq!(curves.len(), loops, "{case}");
8009                for ic in &curves {
8010                    for q in &ic.points {
8011                        let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
8012                        assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
8013                        let (on_ball_at, on_torus_at) = if ball_first {
8014                            (q.param1, q.param2)
8015                        } else {
8016                            (q.param2, q.param1)
8017                        };
8018                        let (pb, pt) = (
8019                            ball.evaluate(on_ball_at.0, on_ball_at.1),
8020                            torus.evaluate(on_torus_at.0, on_torus_at.1),
8021                        );
8022                        assert!(
8023                            (pb - q.point).length() < 1e-9 && (pt - q.point).length() < 1e-9,
8024                            "{case}: a point's parameters miss it"
8025                        );
8026                    }
8027                    let (t0, t1) = ic.curve.domain();
8028                    for k in 0..=400 {
8029                        let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
8030                        let off = on_ball(p).abs().max(on_torus(p).abs());
8031                        assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
8032                    }
8033                }
8034            }
8035        }
8036    }
8037
8038    /// Balls whose loops a fixed scan of the tube misses or blurs: one far
8039    /// smaller than its torus, one near the axis whose two loops share a
8040    /// scan step, one a hair larger than the tube it sits in, whose two
8041    /// loops lie close together all the way round, and one whose winding
8042    /// loops swing round the axis within a few scan steps. Each loop is met
8043    /// either way round, and its curve holds to both surfaces.
8044    #[test]
8045    fn balls_meet_tori_in_loops_a_scan_would_miss() {
8046        for (big, small, centre, radius, loops) in [
8047            (4000.0, 1500.0, Point3::new(5500.0, 0.0, 0.0), 0.001, 1),
8048            (4.0, 1.5, Point3::new(1e-6, 0.0, 0.0), 2.500_002, 2),
8049            (1000.0, 1.0, Point3::new(1000.0, 0.0, 0.0), 1.000_000_5, 2),
8050            (4.0, 1.5, Point3::new(1.500_001, 0.0, 0.0), 4.0, 2),
8051        ] {
8052            let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), big, small).unwrap();
8053            let ball = SphericalSurface::new(centre, radius).unwrap();
8054            let on_torus = |p: Point3| (p.x().hypot(p.y()) - big).hypot(p.z()) - small;
8055            let on_ball = |p: Point3| (p - centre).length() - radius;
8056            for ball_first in [true, false] {
8057                let (a, b) = if ball_first {
8058                    (
8059                        AnalyticSurface::Sphere(&ball),
8060                        AnalyticSurface::Torus(&torus),
8061                    )
8062                } else {
8063                    (
8064                        AnalyticSurface::Torus(&torus),
8065                        AnalyticSurface::Sphere(&ball),
8066                    )
8067                };
8068                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8069                let case = format!("ball {radius} at {centre:?} on torus ({big}, {small})");
8070                assert_eq!(curves.len(), loops, "{case}");
8071                for ic in &curves {
8072                    for q in &ic.points {
8073                        let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
8074                        assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
8075                    }
8076                    let (t0, t1) = ic.curve.domain();
8077                    for k in 0..=2000 {
8078                        let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
8079                        let off = on_ball(p).abs().max(on_torus(p).abs());
8080                        assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
8081                    }
8082                }
8083            }
8084        }
8085    }
8086
8087    /// Sections a closed form can lose to scale or rounding: a plane whose
8088    /// equation is scaled by 1e14 keeps the loop of the plane it describes; a
8089    /// ball 1e-5 across poking out of a large torus, and a ball a micron wider
8090    /// than the tube of a ring 1e8 across, defer to the marcher instead of
8091    /// reading as apart, and the last is not taken for the meridian circle.
8092    #[test]
8093    fn scaled_and_ill_conditioned_sections_are_kept_or_deferred() {
8094        let origin = Point3::new(0.0, 0.0, 0.0);
8095        let torus = ToroidalSurface::new(origin, 4.0, 1.5).unwrap();
8096        let unit = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), 4.0, 128).len();
8097        let scaled = plane_torus_loops(&torus, Vec3::new(1e14, 0.0, 0.0), 4e14, 128).len();
8098        assert_eq!((unit, scaled), (1, 1));
8099
8100        let large = ToroidalSurface::new(origin, 4000.0, 1500.0).unwrap();
8101        let speck = SphericalSurface::new(Point3::new(5_500.000_001, 0.0, 0.0), 1e-5).unwrap();
8102        assert!(sphere_torus_curves(&speck, &large, true).is_none());
8103
8104        let ring = ToroidalSurface::new(origin, 1e8, 1.0).unwrap();
8105        let ball = SphericalSurface::new(Point3::new(1e8, 0.0, 0.0), 1.000_001).unwrap();
8106        assert!(exact_sphere_torus(&ball, &ring).unwrap().is_none());
8107        assert!(sphere_torus_curves(&ball, &ring, true).is_none());
8108    }
8109
8110    /// A ball centred on a ring torus's core circle with the tube's own
8111    /// radius meets it along the meridian circle through its centre: one
8112    /// circle, given either way round.
8113    #[test]
8114    fn a_ball_filling_a_torus_tube_meets_it_in_one_meridian_circle() {
8115        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8116        let centre = Point3::new(4.0, 0.0, 0.0);
8117        let ball = SphericalSurface::new(centre, 1.5).unwrap();
8118        for (a, b) in [
8119            (
8120                AnalyticSurface::Sphere(&ball),
8121                AnalyticSurface::Torus(&torus),
8122            ),
8123            (
8124                AnalyticSurface::Torus(&torus),
8125                AnalyticSurface::Sphere(&ball),
8126            ),
8127        ] {
8128            let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8129            assert_eq!(curves.len(), 1);
8130            let (t0, t1) = curves[0].curve.domain();
8131            for k in 0..=100 {
8132                let p = curves[0]
8133                    .curve
8134                    .evaluate(t0 + (t1 - t0) * f64::from(k) / 100.0);
8135                let off = ((p - centre).length() - 1.5).abs().max(p.y().abs());
8136                assert!(off < 1e-9, "the circle strays {off:.2e}");
8137            }
8138        }
8139    }
8140
8141    #[test]
8142    fn exact_sphere_torus_misses_touches_and_defers() {
8143        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8144        let ball = |x: f64, r: f64| SphericalSurface::new(Point3::new(x, 0.0, 0.0), r).unwrap();
8145        assert!(
8146            exact_sphere_torus(&ball(0.0, 1.0), &torus)
8147                .unwrap()
8148                .unwrap()
8149                .is_empty(),
8150            "a small ball in the hole misses"
8151        );
8152        let touching = exact_sphere_torus(&ball(0.0, 2.5), &torus)
8153            .unwrap()
8154            .unwrap();
8155        let circles = circles_of(&touching);
8156        assert_eq!(
8157            circles.len(),
8158            1,
8159            "a ball in the hole touches the inner equator"
8160        );
8161        assert!((circles[0].radius() - 2.5).abs() < 1e-12);
8162        assert!(circles[0].center().z().abs() < 1e-12);
8163        assert!(
8164            exact_sphere_torus(&ball(1.0, 3.0), &torus)
8165                .unwrap()
8166                .is_none(),
8167            "a ball off the axis defers"
8168        );
8169        let spindle = ToroidalSurface::with_axis_and_ref_dir(
8170            Point3::new(0.0, 0.0, 0.0),
8171            1.0,
8172            2.0,
8173            Vec3::new(0.0, 0.0, 1.0),
8174            Vec3::new(1.0, 0.0, 0.0),
8175        )
8176        .unwrap();
8177        assert!(
8178            exact_sphere_torus(&ball(0.0, 2.5), &spindle)
8179                .unwrap()
8180                .is_none()
8181        );
8182    }
8183
8184    /// A rod of radius 0.6 along `y` through the ring (4, 1.5) at `x = 0.5`,
8185    /// `z = 1` leaves the tube through its top, and meets it in one loop on
8186    /// each side of the ring. The march back to a loop's seed can be several
8187    /// steps long; each loop's curve lies on both surfaces all along it.
8188    #[test]
8189    fn a_marched_loop_closes_on_both_surfaces() {
8190        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8191        let rod =
8192            CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
8193                .unwrap();
8194        let region = Aabb3 {
8195            min: Point3::new(-0.1, -5.5, 0.4),
8196            max: Point3::new(1.1, 5.5, 1.5),
8197        };
8198        let curves = intersect_analytic_analytic_in_region(
8199            AnalyticSurface::Cylinder(&rod),
8200            AnalyticSurface::Torus(&torus),
8201            32,
8202            Some((-10.0, 10.0)),
8203            None,
8204            region,
8205        )
8206        .unwrap();
8207        assert_eq!(curves.len(), 2);
8208        for c in &curves {
8209            let (t0, t1) = c.curve.domain();
8210            let worst = (0..=4000)
8211                .map(|k| {
8212                    let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 4000.0, t0));
8213                    let on_torus = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
8214                    let on_rod = ((p.x() - 0.5).hypot(p.z() - 1.0) - 0.6).abs();
8215                    on_torus.max(on_rod)
8216                })
8217                .fold(0.0, f64::max);
8218            assert!(worst <= 1e-7, "off the surfaces by {worst}");
8219        }
8220    }
8221
8222    /// A funnel's outer wall, a 45 degree cone, crosses the tube of a lip
8223    /// that leans a thousandth of a radian off the cone's axis in one loop
8224    /// round the axis. The marcher closes the loop on its seed, and the loop
8225    /// runs round the axis once.
8226    #[test]
8227    fn a_marched_loop_round_an_axis_runs_round_it_once() {
8228        let skin = 1.6 * std::f64::consts::SQRT_2;
8229        let tilt = 0.001_f64;
8230        let torus = ToroidalSurface::with_axis(
8231            Point3::new(0.0, 0.0, 70.5),
8232            80.8 + skin / 2.0,
8233            2.0,
8234            Vec3::new(0.0, -tilt.sin(), tilt.cos()),
8235        )
8236        .unwrap();
8237        let cone = ConicalSurface::new(
8238            Point3::new(0.0, 0.0, -9.5 - skin),
8239            Vec3::new(0.0, 0.0, 1.0),
8240            std::f64::consts::FRAC_PI_4,
8241        )
8242        .unwrap();
8243        let region = Aabb3 {
8244            min: Point3::new(-84.0, -84.0, 68.0),
8245            max: Point3::new(84.0, 84.0, 73.0),
8246        };
8247        let curves = intersect_analytic_analytic_in_region(
8248            AnalyticSurface::Cone(&cone),
8249            AnalyticSurface::Torus(&torus),
8250            32,
8251            Some((16.6, 116.3)),
8252            None,
8253            region,
8254        )
8255        .unwrap();
8256        assert_eq!(curves.len(), 1);
8257        let (t0, t1) = curves[0].curve.domain();
8258        let (start, end) = (curves[0].curve.evaluate(t0), curves[0].curve.evaluate(t1));
8259        assert!((start - end).length() < 1e-9, "{start:?} to {end:?}");
8260        let n = 4000;
8261        let mut turn = 0.0;
8262        let mut last = start.y().atan2(start.x());
8263        for k in 1..=n {
8264            let p = curves[0]
8265                .curve
8266                .evaluate((t1 - t0).madd(f64::from(k) / f64::from(n), t0));
8267            let at = p.y().atan2(p.x());
8268            turn += (at - last + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
8269            last = at;
8270        }
8271        assert!((turn.abs() - TAU).abs() < 1e-6, "turns {}", turn / TAU);
8272    }
8273
8274    /// A 45 degree cone about the axis of the ring (4, 1.5), its apex at
8275    /// `z = apex` below the ring: its generator `ρ = z − apex` stands
8276    /// `|4 + apex| / √2` from the tube's centre in the half-plane.
8277    #[test]
8278    fn exact_cone_torus_meets_a_coaxial_cone_in_circles() {
8279        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8280        let z = Vec3::new(0.0, 0.0, 1.0);
8281        let quarter = std::f64::consts::FRAC_PI_4;
8282        let cone = |apex: f64, axis: Vec3| {
8283            ConicalSurface::new(Point3::new(0.0, 0.0, apex), axis, quarter).unwrap()
8284        };
8285        let on_cone = |apex: f64| move |p: Point3| p.x().hypot(p.y()) - (p.z() - apex);
8286        let curves = exact_cone_torus(&cone(-5.0, z), &torus).unwrap().unwrap();
8287        let circles = circles_of(&curves);
8288        assert_eq!(
8289            (curves.len(), circles.len()),
8290            (2, 2),
8291            "a wall through the tube"
8292        );
8293        let worst = worst_off(&circles, &torus, on_cone(-5.0));
8294        assert!(worst < 1e-12, "{worst}");
8295        assert!(
8296            exact_cone_torus(&cone(-8.0, z), &torus)
8297                .unwrap()
8298                .unwrap()
8299                .is_empty(),
8300            "a wall clear of the tube misses it"
8301        );
8302        let touch = -4.0 - 1.5 * std::f64::consts::SQRT_2;
8303        let curves = exact_cone_torus(&cone(touch, z), &torus).unwrap().unwrap();
8304        let circles = circles_of(&curves);
8305        assert_eq!(circles.len(), 1, "a wall touching the tube");
8306        let worst = worst_off(&circles, &torus, on_cone(touch));
8307        assert!(worst < 1e-12, "{worst}");
8308        assert_eq!(
8309            exact_cone_torus(&cone(touch + 1e-6, z), &torus)
8310                .unwrap()
8311                .unwrap()
8312                .len(),
8313            2,
8314            "a wall into the tube by more than the tolerance crosses it twice"
8315        );
8316        // The cone's axis may run either way along the torus's.
8317        let below = ConicalSurface::new(Point3::new(0.0, 0.0, 5.0), -z, quarter).unwrap();
8318        let curves = exact_cone_torus(&below, &torus).unwrap().unwrap();
8319        let circles = circles_of(&curves);
8320        assert_eq!(circles.len(), 2);
8321        let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - (5.0 - p.z()));
8322        assert!(worst < 1e-12, "{worst}");
8323        let tilted = cone(-5.0, Vec3::new(0.0, 0.1, 1.0));
8324        let offset = ConicalSurface::new(Point3::new(0.5, 0.0, -5.0), z, quarter).unwrap();
8325        assert!(exact_cone_torus(&tilted, &torus).unwrap().is_none());
8326        assert!(exact_cone_torus(&offset, &torus).unwrap().is_none());
8327        // A near cylinder whose apex lies a million below, its axis 0.0005
8328        // beside the torus's: radius 4.75 at the torus, off its axis.
8329        let far = ConicalSurface::new(Point3::new(0.0005, 0.0, -1e6), z, (1e6_f64 / 4.75).atan())
8330            .unwrap();
8331        assert!(
8332            exact_cone_torus(&far, &torus).unwrap().is_none(),
8333            "a cone off the torus's axis by 0.0005 is not coaxial, however far its apex"
8334        );
8335        let spindle = ToroidalSurface::with_axis_and_ref_dir(
8336            Point3::new(0.0, 0.0, 0.0),
8337            1.0,
8338            2.0,
8339            z,
8340            Vec3::new(1.0, 0.0, 0.0),
8341        )
8342        .unwrap();
8343        assert!(
8344            exact_cone_torus(&cone(-5.0, z), &spindle)
8345                .unwrap()
8346                .is_none(),
8347            "a spindle torus's tube reaches the axis"
8348        );
8349    }
8350
8351    #[test]
8352    fn exact_cylinder_torus_meets_a_coaxial_rod_in_circles() {
8353        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8354        let z = Vec3::new(0.0, 0.0, 1.0);
8355        let rod = |r: f64| CylindricalSurface::new(Point3::new(0.0, 0.0, -5.0), z, r).unwrap();
8356        let curves = exact_cylinder_torus(&rod(4.2), &torus).unwrap().unwrap();
8357        let circles = circles_of(&curves);
8358        assert_eq!((curves.len(), circles.len()), (2, 2));
8359        let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - 4.2);
8360        assert!(worst < 1e-9, "{worst}");
8361        assert!(
8362            exact_cylinder_torus(&rod(2.0), &torus)
8363                .unwrap()
8364                .unwrap()
8365                .is_empty(),
8366            "a rod clear in the hole misses"
8367        );
8368        for (wall, label) in [(5.5, "outer"), (2.5, "inner")] {
8369            let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
8370            let circles = circles_of(&curves);
8371            assert_eq!(circles.len(), 1, "a wall touching the {label} equator");
8372            assert!(circles[0].center().z().abs() < 1e-12, "{label}");
8373            let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - wall);
8374            assert!(worst < 1e-9, "{label}: {worst}");
8375        }
8376        assert!(
8377            exact_cylinder_torus(&rod(5.5 + 1e-6), &torus)
8378                .unwrap()
8379                .unwrap()
8380                .is_empty(),
8381            "a wall clear of the tube by more than the tolerance misses it"
8382        );
8383        assert_eq!(
8384            exact_cylinder_torus(&rod(5.5 - 1e-6), &torus)
8385                .unwrap()
8386                .unwrap()
8387                .len(),
8388            2,
8389            "a wall into the tube by more than the tolerance crosses it twice"
8390        );
8391        // Within the linear tolerance of the tube the wall reads as touching
8392        // it: the two crossings lie under 1e-3 apart on a band the wall
8393        // never leaves by more than that tolerance.
8394        for wall in [5.5 - 5e-8, 5.5 + 5e-8] {
8395            let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
8396            assert_eq!(circles_of(&curves).len(), 1, "a wall at {wall}");
8397        }
8398        let tilted =
8399            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 1.0), 4.2)
8400                .unwrap();
8401        let offset = CylindricalSurface::new(Point3::new(0.5, 0.0, 0.0), z, 4.2).unwrap();
8402        assert!(exact_cylinder_torus(&tilted, &torus).unwrap().is_none());
8403        assert!(exact_cylinder_torus(&offset, &torus).unwrap().is_none());
8404        let spindle = ToroidalSurface::with_axis_and_ref_dir(
8405            Point3::new(0.0, 0.0, 0.0),
8406            1.0,
8407            2.0,
8408            z,
8409            Vec3::new(1.0, 0.0, 0.0),
8410        )
8411        .unwrap();
8412        assert!(
8413            exact_cylinder_torus(&rod(0.5), &spindle).unwrap().is_none(),
8414            "a spindle torus's inner lemon also meets the rod"
8415        );
8416        // The rounded air wall of a fillet whose radius nearly fills its
8417        // corner: the spindle's outer equator rests on the wall.
8418        let spindle = ToroidalSurface::with_axis_and_ref_dir(
8419            Point3::new(0.0, 0.0, 4.7),
8420            0.1,
8421            2.45,
8422            z,
8423            Vec3::new(1.0, 0.0, 0.0),
8424        )
8425        .unwrap();
8426        let curves = exact_cylinder_torus(&rod(2.55), &spindle).unwrap().unwrap();
8427        let circles = circles_of(&curves);
8428        assert_eq!(circles.len(), 1);
8429        assert!((circles[0].center().z() - 4.7).abs() < 1e-12);
8430        let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.55);
8431        assert!(worst < 1e-9, "{worst}");
8432        let curves = exact_cylinder_torus(&rod(2.4), &spindle).unwrap().unwrap();
8433        let circles = circles_of(&curves);
8434        assert_eq!(circles.len(), 2, "a wall into the spindle's outer tube");
8435        let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.4);
8436        assert!(worst < 1e-9, "{worst}");
8437    }
8438
8439    /// Loops of an off-axis sphere-cylinder pair: `(count, worst distance
8440    /// from either surface)`.
8441    fn off_axis_loops(cylinder_origin: Point3, cylinder_radius: f64) -> (usize, f64) {
8442        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
8443        let cyl =
8444            CylindricalSurface::new(cylinder_origin, Vec3::new(0.0, 0.0, 1.0), cylinder_radius)
8445                .unwrap();
8446        let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
8447            .unwrap()
8448            .unwrap();
8449        let mut worst: f64 = 0.0;
8450        for c in &curves {
8451            for ip in &c.points {
8452                let on_sphere = sphere.evaluate(ip.param1.0, ip.param1.1);
8453                let on_cylinder = cyl.evaluate(ip.param2.0, ip.param2.1);
8454                worst = worst
8455                    .max((on_sphere - ip.point).length())
8456                    .max((on_cylinder - ip.point).length());
8457            }
8458            let (t0, t1) = c.curve.domain();
8459            assert!((c.curve.evaluate(t0) - c.curve.evaluate(t1)).length() < 1e-9);
8460            for k in 0..=400 {
8461                let p = c.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
8462                let on_sphere = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 2.0).abs();
8463                let on_cylinder = ((p.x() - cylinder_origin.x())
8464                    .hypot(p.y() - cylinder_origin.y())
8465                    - cylinder_radius)
8466                    .abs();
8467                worst = worst.max(on_sphere).max(on_cylinder);
8468            }
8469        }
8470        (curves.len(), worst)
8471    }
8472
8473    /// A drill off the ball's axis passes through it: an entry and an exit
8474    /// loop.
8475    #[test]
8476    fn off_axis_drill_through_a_sphere_meets_it_in_two_loops() {
8477        let (count, worst) = off_axis_loops(Point3::new(0.5, 0.0, 0.0), 0.2);
8478        assert_eq!(count, 2);
8479        assert!(worst < 1e-5, "loops leave the surfaces by {worst}");
8480    }
8481
8482    /// A cylinder over the ball's side: one loop joined at its branch points.
8483    #[test]
8484    fn cylinder_over_a_spheres_side_meets_it_in_one_loop() {
8485        let (count, worst) = off_axis_loops(Point3::new(1.8, 0.0, 0.0), 0.5);
8486        assert_eq!(count, 1);
8487        assert!(worst < 5e-4, "loop leaves the surfaces by {worst}");
8488    }
8489
8490    /// A ball through the wall of a ring far wider than it: the rulings that
8491    /// meet the ball span a twelfth of the turn, and the loop through them
8492    /// stays on both surfaces.
8493    #[test]
8494    fn a_ball_through_a_wide_wall_meets_it_in_one_close_loop() {
8495        let centre = Point3::new(7.35, 0.0, 0.0);
8496        let sphere = SphericalSurface::new(centre, 2.4145).unwrap();
8497        let cyl =
8498            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 9.15)
8499                .unwrap();
8500        let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
8501            .unwrap()
8502            .unwrap();
8503        assert_eq!(curves.len(), 1);
8504        let (t0, t1) = curves[0].curve.domain();
8505        let mut worst: f64 = 0.0;
8506        for k in 0..=2000 {
8507            let p = curves[0]
8508                .curve
8509                .evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
8510            let on_sphere = ((p - centre).length() - 2.4145).abs();
8511            let on_cylinder = (p.x().hypot(p.y()) - 9.15).abs();
8512            worst = worst.max(on_sphere).max(on_cylinder);
8513        }
8514        assert!(worst < 1e-6, "the loop leaves the surfaces by {worst}");
8515    }
8516
8517    /// A whole torus ends where it starts both ways round; its size is read
8518    /// from its first corner to its middle, across the ring.
8519    #[test]
8520    fn a_whole_torus_patch_spans_its_ring() {
8521        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 50.0, 10.0).unwrap();
8522        let size = patch_diagonal(&|u, v| torus.evaluate(u, v), (0.0, TAU), (0.0, TAU));
8523        assert!((size - 100.0).abs() < 1e-9, "size {size}");
8524    }
8525
8526    /// A cone's face, between two of its circles, and a cylinder's face
8527    /// across it: each marched curve ends on the edge of one face's band,
8528    /// where the other faces' sections meet it, not a march step short.
8529    #[test]
8530    fn marched_cone_cylinder_curves_end_on_the_band_edges() {
8531        let half_angle = 14.0_f64.atan2(10.0);
8532        let cone = ConicalSurface::new(
8533            Point3::new(0.0, 0.0, 273.2),
8534            Vec3::new(0.0, 0.0, -1.0),
8535            half_angle,
8536        )
8537        .unwrap();
8538        let cyl = CylindricalSurface::new(
8539            Point3::new(0.0, -50.0, 215.0),
8540            Vec3::new(0.0, 1.0, 0.0),
8541            60.0,
8542        )
8543        .unwrap();
8544        // The cone from z = 192 down to z = 178, the cylinder from y = -40
8545        // to y = 40.
8546        let v_cone = (81.2 / half_angle.sin(), 95.2 / half_angle.sin());
8547        let region = Aabb3 {
8548            min: Point3::new(-59.98, -40.0, 178.0),
8549            max: Point3::new(-47.23, 40.0, 192.0),
8550        };
8551        let curves = intersect_analytic_analytic_in_region(
8552            AnalyticSurface::Cone(&cone),
8553            AnalyticSurface::Cylinder(&cyl),
8554            32,
8555            Some(v_cone),
8556            Some((10.0, 90.0)),
8557            region,
8558        )
8559        .unwrap();
8560        assert_eq!(curves.len(), 2);
8561        for c in &curves {
8562            let (t0, t1) = c.curve.domain();
8563            for p in [c.curve.evaluate(t0), c.curve.evaluate(t1)] {
8564                let on_edge = (p.z() - 192.0).abs() < 1e-6 || (p.y().abs() - 40.0).abs() < 1e-6;
8565                assert!(on_edge, "a curve ends at {p:?}");
8566            }
8567        }
8568    }
8569
8570    /// Long steps along the same cone and cylinder: a step whose predictor
8571    /// leaves a band while the curve stays on it carries the march on, and
8572    /// each end still lies on a band's edge.
8573    #[test]
8574    fn long_march_steps_end_on_the_band_edges() {
8575        let half_angle = 14.0_f64.atan2(10.0);
8576        let cone = ConicalSurface::new(
8577            Point3::new(0.0, 0.0, 273.2),
8578            Vec3::new(0.0, 0.0, -1.0),
8579            half_angle,
8580        )
8581        .unwrap();
8582        let cyl = CylindricalSurface::new(
8583            Point3::new(0.0, -50.0, 215.0),
8584            Vec3::new(0.0, 1.0, 0.0),
8585            60.0,
8586        )
8587        .unwrap();
8588        let (a, b) = (
8589            AnalyticSurface::Cone(&cone),
8590            AnalyticSurface::Cylinder(&cyl),
8591        );
8592        let (surf_a, norm_a, u_a, _) = surface_closures(&a);
8593        let (surf_b, norm_b, u_b, _) = surface_closures(&b);
8594        let v_a = (81.2 / half_angle.sin(), 95.2 / half_angle.sin());
8595        let v_b = (10.0, 90.0);
8596        let seed = correct_to_intersection(
8597            &a,
8598            &b,
8599            surf_a.as_ref(),
8600            norm_a.as_ref(),
8601            surf_b.as_ref(),
8602            norm_b.as_ref(),
8603            Point3::new(-53.0, -30.0, 187.0),
8604            u_a,
8605            v_a,
8606            u_b,
8607            v_b,
8608            20,
8609        );
8610        for step in [0.5, 1.0, 2.0, 3.0] {
8611            let points = march_analytic_intersection(
8612                &a,
8613                &b,
8614                surf_a.as_ref(),
8615                norm_a.as_ref(),
8616                surf_b.as_ref(),
8617                norm_b.as_ref(),
8618                seed,
8619                u_a,
8620                v_a,
8621                u_b,
8622                v_b,
8623                step,
8624                true,
8625                true,
8626                None,
8627            )
8628            .unwrap();
8629            for p in [points[0], points[points.len() - 1]] {
8630                let on_edge = (p.z() - 192.0).abs() < 1e-6 || (p.y().abs() - 40.0).abs() < 1e-6;
8631                assert!(on_edge, "step {step}: the march ends at {p:?}");
8632            }
8633        }
8634    }
8635
8636    #[test]
8637    fn disjoint_cylinders_no_intersection() {
8638        let cyl_a =
8639            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
8640                .unwrap();
8641        let cyl_b =
8642            CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
8643                .unwrap();
8644
8645        let curves = intersect_analytic_analytic(
8646            AnalyticSurface::Cylinder(&cyl_a),
8647            AnalyticSurface::Cylinder(&cyl_b),
8648            16,
8649        )
8650        .unwrap();
8651
8652        assert!(curves.is_empty(), "disjoint cylinders should not intersect");
8653    }
8654
8655    // ── Oblique plane × cone conic (ellipse / parabola / hyperbola) ──────
8656
8657    /// Collect 3D points from a returned exact curve, sampling analytic forms.
8658    fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
8659        use crate::traits::ParametricCurve;
8660        match curve {
8661            ExactIntersectionCurve::Circle(c) => (0..=64)
8662                .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
8663                .collect(),
8664            ExactIntersectionCurve::Ellipse(e) => (0..=64)
8665                .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
8666                .collect(),
8667            ExactIntersectionCurve::Points(pts) => pts.clone(),
8668        }
8669    }
8670
8671    /// Assert every returned point lies on the plane and the cone surface, on
8672    /// the real (`v >= 0`) nappe, and within a sane axial bound.
8673    fn assert_on_plane_and_cone(
8674        curves: &[ExactIntersectionCurve],
8675        cone: &ConicalSurface,
8676        n: Vec3,
8677        d: f64,
8678        z_bound: (f64, f64),
8679    ) {
8680        assert!(!curves.is_empty(), "expected at least one section curve");
8681        let mut total = 0;
8682        for curve in curves {
8683            for p in collect_points(curve) {
8684                total += 1;
8685                let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
8686                assert!(
8687                    plane_err < 1e-9,
8688                    "point off plane by {plane_err:.2e}: {p:?}"
8689                );
8690                let (u, v) = cone.project_point(p);
8691                let q = cone.evaluate(u, v);
8692                let cone_err =
8693                    ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
8694                        .sqrt();
8695                assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
8696                assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
8697                assert!(
8698                    p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
8699                    "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
8700                    p.z()
8701                );
8702            }
8703        }
8704        assert!(total >= 8, "too few section points ({total})");
8705    }
8706
8707    #[test]
8708    fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
8709        // 45°-half-angle cone (axis +z). A plane tilted only ~16.7° off horizontal
8710        // has plane-axis angle ≈ 73° > 45° (the cone's half-opening from axis) →
8711        // ellipse. Must come back as an exact Ellipse, fully on both surfaces.
8712        let cone = ConicalSurface::new(
8713            Point3::new(0.0, 0.0, 0.0),
8714            Vec3::new(0.0, 0.0, 1.0),
8715            std::f64::consts::FRAC_PI_4,
8716        )
8717        .unwrap();
8718        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
8719        // Plane through (0,0,5): d = n·(0,0,5).
8720        let d = n.z() * 5.0;
8721        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8722        assert!(
8723            curves
8724                .iter()
8725                .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
8726            "oblique steep plane × cone must yield an exact Ellipse"
8727        );
8728        // The ellipse straddles z=5; with the 0.3 tilt the z-extent stays modest.
8729        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
8730    }
8731
8732    #[test]
8733    fn oblique_plane_cone_wrong_nappe_is_empty() {
8734        // Same ellipse-regime plane as above, but offset to the FAR side of the
8735        // apex (z=-5). The +z cone's real (v≥0) nappe is not met — only the
8736        // phantom v<0 nappe — so the result must be EMPTY, not a phantom ellipse.
8737        let cone = ConicalSurface::new(
8738            Point3::new(0.0, 0.0, 0.0),
8739            Vec3::new(0.0, 0.0, 1.0),
8740            std::f64::consts::FRAC_PI_4,
8741        )
8742        .unwrap();
8743        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
8744        let d = n.z() * -5.0;
8745        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8746        assert!(
8747            curves.is_empty(),
8748            "plane on the phantom-nappe side must yield no real curve, got {}",
8749            curves.len()
8750        );
8751    }
8752
8753    #[test]
8754    fn oblique_plane_cone_parabola_on_both_single_branch() {
8755        // Plane normal at exactly 45° to the axis (= the cone half-opening) → the
8756        // plane is parallel to a generator → parabola. One unbounded branch.
8757        let cone = ConicalSurface::new(
8758            Point3::new(0.0, 0.0, 0.0),
8759            Vec3::new(0.0, 0.0, 1.0),
8760            std::f64::consts::FRAC_PI_4,
8761        )
8762        .unwrap();
8763        let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
8764        let d = n.x() * 3.0 + n.z() * 3.0; // through (3,0,3)
8765        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8766        assert_eq!(
8767            curves.len(),
8768            1,
8769            "a parabola is a single branch, got {}",
8770            curves.len()
8771        );
8772        // Bounded by r_max = 32·|e|; |e| here is O(few), so allow a wide z window.
8773        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
8774    }
8775
8776    #[test]
8777    fn oblique_plane_cone_hyperbola_real_nappe_only() {
8778        // Faithful scooplabel lip-foot geometry: a 45° cone with axis −z and
8779        // apex at (−59,−59,15.85) (a bin corner), cut by the upper ramp tread
8780        // plane n=(0,0.99518,0.09802), d=−58.36056. The plane is nearly parallel
8781        // to the axis (cos≈0.098) → plane-axis angle ≈ 5.6° < 45° → hyperbola.
8782        // The downward real nappe is hit by exactly one branch; the phantom
8783        // upward nappe (and the asymptote runaway) must NOT appear, and the arc
8784        // must stay near the apex (the plane is ~1.2 mm from it).
8785        let cone = ConicalSurface::new(
8786            Point3::new(-59.0, -59.0, 15.85),
8787            Vec3::new(0.0, 0.0, -1.0),
8788            std::f64::consts::FRAC_PI_4,
8789        )
8790        .unwrap();
8791        let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
8792        let d = -58.360_56;
8793        let cos_theta = n.dot(cone.axis()).abs();
8794        assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
8795        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8796        // Real downward nappe only: never above the apex (z=15.85). The vertex is
8797        // ~1.2 mm from the apex, so the bounded arc stays within a few mm of it.
8798        assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
8799        // Every returned curve is sampled Points (no false Circle/Ellipse).
8800        for c in &curves {
8801            assert!(
8802                matches!(c, ExactIntersectionCurve::Points(_)),
8803                "hyperbola must be sampled Points, not a closed conic"
8804            );
8805        }
8806    }
8807
8808    /// Two spheres meet in one circle on both of them; spheres apart, one
8809    /// inside the other, or concentric of different radii meet in nothing,
8810    /// and one sphere twice has no curve.
8811    #[test]
8812    fn sphere_sphere_meets_in_a_circle_on_both() {
8813        let ball = |x: f64, y: f64, z: f64, r: f64| {
8814            SphericalSurface::new(Point3::new(x, y, z), r).unwrap()
8815        };
8816        let (a, b) = (ball(0.0, 0.0, 0.0, 2.0), ball(1.6, 0.3, 0.2, 1.5));
8817        let curves = exact_sphere_sphere(&a, &b).unwrap().unwrap();
8818        assert_eq!(curves.len(), 1);
8819        let circle = match &curves[0] {
8820            ExactIntersectionCurve::Circle(circle) => circle,
8821            other => unreachable!("expected a circle, got {other:?}"),
8822        };
8823        for k in 0..16 {
8824            let p = circle.evaluate(std::f64::consts::TAU * f64::from(k) / 16.0);
8825            assert!(((p - a.center()).length() - 2.0).abs() < 1e-12);
8826            assert!(((p - b.center()).length() - 1.5).abs() < 1e-12);
8827        }
8828        assert!(
8829            exact_sphere_sphere(&a, &ball(4.0, 0.0, 0.0, 1.5))
8830                .unwrap()
8831                .unwrap()
8832                .is_empty()
8833        );
8834        assert!(
8835            exact_sphere_sphere(&a, &ball(0.2, 0.0, 0.0, 1.0))
8836                .unwrap()
8837                .unwrap()
8838                .is_empty()
8839        );
8840        assert!(
8841            exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 1.0))
8842                .unwrap()
8843                .unwrap()
8844                .is_empty()
8845        );
8846        assert!(
8847            exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 2.0))
8848                .unwrap()
8849                .is_none()
8850        );
8851
8852        // A tiny sphere nearly bisected by a large one, in either order, and a
8853        // pair far from the origin: each meets in its small circle.
8854        let radius = |p: &SphericalSurface, q: &SphericalSurface| -> f64 {
8855            match exact_sphere_sphere(p, q).unwrap().unwrap().as_slice() {
8856                [ExactIntersectionCurve::Circle(c)] => c.radius(),
8857                other => unreachable!("expected one circle, got {other:?}"),
8858            }
8859        };
8860        let tiny = ball(2.0, 0.0, 0.0, 1e-5);
8861        assert!((radius(&a, &tiny) - 1e-5).abs() < 1e-9);
8862        assert!((radius(&tiny, &a) - 1e-5).abs() < 1e-9);
8863        let near = radius(&ball(0.0, 0.0, 0.0, 2.0), &ball(3.5, 0.0, 0.0, 1.500_001));
8864        let far = radius(
8865            &ball(1e10, 0.0, 0.0, 2.0),
8866            &ball(1e10 + 3.5, 0.0, 0.0, 1.500_001),
8867        );
8868        assert!(near > 1e-3);
8869        assert!((far - near).abs() < 1e-9 * near.max(1.0));
8870    }
8871
8872    /// Each line among `sections`, and whether it is a ray; any other
8873    /// section fails the test.
8874    #[allow(clippy::panic)]
8875    fn lines_of(sections: &[PlaneSection]) -> Vec<(Line3D, bool)> {
8876        sections
8877            .iter()
8878            .map(|s| match s {
8879                PlaneSection::Line { line, ray } => (line.clone(), *ray),
8880                other => panic!("expected a line, got {other:?}"),
8881            })
8882            .collect()
8883    }
8884
8885    /// A plane along a cylinder's axis cuts its rulings: two through the
8886    /// axis, two 2e-6 apart where it sinks a hair into the cylinder, the one
8887    /// it touches along, and none past it. `exact_plane_analytic` gives no
8888    /// curve for any of them.
8889    #[test]
8890    fn a_plane_along_a_cylinder_cuts_its_rulings() {
8891        let cyl =
8892            CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
8893                .unwrap();
8894        let y = Vec3::new(0.0, 1.0, 0.0);
8895        let surface = AnalyticSurface::Cylinder(&cyl);
8896        let on_both = |p: Point3, d: f64| {
8897            assert!((p.y() - d).abs() < 1e-12, "{p:?} off the plane y = {d}");
8898            assert!(
8899                (p.x().hypot(p.y()) - 1.0).abs() < 1e-12,
8900                "{p:?} off the cylinder"
8901            );
8902        };
8903        for (d, count) in [(0.0, 2), (1e-6_f64.cos(), 2), (1.0, 1), (1.5, 0)] {
8904            assert!(exact_plane_analytic(surface, y, d).unwrap().is_empty());
8905            let lines = lines_of(&exact_plane_section(surface, y, d).unwrap());
8906            assert_eq!(lines.len(), count, "plane y = {d}");
8907            let mut xs = Vec::new();
8908            for (line, ray) in lines {
8909                assert!(!ray);
8910                assert!(line.direction().cross(cyl.axis()).length() < 1e-12);
8911                for t in [-3.0, 0.0, 3.0] {
8912                    on_both(line.evaluate(t), d);
8913                }
8914                xs.push(line.evaluate(0.0).x());
8915            }
8916            if count == 2 {
8917                let apart = (xs[0] - xs[1]).abs();
8918                let want = 2.0 * (1.0 - d * d).sqrt();
8919                assert!(
8920                    (apart - want).abs() < 1e-9 * want.max(1e-6),
8921                    "{apart} apart"
8922                );
8923            }
8924        }
8925    }
8926
8927    /// A plane through a cone's apex cuts rays from it: two for a plane
8928    /// through the axis, one for a plane touching the cone along a ruling,
8929    /// and the apex alone for a plane missing the nappe. A plane 5e-8 off the
8930    /// apex still cuts its conic.
8931    #[test]
8932    #[allow(clippy::panic)]
8933    fn a_plane_through_a_cone_apex_cuts_its_rulings() {
8934        use std::f64::consts::FRAC_PI_4;
8935
8936        let cone = ConicalSurface::new(
8937            Point3::new(1.0, 2.0, 3.0),
8938            Vec3::new(0.0, 0.0, 1.0),
8939            FRAC_PI_4,
8940        )
8941        .unwrap();
8942        let surface = AnalyticSurface::Cone(&cone);
8943        let apex = cone.apex();
8944        let through = |n: Vec3| {
8945            let n = n.normalize().unwrap();
8946            let d = n.dot(apex - Point3::new(0.0, 0.0, 0.0));
8947            assert!(exact_plane_analytic(surface, n, d).unwrap().is_empty());
8948            (n, d, exact_plane_section(surface, n, d).unwrap())
8949        };
8950        for (n, count) in [
8951            (Vec3::new(1.0, 0.0, 0.0), 2),
8952            (Vec3::new(1.0, 0.0, -1.0), 1),
8953        ] {
8954            let (n, d, sections) = through(n);
8955            let rays = lines_of(&sections);
8956            assert_eq!(rays.len(), count, "plane normal {n:?}");
8957            for (line, ray) in rays {
8958                assert!(ray);
8959                assert!((line.evaluate(0.0) - apex).length() < 1e-12);
8960                let p = line.evaluate(2.0);
8961                assert!((n.dot(p - Point3::new(0.0, 0.0, 0.0)) - d).abs() < 1e-12);
8962                let rel = p - apex;
8963                assert!(rel.z() > 0.0, "{p:?} on the phantom nappe");
8964                assert!(
8965                    (rel.x().hypot(rel.y()) - rel.z()).abs() < 1e-12,
8966                    "{p:?} off the cone"
8967                );
8968            }
8969        }
8970        for n in [Vec3::new(0.1, 0.0, 1.0), Vec3::new(0.0, 0.0, 1.0)] {
8971            let (_, _, sections) = through(n);
8972            assert!(
8973                matches!(sections[..], [PlaneSection::Point(p)] if (p - apex).length() < 1e-12),
8974                "{sections:?}"
8975            );
8976        }
8977
8978        let upright = ConicalSurface::new(
8979            Point3::new(0.0, 0.0, 0.0),
8980            Vec3::new(0.0, 0.0, 1.0),
8981            FRAC_PI_4,
8982        )
8983        .unwrap();
8984        let n = Vec3::new((0.5 - 1e-8_f64).sqrt(), 0.0, (0.5 + 1e-8_f64).sqrt());
8985        let sections = exact_plane_section(AnalyticSurface::Cone(&upright), n, 5e-8).unwrap();
8986        let [PlaneSection::Ellipse(ellipse)] = &sections[..] else {
8987            panic!("{sections:?}");
8988        };
8989        assert!(
8990            ellipse.semi_major() > 1.0,
8991            "semi-major {}",
8992            ellipse.semi_major()
8993        );
8994    }
8995
8996    /// A plane touching a sphere meets it at the point of contact, and one a
8997    /// hair inside cuts the small circle there, however small.
8998    #[test]
8999    #[allow(clippy::panic)]
9000    fn a_plane_touching_a_sphere_meets_it_at_a_point() {
9001        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 1.0), 1.0).unwrap();
9002        let surface = AnalyticSurface::Sphere(&sphere);
9003        let z = Vec3::new(0.0, 0.0, 1.0);
9004        assert!(exact_plane_analytic(surface, z, 0.0).unwrap().is_empty());
9005        let sections = exact_plane_section(surface, z, 0.0).unwrap();
9006        assert!(
9007            matches!(sections[..], [PlaneSection::Point(p)] if p.z().abs() < 1e-15 && p.x() == 0.0),
9008            "{sections:?}"
9009        );
9010        assert!(exact_plane_section(surface, z, -1e-9).unwrap().is_empty());
9011        for height in [5e-15, 1e-12, 1e-8] {
9012            let sections = exact_plane_section(surface, z, height).unwrap();
9013            let [PlaneSection::Circle(circle)] = &sections[..] else {
9014                panic!("{sections:?}");
9015            };
9016            let want = (height * (2.0 - height)).sqrt();
9017            assert!(
9018                (circle.radius() - want).abs() < 1e-3 * want,
9019                "circle at z = {height}: radius {}, want {want}",
9020                circle.radius()
9021            );
9022            assert!((circle.center().z() - height).abs() < 1e-15);
9023        }
9024    }
9025
9026    /// The farthest any of `curves` strays from `off`, sampled densely.
9027    fn farthest(curves: &[IntersectionCurve], off: impl Fn(Point3) -> f64) -> f64 {
9028        let mut far = 0.0_f64;
9029        for ic in curves {
9030            let (t0, t1) = ic.curve.domain();
9031            for i in 0..=2000 {
9032                let t = t0 + (t1 - t0) * f64::from(i) / 2000.0;
9033                far = far.max(off(ic.curve.evaluate(t)));
9034            }
9035        }
9036        far
9037    }
9038
9039    /// A ball sitting in a bore of its own radius touches it along its
9040    /// equator, which comes back as the exact circle.
9041    #[test]
9042    fn a_ball_in_its_bore_meets_it_on_an_exact_circle() {
9043        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
9044        let bore =
9045            CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9046                .unwrap();
9047        let curves = intersect_analytic_analytic_bounded(
9048            AnalyticSurface::Sphere(&ball),
9049            AnalyticSurface::Cylinder(&bore),
9050            64,
9051            None,
9052            Some((0.0, 4.0)),
9053        )
9054        .unwrap();
9055        assert_eq!(curves.len(), 1);
9056        let far = farthest(&curves, |p| {
9057            let on_ball = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
9058            on_ball
9059                .max((p.x().hypot(p.y()) - 1.0).abs())
9060                .max(p.z().abs())
9061        });
9062        assert!(far < 1e-14, "circle strays {far:.2e}");
9063    }
9064
9065    /// Two unit balls a unit apart meet in a circle of radius √3/2, which
9066    /// comes back exact.
9067    #[test]
9068    fn overlapping_balls_meet_on_an_exact_circle() {
9069        let a = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
9070        let b = SphericalSurface::new(Point3::new(1.0, 0.0, 0.0), 1.0).unwrap();
9071        let curves = intersect_analytic_analytic_bounded(
9072            AnalyticSurface::Sphere(&a),
9073            AnalyticSurface::Sphere(&b),
9074            64,
9075            None,
9076            None,
9077        )
9078        .unwrap();
9079        assert_eq!(curves.len(), 1);
9080        let far = farthest(&curves, |p| {
9081            let on_a = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
9082            on_a.max(((p - Point3::new(1.0, 0.0, 0.0)).length() - 1.0).abs())
9083        });
9084        assert!(far < 1e-14, "circle strays {far:.2e}");
9085    }
9086
9087    /// A loop with semi-axes 3 and 1.5 in a tilted frame lies on its ellipse
9088    /// all the way round and starts at the end of its major axis.
9089    #[test]
9090    fn a_conic_loop_is_its_ellipse() {
9091        let centre = Point3::new(1.0, -2.0, 0.5);
9092        let frame = Frame3::from_normal(centre, Vec3::new(0.3, -0.4, 1.0)).unwrap();
9093        let curve = conic_loop(centre, frame.x, frame.y, 3.0, 1.5).unwrap();
9094        let (t0, t1) = curve.domain();
9095        assert!((curve.evaluate(t0) - (centre + frame.x * 3.0)).length() < 1e-15);
9096        for i in 0..=2000 {
9097            let p = curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 2000.0) - centre;
9098            let (x, y) = (p.dot(frame.x) / 3.0, p.dot(frame.y) / 1.5);
9099            assert!(
9100                (x.hypot(y) - 1.0).abs() < 1e-14,
9101                "off its ellipse by {}",
9102                x.hypot(y) - 1.0
9103            );
9104            assert!(p.dot(frame.z).abs() < 1e-14);
9105        }
9106    }
9107
9108    /// A ball sitting in a ring's hole, and a ring resting on a wider one,
9109    /// meet them along the one circle where they touch, and the bounded
9110    /// call returns it exactly.
9111    #[test]
9112    fn touching_coaxial_rings_meet_along_one_circle() {
9113        let z = Vec3::new(0.0, 0.0, 1.0);
9114        let x = Vec3::new(1.0, 0.0, 0.0);
9115        let ring =
9116            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), 3.0, 1.0, z, x)
9117                .unwrap();
9118        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
9119        let curves = intersect_analytic_analytic_bounded(
9120            AnalyticSurface::Sphere(&ball),
9121            AnalyticSurface::Torus(&ring),
9122            64,
9123            None,
9124            None,
9125        )
9126        .unwrap();
9127        assert_eq!(curves.len(), 1);
9128        let far = farthest(&curves, |p| {
9129            let q = p - Point3::new(0.0, 0.0, 0.0);
9130            let rho = q.x().hypot(q.y());
9131            let on_ring = ((rho - 3.0).hypot(q.z()) - 1.0).abs();
9132            on_ring.max((q.length() - 2.0).abs())
9133        });
9134        assert!(far < 1e-14, "circle strays {far:.2e}");
9135
9136        // Tubes of radius 1 and 0.5 on rings of radius 3 and 3.9, the second
9137        // raised 1.2: their centres lie 1.5 apart, so they touch a third of
9138        // the way along, at height 0.8 on a circle of radius 3.6.
9139        let wider =
9140            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 1.2), 3.9, 0.5, z, x)
9141                .unwrap();
9142        let touching = exact_torus_torus(&ring, &wider).unwrap().unwrap();
9143        let circles = circles_of(&touching);
9144        assert_eq!(circles.len(), 1);
9145        assert!(
9146            (circles[0].radius() - 3.6).abs() < 1e-12,
9147            "{}",
9148            circles[0].radius()
9149        );
9150        assert!((circles[0].center().z() - 0.8).abs() < 1e-12);
9151    }
9152
9153    /// Unit tubes on rings of radius 1e6 and 1e6 + 1.999 overlap by 0.001
9154    /// and cross in two circles 0.063 apart; on rings 2.001 apart they miss.
9155    /// Neither is read as a touch, at a scale where a millionth of it is
9156    /// two thousandths.
9157    #[test]
9158    fn huge_coaxial_rings_cross_or_miss_rather_than_touch() {
9159        let z = Vec3::new(0.0, 0.0, 1.0);
9160        let x = Vec3::new(1.0, 0.0, 0.0);
9161        let ring = |big: f64| {
9162            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), big, 1.0, z, x)
9163                .unwrap()
9164        };
9165        let crossing = exact_torus_torus(&ring(1e6), &ring(1_000_001.999))
9166            .unwrap()
9167            .unwrap();
9168        let circles = circles_of(&crossing);
9169        assert_eq!(circles.len(), 2);
9170        for circle in circles {
9171            let height = (1.0 - 0.9995_f64 * 0.9995).sqrt();
9172            assert!(
9173                (circle.center().z().abs() - height).abs() < 1e-9,
9174                "{}",
9175                circle.center().z()
9176            );
9177        }
9178        let apart = exact_torus_torus(&ring(1e6), &ring(1_000_002.001))
9179            .unwrap()
9180            .unwrap();
9181        assert!(apart.is_empty());
9182    }
9183
9184    /// A plane parallel to a cone's axis cuts the branch of a hyperbola on
9185    /// the cone's one nappe; planes parallel to a generator cut a parabola
9186    /// on one side of the apex and miss the cone on the other.
9187    #[test]
9188    fn a_plane_cuts_a_cones_open_conics() {
9189        let up = Vec3::new(0.0, 0.0, 1.0);
9190        let on_cone = |p: Point3, slope: f64| (p.z() - slope * p.x().hypot(p.y())).abs();
9191        let steep =
9192            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 60_f64.to_radians()).unwrap();
9193        let slope = 60_f64.to_radians().tan();
9194        let along =
9195            exact_plane_section(AnalyticSurface::Cone(&steep), Vec3::new(1.0, 0.0, 0.0), 1.0)
9196                .unwrap();
9197        let [PlaneSection::Hyperbola(h)] = along.as_slice() else {
9198            unreachable!("{along:?}")
9199        };
9200        for i in -20..=20 {
9201            let p = h.evaluate(f64::from(i) / 5.0);
9202            assert!((p.x() - 1.0).abs() < 1e-12 && p.z() > 0.0, "{p:?}");
9203            assert!(on_cone(p, slope) < 1e-12 * p.z().max(1.0), "{p:?}");
9204        }
9205        let even =
9206            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 45_f64.to_radians()).unwrap();
9207        let tilt = Vec3::new(-1.0, 0.0, 1.0) * std::f64::consts::FRAC_1_SQRT_2;
9208        let above = exact_plane_section(AnalyticSurface::Cone(&even), tilt, 1.0).unwrap();
9209        let [PlaneSection::Parabola(parabola)] = above.as_slice() else {
9210            unreachable!("{above:?}")
9211        };
9212        for i in -20..=20 {
9213            let p = parabola.evaluate(f64::from(i) / 2.0);
9214            assert!(
9215                (tilt.dot(p - Point3::new(0.0, 0.0, 0.0)) - 1.0).abs() < 1e-12,
9216                "{p:?}"
9217            );
9218            assert!(
9219                p.z() > 0.0 && on_cone(p, 1.0) < 1e-12 * p.z().max(1.0),
9220                "{p:?}"
9221            );
9222        }
9223        let below = exact_plane_section(AnalyticSurface::Cone(&even), tilt, -1.0).unwrap();
9224        assert!(below.is_empty(), "{below:?}");
9225    }
9226
9227    /// A cone so flat it rises 1e-7 from its radial plane, cut by a plane
9228    /// tilted 7e-7 off it, and a cone so narrow it opens 5e-7 off its axis,
9229    /// cut by a plane parallel to the axis, give sections that lie on the
9230    /// cone: a hyperbola for the flat one, read from its eccentricity, and
9231    /// sampled points where the formulas lose their digits.
9232    #[test]
9233    fn extreme_cones_give_sections_on_the_cone() {
9234        let up = Vec3::new(0.0, 0.0, 1.0);
9235        let apex = Point3::new(0.0, 0.0, 0.0);
9236        let holds = |cone: &ConicalSurface, q: Point3| {
9237            let w = q - apex;
9238            (w.dot(up) - cone.half_angle().sin() * w.length()).abs() <= 1e-6 * (1.0 + w.length())
9239        };
9240        let flat = ConicalSurface::new(apex, up, 1e-7).unwrap();
9241        let tilt = Vec3::new(5e-13_f64.sqrt(), 0.0, (1.0 - 5e-13_f64).sqrt());
9242        let needle = ConicalSurface::new(apex, up, FRAC_PI_2 - 5e-7).unwrap();
9243        for (cone, normal, d) in [(&flat, tilt, 1.0), (&needle, Vec3::new(1.0, 0.0, 0.0), 1.0)] {
9244            let sections = exact_plane_section(AnalyticSurface::Cone(cone), normal, d).unwrap();
9245            assert!(!sections.is_empty());
9246            for section in &sections {
9247                let points: Vec<Point3> = match section {
9248                    PlaneSection::Hyperbola(h) => {
9249                        (-4..=4).map(|i| h.evaluate(f64::from(i) / 4.0)).collect()
9250                    }
9251                    PlaneSection::Parabola(q) => {
9252                        (-4..=4).map(|i| q.evaluate(f64::from(i))).collect()
9253                    }
9254                    PlaneSection::Points(points) => points.clone(),
9255                    other => unreachable!("{other:?}"),
9256                };
9257                for q in points {
9258                    assert!(holds(cone, q), "{q:?} off the cone");
9259                }
9260            }
9261        }
9262        let flat_section = exact_plane_section(AnalyticSurface::Cone(&flat), tilt, 1.0).unwrap();
9263        assert!(matches!(
9264            flat_section.as_slice(),
9265            [PlaneSection::Hyperbola(_)]
9266        ));
9267    }
9268
9269    /// The rulings two parallel cylinders meet along, from the bounded call
9270    /// with each face's `v` range: each ruling's ends, sorted by height.
9271    fn parallel_rulings(
9272        (c1, r1, v1): (Point3, f64, (f64, f64)),
9273        (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
9274    ) -> Vec<(Point3, Point3)> {
9275        rulings_within((c1, r1, v1), (c2, r2, axis2, v2), 1e-12)
9276    }
9277
9278    /// [`parallel_rulings`] with each curve held to `tolerance` of both
9279    /// cylinders.
9280    fn rulings_within(
9281        (c1, r1, v1): (Point3, f64, (f64, f64)),
9282        (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
9283        tolerance: f64,
9284    ) -> Vec<(Point3, Point3)> {
9285        let a = CylindricalSurface::new(c1, Vec3::new(0.0, 0.0, 1.0), r1).unwrap();
9286        let b = CylindricalSurface::new(c2, axis2, r2).unwrap();
9287        let curves = intersect_analytic_analytic_bounded(
9288            AnalyticSurface::Cylinder(&a),
9289            AnalyticSurface::Cylinder(&b),
9290            32,
9291            Some(v1),
9292            Some(v2),
9293        )
9294        .unwrap();
9295        curves
9296            .iter()
9297            .map(|ic| {
9298                let (t0, t1) = ic.curve.domain();
9299                let (p, q) = (ic.curve.evaluate(t0), ic.curve.evaluate(t1));
9300                for i in 0..=100 {
9301                    let x = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 100.0);
9302                    let on_a = ((x - c1) - Vec3::new(0.0, 0.0, (x - c1).z())).length() - r1;
9303                    let w = x - c2;
9304                    let on_b = (w - axis2 * w.dot(axis2)).length() - r2;
9305                    assert!(
9306                        on_a.abs() < tolerance && on_b.abs() < tolerance,
9307                        "{x:?} off a cylinder by {on_a:.1e}, {on_b:.1e}"
9308                    );
9309                }
9310                if p.z() <= q.z() { (p, q) } else { (q, p) }
9311            })
9312            .collect()
9313    }
9314
9315    /// Rods of radius 1 with axes 1.2 apart overlap along two rulings, at
9316    /// x 0.6 and y ±0.8, over the height both faces share; the second rod's
9317    /// axis runs down, so its range counts down from its origin.
9318    #[test]
9319    fn overlapping_parallel_rods_meet_along_two_rulings() {
9320        let mut rulings = parallel_rulings(
9321            (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 4.0)),
9322            (
9323                Point3::new(1.2, 0.0, 3.0),
9324                1.0,
9325                Vec3::new(0.0, 0.0, -1.0),
9326                (0.0, 2.0),
9327            ),
9328        );
9329        rulings.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
9330        assert_eq!(rulings.len(), 2);
9331        for ((lo, hi), y) in rulings.into_iter().zip([-0.8, 0.8]) {
9332            assert!((lo - Point3::new(0.6, y, 1.0)).length() < 1e-12, "{lo:?}");
9333            assert!((hi - Point3::new(0.6, y, 3.0)).length() < 1e-12, "{hi:?}");
9334        }
9335    }
9336
9337    /// Rods touching side by side, or one inside another against its wall,
9338    /// meet along the one ruling where they touch; rods apart do not meet.
9339    #[test]
9340    fn touching_parallel_rods_meet_along_one_ruling() {
9341        let up = Vec3::new(0.0, 0.0, 1.0);
9342        let beside = parallel_rulings(
9343            (Point3::new(0.0, 0.0, 0.0), 1.0, (-2.0, 2.0)),
9344            (Point3::new(2.0, 0.0, -2.0), 1.0, up, (0.0, 4.0)),
9345        );
9346        assert_eq!(beside.len(), 1);
9347        assert!((beside[0].0 - Point3::new(1.0, 0.0, -2.0)).length() < 1e-12);
9348        assert!((beside[0].1 - Point3::new(1.0, 0.0, 2.0)).length() < 1e-12);
9349        let inside = parallel_rulings(
9350            (Point3::new(0.0, 0.0, 0.0), 2.0, (0.0, 1.0)),
9351            (Point3::new(-1.0, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
9352        );
9353        assert_eq!(inside.len(), 1);
9354        assert!((inside[0].0 - Point3::new(-2.0, 0.0, 0.0)).length() < 1e-12);
9355        let apart = parallel_rulings(
9356            (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 1.0)),
9357            (Point3::new(2.5, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
9358        );
9359        assert!(apart.is_empty());
9360    }
9361
9362    /// Rods whose axes lean 1e-5 apart drift 1e-3 over a span of 100, so
9363    /// the rulings defer to the next solver there; over a span of 0.001
9364    /// they drift 1e-8 and keep their two rulings.
9365    #[test]
9366    fn rods_leaning_apart_keep_rulings_only_over_a_short_span() {
9367        let up = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9368            .unwrap();
9369        let lean = Vec3::new(1e-5_f64.sin(), 0.0, 1e-5_f64.cos());
9370        let leaning = CylindricalSurface::new(Point3::new(1.2, 0.0, 0.0), lean, 1.0).unwrap();
9371        let span = |h: f64| parallel_cylinders(&up, &leaning, Some((0.0, h)), Some((0.0, h)));
9372        assert!(span(100.0).unwrap().is_none());
9373        assert_eq!(span(0.001).unwrap().map(|r| r.len()), Some(2));
9374    }
9375
9376    /// Huge rods a short stretch long still meet along both rulings, and
9377    /// rods of radius 100 whose axes lie 3e-7 short of touching meet along
9378    /// two rulings 0.011 apart, not the one where they would touch.
9379    #[test]
9380    fn parallel_rods_keep_short_and_close_rulings() {
9381        let up = Vec3::new(0.0, 0.0, 1.0);
9382        let huge = rulings_within(
9383            (Point3::new(0.0, 0.0, 0.0), 1e6, (0.0, 0.001)),
9384            (Point3::new(1.2e6, 0.0, 0.0), 1e6, up, (0.0, 0.001)),
9385            1e-9,
9386        );
9387        assert_eq!(huge.len(), 2);
9388        assert!(
9389            huge.iter()
9390                .all(|(lo, hi)| ((*hi - *lo).length() - 0.001).abs() < 1e-12)
9391        );
9392        let mut close = rulings_within(
9393            (Point3::new(0.0, 0.0, 0.0), 100.0, (0.0, 1.0)),
9394            (Point3::new(199.999_999_7, 0.0, 0.0), 100.0, up, (0.0, 1.0)),
9395            1e-9,
9396        );
9397        assert_eq!(close.len(), 2);
9398        close.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
9399        let apart = close[1].0.y() - close[0].0.y();
9400        assert!((apart - 0.010_954).abs() < 1e-5, "{apart}");
9401    }
9402
9403    /// How far `p` lies off `cone` (either nappe), and its `v` there.
9404    fn off_cone(cone: &ConicalSurface, p: Point3) -> (f64, f64) {
9405        let q = p - cone.apex();
9406        let (along, s) = (q.dot(cone.axis()), cone.half_angle().sin());
9407        ((along.abs() - s * q.length()).abs(), along / s)
9408    }
9409
9410    /// Cones sharing an apex, their axes 40° apart and each opening 20°
9411    /// from its axis, touch along the one ruling between the axes, which
9412    /// runs where both faces hold it.
9413    #[test]
9414    fn cones_sharing_an_apex_touch_along_one_ruling() {
9415        let apex = Point3::new(1.0, 2.0, 3.0);
9416        let a = 20.0_f64.to_radians();
9417        let half = std::f64::consts::FRAC_PI_2 - a;
9418        let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
9419        let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
9420        let curves = intersect_analytic_analytic_bounded(
9421            AnalyticSurface::Cone(&c1),
9422            AnalyticSurface::Cone(&c2),
9423            64,
9424            Some((0.2, 3.0)),
9425            Some((0.5, 4.0)),
9426        )
9427        .unwrap();
9428        assert_eq!(curves.len(), 1);
9429        let curve = &curves[0].curve;
9430        let (t0, t1) = curve.domain();
9431        let x = Vec3::new(1.0, 0.0, 0.0);
9432        assert!((curve.evaluate(t0) - (apex + x * 0.5)).length() < 1e-12);
9433        assert!((curve.evaluate(t1) - (apex + x * 3.0)).length() < 1e-12);
9434    }
9435
9436    /// Cones sharing an apex, their axes 20° apart and each opening 30°,
9437    /// cross along two rulings; faces reaching past the apex hold each on
9438    /// both sides of it, in two segments that end there.
9439    #[test]
9440    fn cones_sharing_an_apex_cross_along_two_rulings() {
9441        let apex = Point3::new(-1.0, 0.5, 2.0);
9442        let b = 20.0_f64.to_radians();
9443        let half = 60.0_f64.to_radians();
9444        let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9445        let c2 = ConicalSurface::new(apex, Vec3::new(b.sin(), 0.0, b.cos()), half).unwrap();
9446        for (range, pieces) in [((0.5, 2.0), 2), ((-2.0, 2.0), 4)] {
9447            let curves = intersect_analytic_analytic_bounded(
9448                AnalyticSurface::Cone(&c1),
9449                AnalyticSurface::Cone(&c2),
9450                64,
9451                Some(range),
9452                Some(range),
9453            )
9454            .unwrap();
9455            assert_eq!(curves.len(), pieces, "{range:?}");
9456            for ic in &curves {
9457                let (t0, t1) = ic.curve.domain();
9458                for k in 0..=20 {
9459                    let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 20.0);
9460                    for cone in [&c1, &c2] {
9461                        let (off, v) = off_cone(cone, p);
9462                        assert!(off < 1e-12, "{range:?}: off a cone by {off:.2e}");
9463                        assert!(v > range.0 - 1e-12 && v < range.1 + 1e-12);
9464                    }
9465                }
9466                if pieces == 4 {
9467                    let ends = [ic.curve.evaluate(t0), ic.curve.evaluate(t1)];
9468                    assert!(ends.iter().any(|&e| (e - apex).length() < 1e-12));
9469                }
9470                for point in &ic.points {
9471                    let (on1, on2) = (point.param1, point.param2);
9472                    assert!((c1.evaluate(on1.0, on1.1) - point.point).length() < 1e-9);
9473                    assert!((c2.evaluate(on2.0, on2.1) - point.point).length() < 1e-9);
9474                }
9475            }
9476        }
9477    }
9478
9479    /// Axes 1e-8 apart in angle leave a ruling's part across them to
9480    /// rounding, and cones touching within rounding along a ruling leave
9481    /// how far apart their rulings may be 1e6 out to it: neither is solved
9482    /// here.
9483    #[test]
9484    fn cones_sharing_an_apex_defer_what_rounding_cannot_settle() {
9485        let apex = Point3::new(0.0, 0.0, 0.0);
9486        let half = 60.0_f64.to_radians();
9487        let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9488        let c2 = ConicalSurface::new(apex, Vec3::new(1e-8_f64.sin(), 0.0, 1e-8_f64.cos()), half)
9489            .unwrap();
9490        let near = Some((0.5, 2.0));
9491        assert!(shared_apex_cones(&c1, &c2, near, near).unwrap().is_none());
9492        let a = 20.0_f64.to_radians();
9493        let half = std::f64::consts::FRAC_PI_2 - a;
9494        let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
9495        let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
9496        let far = Some((0.5, 1e6));
9497        assert!(shared_apex_cones(&c1, &c2, far, far).unwrap().is_none());
9498    }
9499
9500    /// Perpendicular cones opening 1e-15 short of touching cross along two
9501    /// rulings, which part by about 0.09 a million out: two segments.
9502    #[test]
9503    fn cones_sharing_an_apex_just_short_of_touching_cross_in_two_rulings() {
9504        let apex = Point3::new(0.0, 0.0, 0.0);
9505        let half = std::f64::consts::FRAC_PI_4 - 1e-15;
9506        let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9507        let c2 = ConicalSurface::new(apex, Vec3::new(1.0, 0.0, 0.0), half).unwrap();
9508        let range = Some((0.5, 1e6));
9509        let curves = shared_apex_cones(&c1, &c2, range, range).unwrap().unwrap();
9510        assert_eq!(curves.len(), 2);
9511        let ends: Vec<Point3> = curves
9512            .iter()
9513            .map(|ic| ic.curve.evaluate(ic.curve.domain().1))
9514            .collect();
9515        assert!((ends[0] - ends[1]).length() > 0.05);
9516    }
9517
9518    /// A ball off a ring's axis touches it at one point from outside the
9519    /// tube, from inside it, or holding the whole ring, and that point is
9520    /// all they share. A ball reaching 1e-6 further cuts the tube in a small
9521    /// loop, which is left to the section's closed form, and one centred on
9522    /// the core circle with the tube's radius meets it along the meridian
9523    /// circle through its centre.
9524    #[test]
9525    fn a_ball_off_a_rings_axis_touches_it_at_one_point() {
9526        let o = Point3::new(1.0, 2.0, 3.0);
9527        let ring = ToroidalSurface::new(o, 3.0, 1.0).unwrap();
9528        let (s, c) = 30.0_f64.to_radians().sin_cos();
9529        let (out, up) = (Vec3::new(c, s, 0.0), Vec3::new(0.0, 0.0, 1.0));
9530        let on_ring = |p: Point3| {
9531            let q = p - o;
9532            ((q.x().hypot(q.y()) - 3.0).hypot(q.z()) - 1.0).abs()
9533        };
9534        let balls = [
9535            (o + out * 5.0, 1.0),
9536            (o + out * 3.2 + up * 0.1, 1.0 - 0.05_f64.sqrt()),
9537            (o + out + up * 0.5, 1.0 + 16.25_f64.sqrt()),
9538        ];
9539        let mut touches = Vec::new();
9540        for (centre, radius) in balls {
9541            let ball = SphericalSurface::new(centre, radius).unwrap();
9542            let exacts = exact_sphere_torus(&ball, &ring).unwrap().unwrap();
9543            let p = match exacts.as_slice() {
9544                [ExactIntersectionCurve::Points(points)] => points[0],
9545                _ => unreachable!("one touching point"),
9546            };
9547            assert!(on_ring(p) < 1e-12 && ((p - centre).length() - radius).abs() < 1e-12);
9548            let curves = intersect_analytic_analytic(
9549                AnalyticSurface::Sphere(&ball),
9550                AnalyticSurface::Torus(&ring),
9551                16,
9552            )
9553            .unwrap();
9554            assert_eq!(curves.len(), 1);
9555            let (t0, t1) = curves[0].curve.domain();
9556            assert!((curves[0].curve.evaluate(t0) - p).length() < 1e-15);
9557            assert!((curves[0].curve.evaluate(t1) - p).length() < 1e-15);
9558            touches.push(p);
9559        }
9560        assert!((touches[0] - (o + out * 4.0)).length() < 1e-12);
9561        let past = SphericalSurface::new(o + out * 5.0, 1.0 + 1e-6).unwrap();
9562        assert!(exact_sphere_torus(&past, &ring).unwrap().is_none());
9563        let on_core = SphericalSurface::new(o + out * 3.0, 1.0).unwrap();
9564        let meridian = exact_sphere_torus(&on_core, &ring).unwrap().unwrap();
9565        let [ExactIntersectionCurve::Circle(circle)] = meridian.as_slice() else {
9566            unreachable!("one meridian circle");
9567        };
9568        assert!((circle.center() - (o + out * 3.0)).length() < 1e-12);
9569        assert!((circle.radius() - 1.0).abs() < 1e-12);
9570    }
9571
9572    /// A taper pin through a rod turned `spin` about its axis, as
9573    /// `a_taper_pin_through_a_turned_rod_traces_both_loops` builds it: the pin,
9574    /// its faces' `v` range, and its apex's `y`.
9575    fn taper_pin_and_rod(
9576        flip: bool,
9577        spin: f64,
9578    ) -> (ConicalSurface, (f64, f64), f64, CylindricalSurface) {
9579        let slope = 0.7_f64 / 16.0;
9580        let half = (1.0 / slope).atan();
9581        let (apex_y, axis_y) = if flip {
9582            (-8.0 - 0.8 / slope, 1.0)
9583        } else {
9584            (-8.0 + 1.5 / slope, -1.0)
9585        };
9586        let pin = ConicalSurface::new(
9587            Point3::new(0.0, apex_y, 10.0),
9588            Vec3::new(0.0, axis_y, 0.0),
9589            half,
9590        )
9591        .unwrap();
9592        let (h0, h1) = ((-8.0 - apex_y).abs(), (8.0 - apex_y).abs());
9593        let v_pin = (h0.min(h1) / half.sin(), h0.max(h1) / half.sin());
9594        let rod = CylindricalSurface::with_ref_dir(
9595            Point3::new(0.0, 0.0, 0.0),
9596            Vec3::new(0.0, 0.0, 1.0),
9597            5.0,
9598            Vec3::new(spin.cos(), spin.sin(), 0.0),
9599        )
9600        .unwrap();
9601        (pin, v_pin, apex_y, rod)
9602    }
9603
9604    /// The overlap of the taper pin's and the rod's faces, a little wide.
9605    const TAPER_PIN_REGION: Aabb3 = Aabb3 {
9606        min: Point3::new(-1.6, -5.1, 8.4),
9607        max: Point3::new(1.6, 5.1, 11.6),
9608    };
9609
9610    /// The farthest that `n` points of `curve` lie off a surface, by `off`.
9611    fn farthest_along(curve: &NurbsCurve, n: u32, off: impl Fn(Point3) -> f64) -> f64 {
9612        let (t0, t1) = curve.domain();
9613        (0..=n)
9614            .map(|k| off(curve.evaluate((t1 - t0).madd(f64::from(k) / f64::from(n), t0))))
9615            .fold(0.0, f64::max)
9616    }
9617
9618    /// The general marcher traces a taper pin's two loops on a rod (which the
9619    /// rulings trace, so the marcher is called on its own here), a cone and a
9620    /// tilted tube, and a cone's band across a wide cylinder. Its cubic fits
9621    /// stay within the linear tolerance of both surfaces between their
9622    /// points, not only at them: fits through the marched points alone lay
9623    /// 2e-5 to 1.1e-4 off both, with the points 0.08 to 0.31 apart.
9624    #[test]
9625    fn marched_cone_cylinder_sections_stay_on_both_between_their_points() {
9626        let lin = Tolerance::new().linear;
9627        for flip in [false, true] {
9628            for spin in [0.0_f64, 0.3, 0.9, 1.4, 2.0, 2.6, 3.0, 3.6] {
9629                let (pin, v_pin, apex_y, rod) = taper_pin_and_rod(flip, spin);
9630                let half = pin.half_angle();
9631                let off_pin = |p: Point3| {
9632                    let rho = p.x().hypot(p.z() - 10.0);
9633                    let h = (p.y() - apex_y).abs();
9634                    rho.madd(half.sin(), -h * half.cos()).abs()
9635                };
9636                let off_rod = |p: Point3| (p.x().hypot(p.y()) - 5.0).abs();
9637                for rod_first in [true, false] {
9638                    let (a, b, va, vb) = if rod_first {
9639                        (
9640                            AnalyticSurface::Cylinder(&rod),
9641                            AnalyticSurface::Cone(&pin),
9642                            Some((0.0, 20.0)),
9643                            Some(v_pin),
9644                        )
9645                    } else {
9646                        (
9647                            AnalyticSurface::Cone(&pin),
9648                            AnalyticSurface::Cylinder(&rod),
9649                            Some(v_pin),
9650                            Some((0.0, 20.0)),
9651                        )
9652                    };
9653                    let curves =
9654                        marched_sections(a, b, 32, va, vb, Some(TAPER_PIN_REGION)).unwrap();
9655                    assert_eq!(curves.len(), 2, "spin {spin} flip {flip}: loops");
9656                    for c in &curves {
9657                        let worst = farthest_along(&c.curve, 4000, |p| off_pin(p).max(off_rod(p)));
9658                        assert!(worst <= lin, "spin {spin} flip {flip}: off by {worst:.2e}");
9659                    }
9660                }
9661            }
9662        }
9663
9664        let (cone, tube) = cone_and_tilted_tube();
9665        let curves = intersect_analytic_analytic_bounded(
9666            AnalyticSurface::Cone(&cone),
9667            AnalyticSurface::Cylinder(&tube),
9668            32,
9669            Some((0.5, 4.0)),
9670            Some((-5.0, 5.0)),
9671        )
9672        .unwrap();
9673        assert!(!curves.is_empty());
9674        let (sin, cos) = cone.half_angle().sin_cos();
9675        let axis = tube.axis();
9676        for c in &curves {
9677            let worst = farthest_along(&c.curve, 4000, |p| {
9678                let on_cone = p.x().hypot(p.y()).madd(sin, -p.z().abs() * cos).abs();
9679                let w = p - tube.origin();
9680                let on_tube = ((w - axis * axis.dot(w)).length() - 0.1).abs();
9681                on_cone.max(on_tube)
9682            });
9683            assert!(worst <= lin, "tilted tube: off by {worst:.2e}");
9684        }
9685
9686        let half_angle = 14.0_f64.atan2(10.0);
9687        let cone = ConicalSurface::new(
9688            Point3::new(0.0, 0.0, 273.2),
9689            Vec3::new(0.0, 0.0, -1.0),
9690            half_angle,
9691        )
9692        .unwrap();
9693        let cyl = CylindricalSurface::new(
9694            Point3::new(0.0, -50.0, 215.0),
9695            Vec3::new(0.0, 1.0, 0.0),
9696            60.0,
9697        )
9698        .unwrap();
9699        let curves = intersect_analytic_analytic_in_region(
9700            AnalyticSurface::Cone(&cone),
9701            AnalyticSurface::Cylinder(&cyl),
9702            32,
9703            Some((81.2 / half_angle.sin(), 95.2 / half_angle.sin())),
9704            Some((10.0, 90.0)),
9705            Aabb3 {
9706                min: Point3::new(-59.98, -40.0, 178.0),
9707                max: Point3::new(-47.23, 40.0, 192.0),
9708            },
9709        )
9710        .unwrap();
9711        assert_eq!(curves.len(), 2);
9712        let (sin, cos) = half_angle.sin_cos();
9713        for c in &curves {
9714            let worst = farthest_along(&c.curve, 4000, |p| {
9715                let on_cone = p.x().hypot(p.y()).madd(sin, -(273.2 - p.z()) * cos).abs();
9716                let on_cyl = (p.x().hypot(p.z() - 215.0) - 60.0).abs();
9717                on_cone.max(on_cyl)
9718            });
9719            assert!(worst <= lin, "band: off by {worst:.2e}");
9720        }
9721    }
9722
9723    /// Between the taper pin's two holes, the pin's side and the rod's wall
9724    /// pass closest without meeting. Projections from one to the other
9725    /// settle there, both normals along the gap: with the rod turned 0.9, at
9726    /// (-2.50, -3.35, 9.88), 0.82 off the rod. The march from that seed never
9727    /// came back to it: it ran 1001 points and ended 2.6 from where it began.
9728    /// The seed now moves onto both surfaces by Newton steps before the march,
9729    /// or is dropped where they cannot take it there, and every loop closes
9730    /// on itself.
9731    #[test]
9732    fn a_seed_where_two_walls_pass_closest_starts_no_march() {
9733        let (pin, v_pin, _, rod) = taper_pin_and_rod(false, 0.9);
9734        let (a, b) = (AnalyticSurface::Cylinder(&rod), AnalyticSurface::Cone(&pin));
9735        let stalled = Point3::new(
9736            -2.503_835_657_485_280_5,
9737            -3.349_109_255_073_426,
9738            9.881_016_348_226_973,
9739        );
9740        let off_rod = |p: Point3| section_fit::Carrier::distance(&a, p).unwrap().0;
9741        let off_pin = |p: Point3| section_fit::Carrier::distance(&b, p).unwrap().0;
9742        assert!(off_rod(stalled).abs() > 0.8);
9743        let on = settle_on_section(&a, &b, stalled).unwrap();
9744        let (d_rod, d_pin) = (off_rod(on), off_pin(on));
9745        assert!(
9746            d_rod.abs() < 1e-12 && d_pin.abs() < 1e-12,
9747            "{d_rod:.1e}, {d_pin:.1e}"
9748        );
9749
9750        let curves = marched_sections(
9751            a,
9752            b,
9753            32,
9754            Some((0.0, 20.0)),
9755            Some(v_pin),
9756            Some(TAPER_PIN_REGION),
9757        )
9758        .unwrap();
9759        assert_eq!(curves.len(), 2);
9760        for c in &curves {
9761            let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
9762            assert!((first - last).length() < 1e-9, "{first:?} to {last:?}");
9763            assert!(c.points.len() < 400, "{} points", c.points.len());
9764        }
9765
9766        // Where both normals lie along the gap, no Newton step crosses it.
9767        let ball = SphericalSurface::new(Point3::new(3.0, 0.0, 0.0), 1.0).unwrap();
9768        let post =
9769            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9770                .unwrap();
9771        let gap = Point3::new(1.5, 0.0, 0.0);
9772        assert!(
9773            settle_on_section(
9774                &AnalyticSurface::Sphere(&ball),
9775                &AnalyticSurface::Cylinder(&post),
9776                gap
9777            )
9778            .is_none()
9779        );
9780    }
9781
9782    /// Two rods whose axes cross square, as far apart as their radii add up
9783    /// to, touch at one point and cross nowhere. A seed settles onto that
9784    /// point, where no direction along a section is defined: the march from
9785    /// it wandered up to 1.3e-5 off both rods, and its fit was refused. The
9786    /// seed is now dropped, and no section is traced.
9787    #[test]
9788    fn rods_that_only_touch_trace_no_section() {
9789        let wall =
9790            CylindricalSurface::new(Point3::new(1.1, 1.1, 1.2), Vec3::new(0.0, 0.0, 1.0), 2.55)
9791                .unwrap();
9792        let air =
9793            CylindricalSurface::new(Point3::new(-3.9, 1.1, 4.7), Vec3::new(0.0, 1.0, 0.0), 2.45)
9794                .unwrap();
9795        let (a, b) = (
9796            AnalyticSurface::Cylinder(&wall),
9797            AnalyticSurface::Cylinder(&air),
9798        );
9799        let touch = Point3::new(-1.45, 1.1, 4.7);
9800        assert!(!crosses_at(&a, &b, touch));
9801        let region = Aabb3 {
9802            min: Point3::new(-2.1625, 0.3875, 1.5375),
9803            max: Point3::new(-0.7375, 1.8125, 5.4125),
9804        };
9805        let curves = marched_sections(
9806            a,
9807            b,
9808            32,
9809            Some((1.05, 12.45)),
9810            Some((0.0, 30.9)),
9811            Some(region),
9812        )
9813        .unwrap();
9814        assert!(curves.is_empty(), "{} sections", curves.len());
9815    }
9816
9817    /// The distance from the double cone `cone`, by the ruling on `p`'s side
9818    /// of the axis on `p`'s nappe.
9819    fn off_double_cone(cone: &ConicalSurface, p: Point3) -> f64 {
9820        let w = p - cone.apex();
9821        let h = cone.axis().dot(w);
9822        let rho = (w - cone.axis() * h).length();
9823        let (sin, cos) = cone.half_angle().sin_cos();
9824        rho.madd(sin, -h.abs() * cos).abs()
9825    }
9826
9827    /// Two cones of one axis direction, a unit apart, bounded on their
9828    /// negative nappes between `z = -1` and `z = -1/3`, meet in one loop
9829    /// there (through `(0.125, sqrt(15)/8, -0.5)`). The marcher traces it
9830    /// either way round, and the fit stays on both nappes between its
9831    /// points. Read by the ruling of the positive nappe, the shared point lay
9832    /// 0.707 off the first cone, and no seed settled on the loop.
9833    #[test]
9834    fn negative_nappe_sections_are_marched_on_both_cones() {
9835        let up = Vec3::new(0.0, 0.0, 1.0);
9836        let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
9837            .unwrap();
9838        let narrow = ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, 0.5_f64.atan()).unwrap();
9839        let shared = Point3::new(0.125, 15.0_f64.sqrt() / 8.0, -0.5);
9840        for cone in [&wide, &narrow] {
9841            let (off, _) =
9842                section_fit::Carrier::distance(&AnalyticSurface::Cone(cone), shared).unwrap();
9843            assert!(off.abs() < 1e-12, "{off}");
9844        }
9845        let (r1, r2) = (std::f64::consts::SQRT_2, 5.0_f64.sqrt());
9846        let (v_wide, v_narrow) = ((-r1, -r1 / 3.0), (-r2, -r2 / 3.0));
9847        for wide_first in [true, false] {
9848            let (a, b, va, vb) = if wide_first {
9849                (
9850                    AnalyticSurface::Cone(&wide),
9851                    AnalyticSurface::Cone(&narrow),
9852                    v_wide,
9853                    v_narrow,
9854                )
9855            } else {
9856                (
9857                    AnalyticSurface::Cone(&narrow),
9858                    AnalyticSurface::Cone(&wide),
9859                    v_narrow,
9860                    v_wide,
9861                )
9862            };
9863            let curves = marched_sections(a, b, 32, Some(va), Some(vb), None).unwrap();
9864            assert!(!curves.is_empty(), "wide first {wide_first}: no section");
9865            for c in &curves {
9866                let worst = farthest_along(&c.curve, 4000, |p| {
9867                    off_double_cone(&wide, p).max(off_double_cone(&narrow, p))
9868                });
9869                assert!(worst <= 1e-7, "wide first {wide_first}: off by {worst:.2e}");
9870                let below = farthest_along(&c.curve, 4000, |p| (p.z() + 1.0 / 3.0).max(0.0));
9871                assert!(
9872                    below < 1e-9,
9873                    "wide first {wide_first}: above z = -1/3 by {below:.2e}"
9874                );
9875            }
9876        }
9877    }
9878
9879    /// A 45-degree cone holds its negative ruling from (1, 0, -1) to
9880    /// (4, 0, -4), and so does a rod of radius 1 along it. The bound on the
9881    /// cone reads that ruling as on it, and the fit through its points is
9882    /// the ruling; read by the positive nappe, its factor was negative and
9883    /// no span could be bounded. A span through the apex, where the factor
9884    /// vanishes, has no bound.
9885    #[test]
9886    fn a_fit_along_a_negative_ruling_is_bounded() {
9887        let cone = ConicalSurface::new(
9888            Point3::new(0.0, 0.0, 0.0),
9889            Vec3::new(0.0, 0.0, 1.0),
9890            std::f64::consts::FRAC_PI_4,
9891        )
9892        .unwrap();
9893        let along = Vec3::new(1.0, 0.0, -1.0) * std::f64::consts::FRAC_1_SQRT_2;
9894        let rod = CylindricalSurface::new(Point3::new(0.0, 1.0, 0.0), along, 1.0).unwrap();
9895        let (a, b) = (
9896            AnalyticSurface::Cone(&cone),
9897            AnalyticSurface::Cylinder(&rod),
9898        );
9899        let ruling: Vec<Point3> = (1..=4)
9900            .map(|k| Point3::new(f64::from(k), 0.0, -f64::from(k)))
9901            .collect();
9902        let ctrl = [ruling[0], ruling[1], ruling[2], ruling[3]];
9903        let bound = section_fit::Carrier::bound(&a, &ctrl).unwrap();
9904        assert!(bound < 1e-12, "{bound:.2e}");
9905        let (curve, points) = fit_section(&a, &b, &ruling, 1e-7).unwrap();
9906        assert_eq!(points.len(), 4);
9907        let worst = farthest_along(&curve, 1000, |p| p.y().abs().max((p.x() + p.z()).abs()));
9908        assert!(worst < 1e-12, "{worst:.2e}");
9909        let through_apex = [
9910            Point3::new(-1.0, 0.0, 1.0),
9911            Point3::new(-1.0 / 3.0, 0.0, 1.0 / 3.0),
9912            Point3::new(1.0 / 3.0, 0.0, -1.0 / 3.0),
9913            Point3::new(1.0, 0.0, -1.0),
9914        ];
9915        assert!(section_fit::Carrier::bound(&a, &through_apex).is_none());
9916    }
9917
9918    /// Two rods, `x^2 + y^2 = 1` and `(x - 3)^2 + z^2 = 4`, touch at
9919    /// (1, 0, 0) alone, where a seed near it settles on no crossing. Moved
9920    /// 1e6 along x, a seed settled 3.1e-4 from the touch, where both
9921    /// distances lay below the rounding of the coordinates and the normals
9922    /// 1.5e-4 from parallel, and a march started there; moved 1e12, the
9923    /// spacing of one coordinate let a point one float step from the touch
9924    /// read as a crossing. The marcher now works near the origin, so the
9925    /// rods moved along each axis trace no section, as they do unmoved.
9926    #[test]
9927    fn a_touch_far_from_the_origin_settles_as_one_near_it_does() {
9928        for o in [
9929            Vec3::new(0.0, 0.0, 0.0),
9930            Vec3::new(1e6, 0.0, 0.0),
9931            Vec3::new(1e12, 0.0, 0.0),
9932            Vec3::new(0.0, 1e12, 0.0),
9933            Vec3::new(0.0, 0.0, 1e12),
9934        ] {
9935            let post = CylindricalSurface::new(
9936                Point3::new(0.0, 0.0, 0.0) + o,
9937                Vec3::new(0.0, 0.0, 1.0),
9938                1.0,
9939            )
9940            .unwrap();
9941            let beam = CylindricalSurface::new(
9942                Point3::new(3.0, 0.0, 0.0) + o,
9943                Vec3::new(0.0, 1.0, 0.0),
9944                2.0,
9945            )
9946            .unwrap();
9947            let (a, b) = (
9948                AnalyticSurface::Cylinder(&post),
9949                AnalyticSurface::Cylinder(&beam),
9950            );
9951            if o.length() == 0.0 {
9952                let settled = settle_on_section(&a, &b, Point3::new(1.0, 0.01, 0.01));
9953                assert!(
9954                    settled.is_none_or(|p| !crosses_at(&a, &b, p)),
9955                    "settles on a crossing at {settled:?}"
9956                );
9957            }
9958            let region = Aabb3 {
9959                min: Point3::new(0.5, -0.5, -0.5) + o,
9960                max: Point3::new(1.5, 0.5, 0.5) + o,
9961            };
9962            let curves =
9963                marched_sections(a, b, 32, Some((-1.0, 1.0)), Some((-1.0, 1.0)), Some(region))
9964                    .unwrap();
9965            assert!(curves.is_empty(), "moved {o:?}: {} sections", curves.len());
9966        }
9967    }
9968
9969    /// A cone opening 0.01 or 0.001 either side of its axis, or lying that
9970    /// far off its radial plane, meets a rod on its axis in one circle. The
9971    /// fit through points of that circle is bounded on both surfaces within
9972    /// the linear tolerance: the cone's factor, `|h| cos + rho sin`, keeps a
9973    /// lower bound however slender or flat the cone.
9974    #[test]
9975    fn fits_on_slender_and_flat_cones_are_bounded() {
9976        use std::f64::consts::FRAC_PI_2;
9977        for half in [FRAC_PI_2 - 0.01, FRAC_PI_2 - 0.001, 0.01, 0.001] {
9978            let cone =
9979                ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), half)
9980                    .unwrap();
9981            let v = 10.0;
9982            let (rho, h) = (v * half.cos(), v * half.sin());
9983            let rod =
9984                CylindricalSurface::new(Point3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 1.0), rho)
9985                    .unwrap();
9986            let (a, b) = (
9987                AnalyticSurface::Cone(&cone),
9988                AnalyticSurface::Cylinder(&rod),
9989            );
9990            let circle: Vec<Point3> = (0..=12)
9991                .map(|k| {
9992                    let t = TAU * f64::from(k) / 12.0;
9993                    Point3::new(rho * t.cos(), rho * t.sin(), h)
9994                })
9995                .collect();
9996            let (curve, points) = fit_section(&a, &b, &circle, 1e-7).unwrap();
9997            let worst = farthest_along(&curve, 4000, |p| {
9998                off_double_cone(&cone, p).max((p.x().hypot(p.y()) - rho).abs())
9999            });
10000            assert!(worst <= 1e-7, "half {half}: off by {worst:.2e}");
10001            assert!(points.len() < 2000, "half {half}: {} points", points.len());
10002        }
10003    }
10004
10005    /// The ring of radii 4 and 1.5 and a rod of radius 0.6 along y through
10006    /// (0.5, y, 1), moved 1e6 along each axis, meet in the two loops they
10007    /// meet in unmoved, each within the linear tolerance of both surfaces.
10008    /// Moved 1e9, where the floats' spacing (1.2e-7) leaves no room for the
10009    /// tolerance once a curve is moved back, the traced section is refused
10010    /// before any fit, not dropped; its fit ran 7 passes over 1.4 s first.
10011    #[test]
10012    fn a_section_far_from_the_origin_is_traced_as_near_it() {
10013        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10014        let run = |o: Vec3| {
10015            let torus = ring.translated(o);
10016            let rod = CylindricalSurface::new(
10017                Point3::new(0.5, 0.0, 1.0) + o,
10018                Vec3::new(0.0, 1.0, 0.0),
10019                0.6,
10020            )
10021            .unwrap();
10022            let region = Aabb3 {
10023                min: Point3::new(-0.1, -5.5, 0.4) + o,
10024                max: Point3::new(1.1, 5.5, 1.5) + o,
10025            };
10026            intersect_analytic_analytic_in_region(
10027                AnalyticSurface::Cylinder(&rod),
10028                AnalyticSurface::Torus(&torus),
10029                32,
10030                Some((-10.0, 10.0)),
10031                None,
10032                region,
10033            )
10034        };
10035        for o in [
10036            Vec3::new(0.0, 0.0, 0.0),
10037            Vec3::new(1e6, 0.0, 0.0),
10038            Vec3::new(0.0, 1e6, 0.0),
10039            Vec3::new(0.0, 0.0, 1e6),
10040        ] {
10041            let curves = run(o).unwrap();
10042            assert_eq!(curves.len(), 2, "moved {o:?}");
10043            for c in &curves {
10044                let worst = farthest_along(&c.curve, 4000, |p| {
10045                    let q = p - o;
10046                    let on_torus = ((q.x().hypot(q.y()) - 4.0).hypot(q.z()) - 1.5).abs();
10047                    let on_rod = ((q.x() - 0.5).hypot(q.z() - 1.0) - 0.6).abs();
10048                    on_torus.max(on_rod)
10049                });
10050                assert!(worst <= 1e-7, "moved {o:?}: off by {worst:.2e}");
10051            }
10052        }
10053        for o in [
10054            Vec3::new(1e9, 0.0, 0.0),
10055            Vec3::new(0.0, 1e9, 0.0),
10056            Vec3::new(0.0, 0.0, 1e9),
10057        ] {
10058            assert!(
10059                matches!(run(o), Err(MathError::ConvergenceFailure { iterations: 0 })),
10060                "moved {o:?}: not refused before its fit"
10061            );
10062        }
10063    }
10064
10065    /// A cylinder's frame can sit anywhere along its axis. The rods
10066    /// `x^2 + y^2 = 1` and `(x - 3)^2 + z^2 = 4`, with their frames 1e6 along
10067    /// their axes, touch at (1, 0, 0) alone, as with their frames beside it:
10068    /// a seed near the touch settled 1.55e-4 from it and read as a crossing,
10069    /// and the marcher refused the pair. Now the seed settles on no crossing
10070    /// and no section is traced. The ring and rod of the truth audit, the
10071    /// rod's frame 1e6 along its axis, meet in the loops they meet in with
10072    /// the frame beside them.
10073    #[test]
10074    fn frames_far_along_a_rods_axis_read_as_near_ones() {
10075        let post =
10076            CylindricalSurface::new(Point3::new(0.0, 0.0, -1e6), Vec3::new(0.0, 0.0, 1.0), 1.0)
10077                .unwrap();
10078        let beam =
10079            CylindricalSurface::new(Point3::new(3.0, -1e6, 0.0), Vec3::new(0.0, 1.0, 0.0), 2.0)
10080                .unwrap();
10081        let (a, b) = (
10082            AnalyticSurface::Cylinder(&post),
10083            AnalyticSurface::Cylinder(&beam),
10084        );
10085        let settled = settle_on_section(&a, &b, Point3::new(1.0, 0.01, 0.01));
10086        assert!(
10087            settled.is_none_or(|p| !crosses_at(&a, &b, p)),
10088            "settles on a crossing at {settled:?}"
10089        );
10090        let region = Aabb3 {
10091            min: Point3::new(0.5, -0.5, -0.5),
10092            max: Point3::new(1.5, 0.5, 0.5),
10093        };
10094        let far = Some((1e6 - 1.0, 1e6 + 1.0));
10095        let curves = marched_sections(a, b, 32, far, far, Some(region)).unwrap();
10096        assert!(curves.is_empty(), "{} sections", curves.len());
10097
10098        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10099        let boxes = |frame: f64| {
10100            let rod = CylindricalSurface::new(
10101                Point3::new(0.5, -frame, 1.0),
10102                Vec3::new(0.0, 1.0, 0.0),
10103                0.6,
10104            )
10105            .unwrap();
10106            let region = Aabb3 {
10107                min: Point3::new(-0.1, -5.5, 0.4),
10108                max: Point3::new(1.1, 5.5, 1.5),
10109            };
10110            let curves = intersect_analytic_analytic_in_region(
10111                AnalyticSurface::Cylinder(&rod),
10112                AnalyticSurface::Torus(&ring),
10113                32,
10114                Some((frame - 10.0, frame + 10.0)),
10115                None,
10116                region,
10117            )
10118            .unwrap();
10119            let mut boxes: Vec<Aabb3> = curves
10120                .iter()
10121                .map(|c| {
10122                    let worst = farthest_along(&c.curve, 4000, |p| {
10123                        let on_torus = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
10124                        let on_rod = ((p.x() - 0.5).hypot(p.z() - 1.0) - 0.6).abs();
10125                        on_torus.max(on_rod)
10126                    });
10127                    assert!(worst <= 1e-7, "frame {frame}: off by {worst:.2e}");
10128                    Aabb3::try_from_points(c.points.iter().map(|ip| ip.point)).unwrap()
10129                })
10130                .collect();
10131            boxes.sort_by(|p, q| p.min.y().total_cmp(&q.min.y()));
10132            boxes
10133        };
10134        let (near, far) = (boxes(0.0), boxes(1e6));
10135        assert_eq!(near.len(), 2);
10136        assert_eq!(far.len(), near.len());
10137        for (n, f) in near.iter().zip(&far) {
10138            assert!((n.min - f.min).length() < 1e-6 && (n.max - f.max).length() < 1e-6);
10139        }
10140    }
10141
10142    /// `a + b` as a float and its rounding error.
10143    fn two_sum(a: f64, b: f64) -> (f64, f64) {
10144        let s = a + b;
10145        let back = s - a;
10146        (s, (a - (s - back)) + (b - back))
10147    }
10148
10149    /// `a b` as a float and its rounding error, by Dekker's split.
10150    fn two_prod(a: f64, b: f64) -> (f64, f64) {
10151        let split = |v: f64| {
10152            let c = 134_217_729.0 * v;
10153            let hi = c - (c - v);
10154            (hi, v - hi)
10155        };
10156        let p = a * b;
10157        let ((ah, al), (bh, bl)) = (split(a), split(b));
10158        (p, ((ah * bh - p) + ah * bl + al * bh) + al * bl)
10159    }
10160
10161    /// How far `p` lies from the line through `o` along `a`, in
10162    /// double-length arithmetic, so a far `o` costs no digits of the answer
10163    /// (nor does `a` being a float step from unit length).
10164    fn off_line(o: Point3, a: Vec3, p: Point3) -> f64 {
10165        let w = [
10166            two_sum(p.x(), -o.x()),
10167            two_sum(p.y(), -o.y()),
10168            two_sum(p.z(), -o.z()),
10169        ];
10170        let a = [a.x(), a.y(), a.z()];
10171        // A sum of products `a_i y_i` with each `y_i` double-length.
10172        let dot = |y: &[(f64, f64); 3]| {
10173            let (mut hi, mut lo) = (0.0, 0.0);
10174            for (ai, (yh, yl)) in a.iter().zip(y) {
10175                let (prod, prod_err) = two_prod(*ai, *yh);
10176                let (sum, sum_err) = two_sum(hi, prod);
10177                hi = sum;
10178                lo += sum_err + prod_err + ai * yl;
10179            }
10180            two_sum(hi, lo)
10181        };
10182        let (aw, aw_err) = dot(&w);
10183        let (aa, aa_err) = dot(&a.map(|x| (x, 0.0)));
10184        // `s = aw / aa` to double length: its float, then the remainder
10185        // over `aa`.
10186        let s = aw / aa;
10187        let (sa, sa_err) = two_prod(s, aa);
10188        let rest = ((aw - sa) - sa_err) + aw_err - s * aa_err;
10189        let s_err = rest / aa;
10190        let across = a.iter().zip(w).map(|(ai, (hi, lo))| {
10191            let (prod, prod_err) = two_prod(*ai, s);
10192            let (diff, diff_err) = two_sum(hi, -prod);
10193            diff + (diff_err + lo - prod_err - ai * s_err)
10194        });
10195        across.map(|c| c * c).sum::<f64>().sqrt()
10196    }
10197
10198    /// A rod of radius 0.6 on an axis along (0.3, 0.4, 0.5) through the
10199    /// centre circle of the ring of radii 4 and 1.5 at (4, 0, 0), its frame
10200    /// 1e12 along the axis. Moved to the region by plain sums, such a frame
10201    /// landed 2.1e-5 off the axis, and a fit certified against the moved rod
10202    /// need not lie within 1e-7 of the input one. The frame now lands within
10203    /// 4e-15 of the axis, and both loops lie within 1e-7 of the input rod
10204    /// (measured in double-length arithmetic) and of the ring.
10205    #[test]
10206    fn a_tilted_rod_framed_far_along_its_axis_is_traced_on_it() {
10207        let along = Vec3::new(0.3, 0.4, 0.5);
10208        let through = Point3::new(4.0, 0.0, 0.0);
10209        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10210        let near_rod = CylindricalSurface::new(through, along, 0.6).unwrap();
10211        let axis = near_rod.axis();
10212        let far = through + axis * 1e12;
10213        let rod = CylindricalSurface::new(far, along, 0.6).unwrap();
10214        let anchor = Point3::new(4.0, 0.0, 0.0);
10215        let (moved, dv, error) = Moved::new(&AnalyticSurface::Cylinder(&rod), anchor);
10216        let AnalyticSurface::Cylinder(moved) = moved.surface() else {
10217            unreachable!("a rod moves to a rod");
10218        };
10219        let foot = moved.origin() + (anchor - Point3::new(0.0, 0.0, 0.0));
10220        let off = off_line(rod.origin(), rod.axis(), foot);
10221        assert!(
10222            off <= error && error < 1e-14,
10223            "the frame lies {off:.2e} off the axis"
10224        );
10225        assert!((dv + 1e12).abs() < 1.0, "v moved by {dv}");
10226
10227        let region = Aabb3 {
10228            min: Point3::new(2.0, -2.0, -2.0),
10229            max: Point3::new(6.0, 2.0, 2.0),
10230        };
10231        let sweep = (1e12 - 10.0, 1e12 + 10.0);
10232        let result = marched_sections(
10233            AnalyticSurface::Cylinder(&rod),
10234            AnalyticSurface::Torus(&ring),
10235            32,
10236            Some((-sweep.1, -sweep.0)),
10237            None,
10238            Some(region),
10239        );
10240        let curves = result.unwrap();
10241        assert_eq!(curves.len(), 2);
10242        {
10243            for c in &curves {
10244                let worst = farthest_along(&c.curve, 4000, |p| {
10245                    let on_rod = (off_line(rod.origin(), rod.axis(), p) - 0.6).abs();
10246                    let on_ring = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
10247                    on_rod.max(on_ring)
10248                });
10249                assert!(worst <= 1e-7, "off by {worst:.2e}");
10250            }
10251        }
10252    }
10253
10254    /// Each surface's closed-form second derivative of its distance along a
10255    /// direction matches the distance's central second difference, at points
10256    /// on and near the surface, along and across it.
10257    #[test]
10258    fn each_surface_bends_as_its_distance_does() {
10259        use section_fit::Carrier;
10260        let cyl =
10261            CylindricalSurface::new(Point3::new(0.3, -0.2, 0.5), Vec3::new(0.2, 0.3, 1.0), 0.7)
10262                .unwrap();
10263        let ball = SphericalSurface::new(Point3::new(-0.4, 0.1, 0.2), 1.3).unwrap();
10264        let cone = ConicalSurface::new(Point3::new(0.1, 0.2, -0.3), Vec3::new(-0.3, 0.1, 1.0), 0.6)
10265            .unwrap();
10266        let ring = ToroidalSurface::new(Point3::new(0.2, -0.1, 0.1), 2.0, 0.6).unwrap();
10267        let surfaces = [
10268            AnalyticSurface::Cylinder(&cyl),
10269            AnalyticSurface::Sphere(&ball),
10270            AnalyticSurface::Cone(&cone),
10271            AnalyticSurface::Torus(&ring),
10272        ];
10273        let directions = [
10274            Vec3::new(1.0, 0.0, 0.0),
10275            Vec3::new(0.0, 1.0, 0.0),
10276            Vec3::new(0.0, 0.0, 1.0),
10277            Vec3::new(0.6, -0.48, 0.64),
10278        ];
10279        let (_, _, _, cone_v) = surface_closures(&AnalyticSurface::Cone(&cone));
10280        for (k, s) in surfaces.iter().enumerate() {
10281            let (surf, norm, _, (v0, v1)) = surface_closures(s);
10282            let (v0, v1) = if matches!(s, AnalyticSurface::Cone(_)) {
10283                (cone_v.0.max(0.5), cone_v.1)
10284            } else {
10285                (v0, v1)
10286            };
10287            for (u, v) in [(0.3, 0.25), (1.9, 0.5), (4.4, 0.75)] {
10288                let v = (v1 - v0).madd(v, v0);
10289                for off in [0.0, 0.05, -0.05] {
10290                    let p = surf(u, v) + norm(u, v) * off;
10291                    let f = |q: Point3| s.distance(q).unwrap().0;
10292                    for d in directions {
10293                        let d = d * (1.0 / d.length());
10294                        let h = 1e-4;
10295                        let second = (f(p + d * h) - 2.0 * f(p) + f(p - d * h)) / (h * h);
10296                        let exact = s.bend(p, d).unwrap();
10297                        assert!(
10298                            (second - exact).abs() <= 1e-5 * (1.0 + exact.abs()),
10299                            "surface {k} at {p:?} along {d:?}: {exact} against {second}"
10300                        );
10301                    }
10302                }
10303            }
10304        }
10305    }
10306
10307    /// A cone's distance holds `-|h| cos`, which has no second derivative
10308    /// across the apex's plane. Off the axis on that plane, within the
10309    /// rounding of `h`, no curvature is read, along the axis or across it,
10310    /// so neither a march station nor a search for a touch is built there:
10311    /// both find nothing, and no touch is read. Just off the plane each
10312    /// curvature reads again.
10313    #[test]
10314    fn a_cone_reads_no_curvature_on_its_apex_plane() {
10315        use section_fit::Carrier;
10316        let axis = Vec3::new(0.0, 0.0, 1.0);
10317        let cone = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), axis, 0.7).unwrap();
10318        let rod =
10319            CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
10320                .unwrap();
10321        let (a, b) = (
10322            AnalyticSurface::Cone(&cone),
10323            AnalyticSurface::Cylinder(&rod),
10324        );
10325        let across = Vec3::new(1.0, 0.0, 0.0);
10326        for on in [
10327            Point3::new(2.0, 0.0, 0.0),
10328            Point3::new(2.0, 0.0, 1e-17),
10329            Point3::new(2.0, 0.0, -1e-17),
10330        ] {
10331            assert!(a.distance(on).is_some());
10332            assert!(a.bend(on, axis).is_none(), "{on:?} along the axis");
10333            assert!(a.bend(on, across).is_none(), "{on:?} across");
10334            assert!(station(&a, &b, on, axis).is_none(), "{on:?} station");
10335            assert!(singular_point(&a, &b, on, 1.0).is_none(), "{on:?} touch");
10336        }
10337        for off in [Point3::new(2.0, 0.0, 1e-3), Point3::new(2.0, 0.0, -1e-3)] {
10338            assert!(a.bend(off, axis).is_some(), "{off:?} along the axis");
10339            assert!(a.bend(off, across).is_some(), "{off:?} across");
10340        }
10341    }
10342
10343    /// Upright, turned and moved, and mirrored through a slanted plane.
10344    fn three_poses() -> [crate::mat::Mat4; 3] {
10345        use crate::mat::Mat4;
10346        [
10347            Mat4::identity(),
10348            Mat4::translation(-3.7, 5.5, 14.0) * Mat4::rotation_z(0.7) * Mat4::rotation_x(-0.9),
10349            Mat4::scale(-1.0, 1.0, 1.0) * Mat4::rotation_y(0.4),
10350        ]
10351    }
10352
10353    /// A cone with its apex at the origin and its axis along z, and a rod of
10354    /// radius `r` along x through `(0, 0, z0)`, both moved by `pose`; and
10355    /// the points of their section where the rod's angle about its axis is
10356    /// `k / n` of a turn, for `k` below `n`, each moved by `pose`.
10357    fn posed_cone_and_rod(
10358        pose: &crate::mat::Mat4,
10359        half: f64,
10360        z0: f64,
10361        r: f64,
10362        n: u32,
10363    ) -> (ConicalSurface, CylindricalSurface, Vec<Point3>) {
10364        let o = Point3::new(0.0, 0.0, 0.0);
10365        let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10366        let cone =
10367            ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half).unwrap();
10368        let rod = CylindricalSurface::new(
10369            pose.mul_point(Point3::new(0.0, 0.0, z0)),
10370            along(Vec3::new(1.0, 0.0, 0.0)),
10371            r,
10372        )
10373        .unwrap();
10374        let mut truth = Vec::new();
10375        for k in 0..n {
10376            let phi = TAU * f64::from(k) / f64::from(n);
10377            let (y, z) = (r * phi.sin(), r.madd(-phi.cos(), z0));
10378            let rho = z.abs() / half.tan();
10379            let x2 = rho.madd(rho, -y * y);
10380            if x2 >= 0.0 {
10381                for x in [x2.sqrt(), -x2.sqrt()] {
10382                    truth.push(pose.mul_point(Point3::new(x, y, z)));
10383                }
10384            }
10385        }
10386        (cone, rod, truth)
10387    }
10388
10389    /// A cone lying 0.01 off its radial plane meets a rod of radius 0.05 at
10390    /// height 0.1 in two loops 10 long and 0.1 across, which turn at radius
10391    /// 5e-4 at their ends. A cone opening 0.01 about its axis meets rods
10392    /// across it in loops 0.2 to 0.6 long. The march's steps of up to 1.5
10393    /// passed the turns and left points 2.4e-2 off the rod, and its closure,
10394    /// five steps from the seed, joined a loop's far side: each fit was
10395    /// refused, but for the rod of radius 0.2, whose second loop was lost
10396    /// with no error. The march now follows each loop round once, in every
10397    /// pose and either way round: each fit lies within the linear tolerance
10398    /// of both surfaces, closes, and passes within 1e-5 of every point of
10399    /// the section.
10400    #[test]
10401    fn thin_loops_on_flat_and_slender_cones_are_marched_round() {
10402        use std::f64::consts::FRAC_PI_2;
10403        let lin = Tolerance::new().linear;
10404        let cases = [
10405            (0.01, 0.1, 0.05),
10406            (FRAC_PI_2 - 0.01, 3.0, 0.05),
10407            (FRAC_PI_2 - 0.01, 10.0, 0.05),
10408            (FRAC_PI_2 - 0.01, 10.0, 0.2),
10409        ];
10410        for (half, z0, r) in cases {
10411            for (p, pose) in three_poses().iter().enumerate() {
10412                let (cone, rod, truth) = posed_cone_and_rod(pose, half, z0, r, 360);
10413                for cone_first in [true, false] {
10414                    let label =
10415                        format!("half {half} z0 {z0} r {r} pose {p} cone first {cone_first}");
10416                    let (a, b, va, vb) = if cone_first {
10417                        (
10418                            AnalyticSurface::Cone(&cone),
10419                            AnalyticSurface::Cylinder(&rod),
10420                            (1.0, 20.0),
10421                            (-20.0, 20.0),
10422                        )
10423                    } else {
10424                        (
10425                            AnalyticSurface::Cylinder(&rod),
10426                            AnalyticSurface::Cone(&cone),
10427                            (-20.0, 20.0),
10428                            (1.0, 20.0),
10429                        )
10430                    };
10431                    let result = marched_sections(a, b, 32, Some(va), Some(vb), None);
10432                    assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10433                    let curves = result.unwrap();
10434                    assert_eq!(curves.len(), 2, "{label}: loops");
10435                    let off_rod = |p: Point3| {
10436                        let (w, ax) = (p - rod.origin(), rod.axis());
10437                        ((w - ax * ax.dot(w)).length() - r).abs()
10438                    };
10439                    for c in &curves {
10440                        let worst = farthest_along(&c.curve, 4000, |p| {
10441                            off_double_cone(&cone, p).max(off_rod(p))
10442                        });
10443                        assert!(worst <= lin, "{label}: off by {worst:.2e}");
10444                        let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
10445                        assert!((first - last).length() < 1e-9, "{label}: open");
10446                    }
10447                    for &t in &truth {
10448                        let near = curves
10449                            .iter()
10450                            .map(|c| {
10451                                crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10452                                    .unwrap()
10453                                    .distance
10454                            })
10455                            .fold(f64::INFINITY, f64::min);
10456                        assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10457                    }
10458                }
10459            }
10460        }
10461    }
10462
10463    /// A cone lying 0.001 off its radial plane, its apex at the origin, and
10464    /// a rod of radius 0.05 along x through the apex meet in four curves
10465    /// along the rod, two on each nappe, a nappe's 1e-4 from the other's.
10466    /// With both nappes in the cone's patch, a march step hopped to the other
10467    /// nappe and the fit was refused; with each step kept on its nappe, a
10468    /// seed on one nappe still lay within the estimated gap of a curve
10469    /// marched on the other and started no march, and two of the four curves
10470    /// were lost with no error. A seed now joins a marched curve only on its
10471    /// nappe and where Newton steps from the curve's chord reach it within
10472    /// the linear tolerance.
10473    #[test]
10474    fn sections_on_both_nappes_of_a_flat_cone_are_each_marched() {
10475        let (half, r) = (0.001_f64, 0.05_f64);
10476        let lin = Tolerance::new().linear;
10477        let t2 = half.tan() * half.tan();
10478        for (k, pose) in three_poses().iter().enumerate() {
10479            let o = Point3::new(0.0, 0.0, 0.0);
10480            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10481            let cone =
10482                ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half)
10483                    .unwrap();
10484            let rod =
10485                CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(1.0, 0.0, 0.0)), r)
10486                    .unwrap();
10487            let mut truth = Vec::new();
10488            for j in 0..=90 {
10489                let x = 0.9 * (f64::from(j) / 45.0 - 1.0);
10490                let z = (t2 * x.madd(x, r * r) / (1.0 + t2)).sqrt();
10491                let y = z.madd(-z, r * r).sqrt();
10492                for (sy, sz) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] {
10493                    truth.push(pose.mul_point(Point3::new(x, sy * y, sz * z)));
10494                }
10495            }
10496            let off_rod = |p: Point3| {
10497                let (w, ax) = (p - rod.origin(), rod.axis());
10498                ((w - ax * ax.dot(w)).length() - r).abs()
10499            };
10500            for cone_first in [true, false] {
10501                let label = format!("pose {k} cone first {cone_first}");
10502                let (a, b) = if cone_first {
10503                    (
10504                        AnalyticSurface::Cone(&cone),
10505                        AnalyticSurface::Cylinder(&rod),
10506                    )
10507                } else {
10508                    (
10509                        AnalyticSurface::Cylinder(&rod),
10510                        AnalyticSurface::Cone(&cone),
10511                    )
10512                };
10513                let result = marched_sections(a, b, 32, Some((-1.0, 1.0)), Some((-1.0, 1.0)), None);
10514                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10515                let curves = result.unwrap();
10516                assert_eq!(curves.len(), 4, "{label}: curves");
10517                for c in &curves {
10518                    let worst = farthest_along(&c.curve, 4000, |p| {
10519                        off_double_cone(&cone, p).max(off_rod(p))
10520                    });
10521                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
10522                }
10523                for &t in &truth {
10524                    let near = curves
10525                        .iter()
10526                        .map(|c| {
10527                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10528                                .unwrap()
10529                                .distance
10530                        })
10531                        .fold(f64::INFINITY, f64::min);
10532                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10533                }
10534            }
10535        }
10536    }
10537
10538    /// A cone lying 2e-6 off its radial plane, its apex at the origin, and a
10539    /// rod of radius 0.1 along x through the apex cross at a shallow angle,
10540    /// 2e-6, in a curve whose two sides along the rod meet near
10541    /// (50000, 0, 0.1), where it turns at a radius of about 2e-7. The march
10542    /// cannot step round that turn and stops there, the normals 2e-6 from
10543    /// parallel but no point near where they are parallel: each march ended
10544    /// there with a lone point, which was dropped, and the section was lost
10545    /// with no error. The march now refuses it, or traces all of it.
10546    #[test]
10547    fn a_shallow_crossing_too_tight_to_march_is_refused_not_dropped() {
10548        let (half, r) = (2e-6_f64, 0.1_f64);
10549        let t2 = half.tan() * half.tan();
10550        for (k, pose) in three_poses().iter().enumerate() {
10551            let o = Point3::new(0.0, 0.0, 0.0);
10552            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10553            let cone =
10554                ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half)
10555                    .unwrap();
10556            let rod =
10557                CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(1.0, 0.0, 0.0)), r)
10558                    .unwrap();
10559            let mut truth = Vec::new();
10560            for j in 0..=100 {
10561                let x = 40_000.0 + 99.9 * f64::from(j);
10562                let z = (t2 * x.madd(x, r * r) / (1.0 + t2)).sqrt();
10563                if z < r {
10564                    let y = z.madd(-z, r * r).sqrt();
10565                    for sy in [1.0, -1.0] {
10566                        truth.push(pose.mul_point(Point3::new(x, sy * y, z)));
10567                    }
10568                }
10569            }
10570            for cone_first in [true, false] {
10571                let label = format!("pose {k} cone first {cone_first}");
10572                let (a, b) = if cone_first {
10573                    (
10574                        AnalyticSurface::Cone(&cone),
10575                        AnalyticSurface::Cylinder(&rod),
10576                    )
10577                } else {
10578                    (
10579                        AnalyticSurface::Cylinder(&rod),
10580                        AnalyticSurface::Cone(&cone),
10581                    )
10582                };
10583                let range = Some((40_000.0, 60_000.0));
10584                let Ok(curves) = marched_sections(a, b, 32, range, range, None) else {
10585                    continue;
10586                };
10587                for &t in &truth {
10588                    let near = curves
10589                        .iter()
10590                        .map(|c| {
10591                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10592                                .unwrap()
10593                                .distance
10594                        })
10595                        .fold(f64::INFINITY, f64::min);
10596                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10597                }
10598            }
10599        }
10600    }
10601
10602    /// A ball of radius 2 at the origin and a rod of radius 1 along z
10603    /// through (1, 0, 0) touch at (2, 0, 0), where their section, two lobes,
10604    /// crosses itself. The march steps through that node, where its steps
10605    /// grow faster than the gap to the other lobe shrinks; a curve that
10606    /// stops instead stops on the node. Either way the curves cover both
10607    /// lobes, in every pose and either way round.
10608    #[test]
10609    fn a_section_that_crosses_itself_is_traced_through_the_node() {
10610        let lin = Tolerance::new().linear;
10611        for (k, pose) in three_poses().iter().enumerate() {
10612            let o = Point3::new(0.0, 0.0, 0.0);
10613            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10614            let ball = SphericalSurface::new(pose.mul_point(o), 2.0).unwrap();
10615            let rod = CylindricalSurface::new(
10616                pose.mul_point(Point3::new(1.0, 0.0, 0.0)),
10617                along(Vec3::new(0.0, 0.0, 1.0)),
10618                1.0,
10619            )
10620            .unwrap();
10621            let node = pose.mul_point(Point3::new(2.0, 0.0, 0.0));
10622            let mut truth = Vec::new();
10623            for j in 1..360 {
10624                let t = TAU * f64::from(j) / 360.0;
10625                let z = 2.0 * (0.5 * t).sin().abs();
10626                for sz in [1.0, -1.0] {
10627                    truth.push(pose.mul_point(Point3::new(1.0 + t.cos(), t.sin(), sz * z)));
10628                }
10629            }
10630            let off_ball = |p: Point3| ((p - pose.mul_point(o)).length() - 2.0).abs();
10631            let off_rod = |p: Point3| {
10632                let (w, ax) = (p - rod.origin(), rod.axis());
10633                ((w - ax * ax.dot(w)).length() - 1.0).abs()
10634            };
10635            for ball_first in [true, false] {
10636                let label = format!("pose {k} ball first {ball_first}");
10637                let (a, b, va, vb) = if ball_first {
10638                    (
10639                        AnalyticSurface::Sphere(&ball),
10640                        AnalyticSurface::Cylinder(&rod),
10641                        None,
10642                        Some((-3.0, 3.0)),
10643                    )
10644                } else {
10645                    (
10646                        AnalyticSurface::Cylinder(&rod),
10647                        AnalyticSurface::Sphere(&ball),
10648                        Some((-3.0, 3.0)),
10649                        None,
10650                    )
10651                };
10652                let result = marched_sections(a, b, 32, va, vb, None);
10653                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10654                let curves = result.unwrap();
10655                assert!(!curves.is_empty(), "{label}: no section");
10656                for c in &curves {
10657                    let worst = farthest_along(&c.curve, 4000, |p| off_ball(p).max(off_rod(p)));
10658                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
10659                    let (t0, t1) = c.curve.domain();
10660                    let (first, last) = (c.curve.evaluate(t0), c.curve.evaluate(t1));
10661                    if (first - last).length() > lin {
10662                        for end in [first, last] {
10663                            let miss = (end - node).length();
10664                            assert!(miss <= lin, "{label}: an end lies {miss:.1e} from the node");
10665                        }
10666                    }
10667                }
10668                for &t in &truth {
10669                    let near = curves
10670                        .iter()
10671                        .map(|c| {
10672                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10673                                .unwrap()
10674                                .distance
10675                        })
10676                        .fold(f64::INFINITY, f64::min);
10677                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10678                }
10679            }
10680        }
10681    }
10682
10683    /// A rod of radius 3 along z up to z = 30 and the ring of radii 20 and 3
10684    /// about the y axis through (20, 0, 30), a leg and the bend on its top,
10685    /// touch along the circle z = 30 of the rod, and cross below it in a
10686    /// curve that runs from (0, 3, 30) round through (3, 0, 14.5) to
10687    /// (0, -3, 30): there the touch is of higher order, and the march stops
10688    /// short of it. The curve ends where Gauss-Newton steps find both
10689    /// surfaces passing with their normals parallel to rounding, within
10690    /// 1e-5 of the touch, which rounding leaves no closer to fix, in every
10691    /// pose and either way round.
10692    #[test]
10693    fn a_marched_branch_that_runs_into_a_touch_ends_on_it() {
10694        let lin = Tolerance::new().linear;
10695        for (k, pose) in three_poses().iter().enumerate() {
10696            let o = Point3::new(0.0, 0.0, 0.0);
10697            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10698            let leg =
10699                CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), 3.0)
10700                    .unwrap();
10701            let bend = ToroidalSurface::with_axis(
10702                pose.mul_point(Point3::new(20.0, 0.0, 30.0)),
10703                20.0,
10704                3.0,
10705                along(Vec3::new(0.0, 1.0, 0.0)),
10706            )
10707            .unwrap();
10708            let touches = [
10709                pose.mul_point(Point3::new(0.0, 3.0, 30.0)),
10710                pose.mul_point(Point3::new(0.0, -3.0, 30.0)),
10711            ];
10712            let mut truth = Vec::new();
10713            for j in 1..=120 {
10714                let x = 3.0 * f64::from(j) / 120.0;
10715                let z = 30.0 - (80.0 * x).sqrt();
10716                let y = x.madd(-x, 9.0).max(0.0).sqrt();
10717                for sy in [1.0, -1.0] {
10718                    truth.push(pose.mul_point(Point3::new(x, sy * y, z)));
10719                }
10720            }
10721            let back = pose.inverse().unwrap();
10722            let off_leg = |p: Point3| {
10723                let (w, ax) = (p - leg.origin(), leg.axis());
10724                ((w - ax * ax.dot(w)).length() - 3.0).abs()
10725            };
10726            let off_bend = |p: Point3| {
10727                let q = back.mul_point(p);
10728                (((q.x() - 20.0).hypot(q.z() - 30.0) - 20.0).hypot(q.y()) - 3.0).abs()
10729            };
10730            for leg_first in [true, false] {
10731                let label = format!("pose {k} leg first {leg_first}");
10732                let (a, b, va, vb) = if leg_first {
10733                    (
10734                        AnalyticSurface::Cylinder(&leg),
10735                        AnalyticSurface::Torus(&bend),
10736                        Some((0.0, 30.0)),
10737                        None,
10738                    )
10739                } else {
10740                    (
10741                        AnalyticSurface::Torus(&bend),
10742                        AnalyticSurface::Cylinder(&leg),
10743                        None,
10744                        Some((0.0, 30.0)),
10745                    )
10746                };
10747                let result = marched_sections(a, b, 32, va, vb, None);
10748                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10749                let curves = result.unwrap();
10750                assert_eq!(curves.len(), 1, "{label}: curves");
10751                let c = &curves[0];
10752                let worst = farthest_along(&c.curve, 4000, |p| off_leg(p).max(off_bend(p)));
10753                assert!(worst <= lin, "{label}: off by {worst:.2e}");
10754                let (t0, t1) = c.curve.domain();
10755                for end in [c.curve.evaluate(t0), c.curve.evaluate(t1)] {
10756                    let miss = touches
10757                        .iter()
10758                        .map(|&t| (end - t).length())
10759                        .fold(f64::INFINITY, f64::min);
10760                    assert!(
10761                        miss <= 1e-5,
10762                        "{label}: an end lies {miss:.1e} from the touch"
10763                    );
10764                }
10765                for &t in &truth {
10766                    let near = crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10767                        .unwrap()
10768                        .distance;
10769                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10770                }
10771            }
10772        }
10773    }
10774
10775    /// A cone opening a quarter turn about z, its apex at the origin, and a
10776    /// ball of radius 0.1 about the apex meet in two circles, one on each
10777    /// nappe. With the cone's patch from v = -0.5 to 31.5 in a grid of 32,
10778    /// the only cells near the ball have their middles on the apex, the
10779    /// ball's centre, where the ball's distance has no gradient: they were
10780    /// dropped as holding no section, no cell of the cone was kept, and the
10781    /// pair traced nothing. A cell whose distance cannot be read may hold the
10782    /// section and is kept, so the ball's cells near it are read too.
10783    #[test]
10784    fn cells_centred_on_a_balls_centre_are_kept() {
10785        use std::f64::consts::FRAC_PI_4;
10786        let lin = Tolerance::new().linear;
10787        let (radius, h) = (0.1_f64, 0.1 * FRAC_PI_4.sin());
10788        let rho = 0.1 * FRAC_PI_4.cos();
10789        for (k, pose) in three_poses().iter().enumerate() {
10790            let o = Point3::new(0.0, 0.0, 0.0);
10791            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10792            let cone = ConicalSurface::new(
10793                pose.mul_point(o),
10794                along(Vec3::new(0.0, 0.0, 1.0)),
10795                FRAC_PI_4,
10796            )
10797            .unwrap();
10798            let ball = SphericalSurface::new(pose.mul_point(o), radius).unwrap();
10799            let mut truth = Vec::new();
10800            for j in 0..72 {
10801                let t = TAU * f64::from(j) / 72.0;
10802                for z in [h, -h] {
10803                    truth.push(pose.mul_point(Point3::new(rho * t.cos(), rho * t.sin(), z)));
10804                }
10805            }
10806            let off_ball = |p: Point3| ((p - pose.mul_point(o)).length() - radius).abs();
10807            for cone_first in [true, false] {
10808                let label = format!("pose {k} cone first {cone_first}");
10809                let (a, b, va, vb) = if cone_first {
10810                    (
10811                        AnalyticSurface::Cone(&cone),
10812                        AnalyticSurface::Sphere(&ball),
10813                        Some((-0.5, 31.5)),
10814                        None,
10815                    )
10816                } else {
10817                    (
10818                        AnalyticSurface::Sphere(&ball),
10819                        AnalyticSurface::Cone(&cone),
10820                        None,
10821                        Some((-0.5, 31.5)),
10822                    )
10823                };
10824                let result = marched_sections(a, b, 32, va, vb, None);
10825                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10826                let curves = result.unwrap();
10827                assert_eq!(curves.len(), 2, "{label}: circles");
10828                for c in &curves {
10829                    let worst = farthest_along(&c.curve, 4000, |p| {
10830                        off_double_cone(&cone, p).max(off_ball(p))
10831                    });
10832                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
10833                    let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
10834                    assert!((first - last).length() < 1e-9, "{label}: open");
10835                }
10836                for &t in &truth {
10837                    let near = curves
10838                        .iter()
10839                        .map(|c| {
10840                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10841                                .unwrap()
10842                                .distance
10843                        })
10844                        .fold(f64::INFINITY, f64::min);
10845                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10846                }
10847            }
10848        }
10849    }
10850
10851    /// A cone lying 1e-14 off its radial plane, its apex at the origin, and a
10852    /// rod of radius 1 along z through (3, 0, 0) cross square to each other
10853    /// in a circle. Every point of the cone lies within 64 float steps of its
10854    /// apex's plane, where its curvature was not read: each seed on the
10855    /// crossing found no station and was dropped, and the pair traced
10856    /// nothing with no error. A seed on a crossing whose curvature cannot be
10857    /// read now refuses the section. The pair refuses or traces the circle,
10858    /// in three poses and either way round, and never returns empty.
10859    #[test]
10860    fn a_crossing_on_a_nearly_flat_cone_is_traced_or_refused() {
10861        let lin = Tolerance::new().linear;
10862        for (k, pose) in three_poses().iter().enumerate() {
10863            let o = Point3::new(0.0, 0.0, 0.0);
10864            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10865            let cone =
10866                ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), 1e-14)
10867                    .unwrap();
10868            let rod = CylindricalSurface::new(
10869                pose.mul_point(Point3::new(3.0, 0.0, 0.0)),
10870                along(Vec3::new(0.0, 0.0, 1.0)),
10871                1.0,
10872            )
10873            .unwrap();
10874            let truth: Vec<Point3> = (0..72)
10875                .map(|j| {
10876                    let t = TAU * f64::from(j) / 72.0;
10877                    let (x, y) = (3.0 + t.cos(), t.sin());
10878                    pose.mul_point(Point3::new(x, y, 1e-14_f64.tan() * x.hypot(y)))
10879                })
10880                .collect();
10881            let off_rod = |p: Point3| {
10882                let (w, ax) = (p - rod.origin(), rod.axis());
10883                ((w - ax * ax.dot(w)).length() - 1.0).abs()
10884            };
10885            for cone_first in [true, false] {
10886                let label = format!("pose {k} cone first {cone_first}");
10887                let (a, b, va, vb) = if cone_first {
10888                    (
10889                        AnalyticSurface::Cone(&cone),
10890                        AnalyticSurface::Cylinder(&rod),
10891                        Some((1.0, 5.0)),
10892                        Some((-1.0, 1.0)),
10893                    )
10894                } else {
10895                    (
10896                        AnalyticSurface::Cylinder(&rod),
10897                        AnalyticSurface::Cone(&cone),
10898                        Some((-1.0, 1.0)),
10899                        Some((1.0, 5.0)),
10900                    )
10901                };
10902                let Ok(curves) = marched_sections(a, b, 32, va, vb, None) else {
10903                    continue;
10904                };
10905                assert!(!curves.is_empty(), "{label}: no section and no refusal");
10906                for c in &curves {
10907                    let worst = farthest_along(&c.curve, 4000, |p| {
10908                        off_double_cone(&cone, p).max(off_rod(p))
10909                    });
10910                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
10911                }
10912                for &t in &truth {
10913                    let near = curves
10914                        .iter()
10915                        .map(|c| {
10916                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10917                                .unwrap()
10918                                .distance
10919                        })
10920                        .fold(f64::INFINITY, f64::min);
10921                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10922                }
10923            }
10924        }
10925    }
10926
10927    /// A rod of radius 0.6 runs along x over the top of the ring of radii 4
10928    /// and 1.5, its axis 0.007 inside the tube's top circle, its underside
10929    /// 8e-6 below the tube's top. Along the rod the tube's top rises to two
10930    /// crests 0.47 apart, where the rod dips into it in two loops about 0.17
10931    /// long and 0.005 wide. Each loop is smaller than a cell of either patch,
10932    /// and both lie in about one cell of the rod's. A cell's seed settles on
10933    /// one loop: one loop was lost with no error. The cells are now cut until
10934    /// each part of the section is proved to run through cells that a marched
10935    /// point or a seed reaches. Both loops are traced, in three poses and
10936    /// either way round, within the linear tolerance of both surfaces. Where
10937    /// the two cross at an angle whose sine is `s`, a fit within the
10938    /// tolerance of both can lie twice the tolerance over `s` off the
10939    /// section, up to 3e-3 at the loops' ends, where `s` is 7e-5: every point
10940    /// of the section lies within twice that, or 1e-5, of a curve.
10941    #[test]
10942    fn two_loops_in_one_cell_of_each_patch_are_both_traced() {
10943        let lin = Tolerance::new().linear;
10944        let turn = crate::mat::Mat4::rotation_z(0.75 * TAU / 32.0);
10945        let (delta, depth) = (0.007_f64, 8e-6_f64);
10946        let (y0, z0) = (4.0 - delta, 2.1 - depth);
10947        for (k, pose) in three_poses().iter().enumerate() {
10948            let pose = *pose * turn;
10949            let o = Point3::new(0.0, 0.0, 0.0);
10950            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10951            let centre = pose.mul_point(o);
10952            let up = along(Vec3::new(0.0, 0.0, 1.0));
10953            let ring = ToroidalSurface::with_axis(centre, 4.0, 1.5, up).unwrap();
10954            let start = pose.mul_point(Point3::new(0.0, y0, z0));
10955            let dir = along(Vec3::new(1.0, 0.0, 0.0));
10956            let rod = CylindricalSurface::new(start, dir, 0.6).unwrap();
10957            let ring_normal = |p: Point3| {
10958                let w = p - centre;
10959                let across = w - up * up.dot(w);
10960                let tube = centre + across * (4.0 / across.length());
10961                (p - tube) * (1.0 / (p - tube).length())
10962            };
10963            let rod_normal = |p: Point3| {
10964                let w = p - start;
10965                let across = w - dir * dir.dot(w);
10966                across * (1.0 / across.length())
10967            };
10968            let off_ring = |p: Point3| {
10969                let w = p - centre;
10970                let h = up.dot(w);
10971                ((w - up * h).length() - 4.0).hypot(h) - 1.5
10972            };
10973            let off_rod = |p: Point3| {
10974                let w = p - start;
10975                ((w - dir * dir.dot(w)).length() - 0.6).abs()
10976            };
10977            // Each ruling of the rod meets the ring where a quartic along it
10978            // vanishes.
10979            let mut truth = Vec::new();
10980            for j in -300..=300 {
10981                let phi = f64::from(j) * 1e-4;
10982                let from =
10983                    pose.mul_point(Point3::new(0.0, y0 + 0.6 * phi.sin(), z0 - 0.6 * phi.cos()));
10984                for t in intersect_line_torus(&ring, from, dir) {
10985                    if t.abs() < 2.0 {
10986                        truth.push(from + dir * t);
10987                    }
10988                }
10989            }
10990            assert!(truth.len() > 100, "pose {k}: {} points", truth.len());
10991            for rod_first in [true, false] {
10992                let label = format!("pose {k} rod first {rod_first}");
10993                let along_rod = Some((-9.6875, 10.3125));
10994                let result = if rod_first {
10995                    marched_sections(
10996                        AnalyticSurface::Cylinder(&rod),
10997                        AnalyticSurface::Torus(&ring),
10998                        32,
10999                        along_rod,
11000                        None,
11001                        None,
11002                    )
11003                } else {
11004                    marched_sections(
11005                        AnalyticSurface::Torus(&ring),
11006                        AnalyticSurface::Cylinder(&rod),
11007                        32,
11008                        None,
11009                        along_rod,
11010                        None,
11011                    )
11012                };
11013                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
11014                let curves = result.unwrap();
11015                assert_eq!(curves.len(), 2, "{label}: loops");
11016                for c in &curves {
11017                    let worst =
11018                        farthest_along(&c.curve, 4000, |p| off_ring(p).abs().max(off_rod(p)));
11019                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
11020                }
11021                for &t in &truth {
11022                    let sin = ring_normal(t).cross(rod_normal(t)).length();
11023                    let bound = (4.0 * lin / sin).max(1e-5);
11024                    let near = curves
11025                        .iter()
11026                        .map(|c| {
11027                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
11028                                .unwrap()
11029                                .distance
11030                        })
11031                        .fold(f64::INFINITY, f64::min);
11032                    assert!(
11033                        near <= bound,
11034                        "{label}: {t:?} lies {near:.1e} off, past {bound:.1e}"
11035                    );
11036                }
11037            }
11038        }
11039    }
11040}