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};
25
26/// Exact curve type resulting from plane-analytic surface intersection.
27#[derive(Debug, Clone)]
28pub enum ExactIntersectionCurve {
29    /// A circle (plane perpendicular to axis of cylinder/cone/sphere).
30    Circle(Circle3D),
31    /// An ellipse (plane oblique to cylinder/cone axis).
32    Ellipse(Ellipse3D),
33    /// Fallback to sampled point chain (torus, degenerate cases).
34    Points(Vec<Point3>),
35}
36
37/// A plane's section of an analytic surface, from [`exact_plane_section`].
38#[derive(Debug, Clone)]
39#[non_exhaustive]
40pub enum PlaneSection {
41    /// A circle.
42    Circle(Circle3D),
43    /// An ellipse.
44    Ellipse(Ellipse3D),
45    /// A straight section: a cylinder's ruling, running both ways from the
46    /// line's origin, or with `ray` a cone's ruling, running from the apex at
47    /// the line's origin along its direction only.
48    Line {
49        /// The ruling's line.
50        line: Line3D,
51        /// Whether the section runs one way only, from the line's origin.
52        ray: bool,
53    },
54    /// The one point where the plane touches the surface.
55    Point(Point3),
56    /// A sampled chain of points along the section.
57    Points(Vec<Point3>),
58    /// A cone's parabola.
59    Parabola(Parabola3D),
60    /// The branch of a cone's hyperbola on the cone's one nappe, which the
61    /// hyperbola's `u_axis` points to from its centre.
62    Hyperbola(Hyperbola3D),
63}
64
65impl From<ExactIntersectionCurve> for PlaneSection {
66    fn from(curve: ExactIntersectionCurve) -> Self {
67        match curve {
68            ExactIntersectionCurve::Circle(circle) => Self::Circle(circle),
69            ExactIntersectionCurve::Ellipse(ellipse) => Self::Ellipse(ellipse),
70            ExactIntersectionCurve::Points(points) => Self::Points(points),
71        }
72    }
73}
74
75/// A plane's exact section of an analytic surface.
76///
77/// It includes the sections [`exact_plane_analytic`] has no curve for: the
78/// rulings a plane along a cylinder's axis or through a cone's apex cuts,
79/// and the point where a plane touches a sphere or meets a cone at its apex
80/// alone. A cone's parabola and hyperbola come back as curves, which
81/// [`exact_plane_analytic`] samples into points, except in a band about the
82/// parabola where neither form keeps its digits.
83///
84/// The plane is `dot(normal, p) = d`, with `normal` of unit length.
85///
86/// # Errors
87///
88/// Returns an error if a section's curve cannot be built.
89pub fn exact_plane_section(
90    surface: AnalyticSurface<'_>,
91    normal: Vec3,
92    d: f64,
93) -> Result<Vec<PlaneSection>, MathError> {
94    match surface {
95        AnalyticSurface::Cylinder(cyl) if normal.dot(cyl.axis()).abs() < 1e-10 => {
96            return plane_cylinder_rulings(cyl, normal, d);
97        }
98        AnalyticSurface::Cone(cone) if plane_holds_apex(cone, normal, d) => {
99            return plane_cone_apex_rulings(cone, normal);
100        }
101        AnalyticSurface::Cone(cone) => {
102            if let Some(open) = plane_cone_open_section(cone, normal, d)? {
103                return Ok(open);
104            }
105        }
106        AnalyticSurface::Sphere(sphere) => {
107            let h = dot_np(normal, sphere.center()) - d;
108            let r = sphere.radius();
109            if (r - h.abs()).abs() <= TOUCH * r {
110                return Ok(vec![PlaneSection::Point(Point3::new(
111                    h.madd(-normal.x(), sphere.center().x()),
112                    h.madd(-normal.y(), sphere.center().y()),
113                    h.madd(-normal.z(), sphere.center().z()),
114                ))]);
115            }
116        }
117        AnalyticSurface::Cylinder(_) | AnalyticSurface::Torus(_) => {}
118    }
119    Ok(exact_plane_analytic(surface, normal, d)?
120        .into_iter()
121        .map(PlaneSection::from)
122        .collect())
123}
124
125/// How far a cone section's `e² − 1` (its eccentricity squared, less one)
126/// may sit from zero for the section to be read as a parabola.
127const PARABOLIC: f64 = 1e-12;
128
129/// Where a cone's hyperbola starts, in `e² − 1`: its centre lies the
130/// plane's offset over the conic coefficient away, and nearer zero its
131/// vertex loses digits.
132const HYPERBOLIC: f64 = 1e-6;
133
134/// A plane's parabola or hyperbola section of a cone, on the cone's one
135/// nappe, worked in the frame of [`exact_plane_cone`]. `None` for a circle
136/// or an ellipse, in the band between [`PARABOLIC`] and [`HYPERBOLIC`], and
137/// for a curve whose points do not hold to the cone (a cone so narrow or so
138/// flat that the formulas lose their digits), all of which go to the
139/// sampled section.
140#[allow(clippy::many_single_char_names)]
141fn plane_cone_open_section(
142    cone: &ConicalSurface,
143    normal: Vec3,
144    d: f64,
145) -> Result<Option<Vec<PlaneSection>>, MathError> {
146    let axis = cone.axis();
147    let c = normal.dot(axis);
148    let p2 = c.madd(-c, 1.0).max(0.0);
149    let p = p2.sqrt();
150    let rise = cone.half_angle().sin();
151    let k = rise * rise;
152    let a_coeff = p2 - k;
153    let eccentric = a_coeff / k;
154    let m = axis - normal * c;
155    let m_len = m.length();
156    if m_len < 1e-12 || eccentric < -PARABOLIC || (eccentric > PARABOLIC && eccentric <= HYPERBOLIC)
157    {
158        return Ok(None);
159    }
160    let e1 = m * (1.0 / m_len);
161    let e2 = normal.cross(e1);
162    let apex = cone.apex();
163    let e = d - dot_np(normal, apex);
164    let origin = apex + normal * e;
165    // A point `s` along `e1` from `origin` lies `e·c + s·p` up the axis from
166    // the apex, which the real nappe keeps non-negative.
167    let real = |s: f64| e.madd(c, s * p) >= 0.0;
168    // On the one nappe a point's height up the axis is `rise` times its
169    // distance from the apex.
170    let holds = |q: Point3| {
171        let w = q - apex;
172        let reach = w.length();
173        reach.is_finite() && (w.dot(axis) - rise * reach).abs() <= 1e-9 * (1.0 + reach)
174    };
175    if eccentric <= PARABOLIC {
176        // k t² = 2ecp s + e²(c² − k): the vertex at t = 0, opening along e1
177        // with the sign of ecp, `1 / 4f = k / 2|ecp|`.
178        let ecp = e * c * p;
179        let vertex_s = -e * (c * c - k) / (2.0 * c * p);
180        let focal = ecp.abs() / (2.0 * k);
181        if !(vertex_s.is_finite() && focal > 0.0 && focal.is_finite()) {
182            return Ok(None);
183        }
184        if !real(vertex_s) {
185            return Ok(Some(Vec::new()));
186        }
187        let parabola = Parabola3D::with_axes(origin + e1 * vertex_s, e1 * ecp.signum(), e2, focal)?;
188        if ![0.0, focal, -focal]
189            .iter()
190            .all(|&t| holds(parabola.evaluate(t)))
191        {
192            return Ok(None);
193        }
194        return Ok(Some(vec![PlaneSection::Parabola(parabola)]));
195    }
196    // A(s − s_c)² − k t² = e²k(1 − k)/A: the branches' vertices lie a real
197    // semi-axis either side of the centre, one on each nappe.
198    let centre_s = -e * c * p / a_coeff;
199    let rhs = e * e * k * (1.0 - k) / a_coeff;
200    let (real_axis, imaginary_axis) = ((rhs / a_coeff).sqrt(), (rhs / k).sqrt());
201    if !(real_axis > 0.0 && imaginary_axis > 0.0 && centre_s.is_finite()) {
202        return Ok(None);
203    }
204    let toward = if real(centre_s + real_axis) { e1 } else { -e1 };
205    let hyperbola = Hyperbola3D::with_axes(
206        origin + e1 * centre_s,
207        real_axis,
208        imaginary_axis,
209        toward,
210        e2,
211    )?;
212    if ![0.0, 1.0, -1.0]
213        .iter()
214        .all(|&t| holds(hyperbola.evaluate(t)))
215    {
216        return Ok(None);
217    }
218    Ok(Some(vec![PlaneSection::Hyperbola(hyperbola)]))
219}
220
221/// Rounding band, relative, within which a plane counts as touching a
222/// surface or passing through a cone's apex.
223const TOUCH: f64 = 4.0 * f64::EPSILON;
224
225/// The rulings a plane along a cylinder's axis cuts from it: two lines, the
226/// one it touches along, or none.
227fn plane_cylinder_rulings(
228    cyl: &CylindricalSurface,
229    normal: Vec3,
230    d: f64,
231) -> Result<Vec<PlaneSection>, MathError> {
232    // n·P(u, 0) = n·O + r·(a cos u + b sin u): the plane holds the ruling at
233    // u where cos(u − φ) = (d − n·O) / (r·√(a² + b²)).
234    let (a, b) = (normal.dot(cyl.x_axis()), normal.dot(cyl.y_axis()));
235    let amp = a.hypot(b);
236    if amp < 1e-12 {
237        return Ok(vec![]);
238    }
239    let ratio = (d - dot_np(normal, cyl.origin())) / (cyl.radius() * amp);
240    if ratio.abs() > 1.0 + TOUCH {
241        return Ok(vec![]);
242    }
243    let phi = b.atan2(a);
244    let spread = ratio.clamp(-1.0, 1.0).acos();
245    let at = if ratio.abs() >= 1.0 - TOUCH {
246        vec![phi + spread]
247    } else {
248        vec![phi + spread, phi - spread]
249    };
250    at.into_iter()
251        .map(|u| {
252            Ok(PlaneSection::Line {
253                line: Line3D::new(cyl.evaluate(u, 0.0), cyl.axis())?,
254                ray: false,
255            })
256        })
257        .collect()
258}
259
260/// Whether a plane passes through a cone's apex, but for rounding.
261fn plane_holds_apex(cone: &ConicalSurface, normal: Vec3, d: f64) -> bool {
262    let apex = cone.apex() - Point3::new(0.0, 0.0, 0.0);
263    (normal.dot(apex) - d).abs() <= TOUCH * (1.0 + apex.length() + d.abs())
264}
265
266/// The rulings a plane through a cone's apex cuts from its nappe, as rays
267/// from the apex: two, the one it touches along, or none, when the plane
268/// meets the cone at the apex alone.
269fn plane_cone_apex_rulings(
270    cone: &ConicalSurface,
271    normal: Vec3,
272) -> Result<Vec<PlaneSection>, MathError> {
273    // g(u) = cos a·(cos u·X + sin u·Y) + sin a·axis, so n·g(u) = 0 reads
274    // A cos u + B sin u = −C.
275    let (sin_a, cos_a) = cone.half_angle().sin_cos();
276    let a = cos_a * normal.dot(cone.x_axis());
277    let b = cos_a * normal.dot(cone.y_axis());
278    let c = sin_a * normal.dot(cone.axis());
279    let amp = a.hypot(b);
280    let apex = cone.apex();
281    if amp < 1e-12 * c.abs().max(1.0) {
282        return Ok(vec![PlaneSection::Point(apex)]);
283    }
284    let ratio = -c / amp;
285    if ratio.abs() > 1.0 + TOUCH {
286        return Ok(vec![PlaneSection::Point(apex)]);
287    }
288    let phi = b.atan2(a);
289    let spread = ratio.clamp(-1.0, 1.0).acos();
290    let at = if ratio.abs() >= 1.0 - TOUCH {
291        vec![phi + spread]
292    } else {
293        vec![phi + spread, phi - spread]
294    };
295    at.into_iter()
296        .map(|u| {
297            Ok(PlaneSection::Line {
298                line: Line3D::new(apex, cone.evaluate(u, 1.0) - apex)?,
299                ray: true,
300            })
301        })
302        .collect()
303}
304
305/// Compute exact intersection curves between a plane and an analytic surface.
306///
307/// Returns exact `Circle3D` or `Ellipse3D` where possible, falling back to
308/// sampled points for complex cases (torus).
309///
310/// A plane along a cylinder's axis or through a cone's apex, whose sections
311/// are straight, and a plane touching a sphere get no curve here;
312/// [`exact_plane_section`] returns those sections.
313///
314/// The plane is defined by `dot(normal, p) = d`.
315///
316/// # Errors
317///
318/// Returns an error if the intersection computation fails.
319pub fn exact_plane_analytic(
320    surface: AnalyticSurface<'_>,
321    plane_normal: Vec3,
322    plane_d: f64,
323) -> Result<Vec<ExactIntersectionCurve>, MathError> {
324    exact_plane_analytic_reaching(surface, plane_normal, plane_d, 0.0)
325}
326
327/// [`exact_plane_analytic`] with a cone's sampled hyperbola or parabola
328/// carried at least `reach` from the apex, so it spans whatever faces the
329/// caller will trim it to.
330///
331/// # Errors
332///
333/// Returns an error if the intersection computation fails.
334pub fn exact_plane_analytic_reaching(
335    surface: AnalyticSurface<'_>,
336    plane_normal: Vec3,
337    plane_d: f64,
338    reach: f64,
339) -> Result<Vec<ExactIntersectionCurve>, MathError> {
340    match surface {
341        AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
342        AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
343        AnalyticSurface::Cone(cone) if plane_holds_apex(cone, plane_normal, plane_d) => Ok(vec![]),
344        AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d, reach),
345        AnalyticSurface::Torus(torus) => {
346            if let Some(circles) = exact_plane_torus(torus, plane_normal, plane_d)? {
347                return Ok(circles);
348            }
349            if let Some(loops) = plane_torus_winding_loops(torus, plane_normal, plane_d, 128) {
350                return Ok(loops
351                    .into_iter()
352                    .map(ExactIntersectionCurve::Points)
353                    .collect());
354            }
355            // Other torus sections are degree-4 — fall back to sampling.
356            let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
357            Ok(chains
358                .into_iter()
359                .map(ExactIntersectionCurve::Points)
360                .collect())
361        }
362    }
363}
364
365/// The plane-torus sections that are circles:
366///
367/// - a plane across the axis at height `h` from the centre, `|h| < r`: the
368///   two circles of radius `R ± sqrt(r² − h²)` about the axis;
369/// - a plane through the axis: the two tube cross-sections of radius `r`,
370///   `R` either side of the axis.
371///
372/// A plane across the axis tangent to the tube's top or bottom touches it
373/// along the one circle of radius `R`, ring or spindle.
374///
375/// `Some` of no curves for a plane across the axis that misses the tube;
376/// `None` for any other plane, and for a section across the axis whose inner
377/// circle would reach the axis.
378fn exact_plane_torus(
379    torus: &ToroidalSurface,
380    normal: Vec3,
381    d: f64,
382) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
383    let len = normal.length();
384    let n = normal.normalize()?;
385    let d = d / len;
386    let axis = torus.z_axis();
387    let center = torus.center();
388    let (big, small) = (torus.major_radius(), torus.minor_radius());
389    let height = d - dot_np(n, center);
390    let along = n.dot(axis);
391    if along.abs() > 1.0 - 1e-10 {
392        if height.abs() >= small - 1e-10 * small {
393            if height.abs() > small + 1e-10 * small {
394                return Ok(Some(Vec::new()));
395            }
396            // Tangent to the tube's top or bottom: the plane touches the
397            // torus along the one circle of its own radius. That circle lies
398            // on the torus within the plane's distance from the tube's top,
399            // so it stands for the section while that distance is within the
400            // linear tolerance, whatever the scale. A tilted plane's section
401            // is no circle.
402            if big <= 1e-10 * small
403                || axis.cross(n).length() > 1e-12
404                || (small - height.abs()).abs() > crate::tolerance::Tolerance::default().linear
405            {
406                return Ok(None);
407            }
408            let middle = center + n * height;
409            return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
410                middle, n, big,
411            )?)]));
412        }
413        let reach = small.madd(small, -(height * height)).sqrt();
414        if big - reach <= 1e-10 * big {
415            return Ok(None);
416        }
417        let middle = center + n * height;
418        return Ok(Some(vec![
419            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big + reach)?),
420            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big - reach)?),
421        ]));
422    }
423    if along.abs() < 1e-10 && height.abs() < 1e-10 * (big + small) {
424        let out = axis.cross(n).normalize()?;
425        return Ok(Some(vec![
426            ExactIntersectionCurve::Circle(Circle3D::new(center + out * big, n, small)?),
427            ExactIntersectionCurve::Circle(Circle3D::new(center - out * big, n, small)?),
428        ]));
429    }
430    Ok(None)
431}
432
433/// Exact plane-cylinder intersection.
434///
435/// - Plane perpendicular to axis → `Circle3D`
436/// - Plane oblique to axis → `Ellipse3D`
437/// - Plane parallel to axis → `Points` fallback (0 or 2 lines)
438fn exact_plane_cylinder(
439    cyl: &CylindricalSurface,
440    normal: Vec3,
441    d: f64,
442) -> Result<Vec<ExactIntersectionCurve>, MathError> {
443    let axis = cyl.axis();
444    let cos_theta = normal.dot(axis).abs();
445    let r = cyl.radius();
446
447    if cos_theta < 1e-10 {
448        // A plane along the axis cuts straight rulings, which
449        // `exact_plane_section` returns.
450        return Ok(vec![]);
451    }
452
453    // Find where axis intersects the plane: axis_point + t*axis, dot(normal, P) = d
454    // t = (d - dot(normal, origin)) / dot(normal, axis)
455    let n_dot_axis = normal.dot(axis);
456    let n_dot_origin = dot_np(normal, cyl.origin());
457    let t = (d - n_dot_origin) / n_dot_axis;
458    let center_on_axis = Point3::new(
459        cyl.origin().x() + t * axis.x(),
460        cyl.origin().y() + t * axis.y(),
461        cyl.origin().z() + t * axis.z(),
462    );
463
464    if cos_theta > 1.0 - 1e-10 {
465        // Plane perpendicular to axis → Circle
466        let circle = Circle3D::new(center_on_axis, normal, r)?;
467        Ok(vec![ExactIntersectionCurve::Circle(circle)])
468    } else {
469        // Oblique plane → Ellipse
470        // Semi-minor = r (the cylinder radius, unchanged)
471        // Semi-major = r / cos(θ) where θ = angle between plane normal and axis
472        let semi_minor = r;
473        let semi_major = r / cos_theta;
474
475        // The major axis direction lies in the intersection of the plane
476        // with the plane containing the axis and the plane normal.
477        // It's the projection of the axis onto the cutting plane, normalized.
478        let axis_proj = Vec3::new(
479            axis.x() - n_dot_axis * normal.x(),
480            axis.y() - n_dot_axis * normal.y(),
481            axis.z() - n_dot_axis * normal.z(),
482        );
483        let u_axis = axis_proj.normalize()?;
484        let v_axis = normal.cross(u_axis);
485
486        let ellipse = Ellipse3D::with_axes(
487            center_on_axis,
488            normal,
489            semi_major,
490            semi_minor,
491            u_axis,
492            v_axis,
493        )?;
494        Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
495    }
496}
497
498/// Exact plane-sphere intersection.
499///
500/// Always produces a `Circle3D` (or empty if no intersection).
501fn exact_plane_sphere(
502    sphere: &SphericalSurface,
503    normal: Vec3,
504    d: f64,
505) -> Result<Vec<ExactIntersectionCurve>, MathError> {
506    let h = dot_np(normal, sphere.center()) - d;
507    let r = sphere.radius();
508
509    // A plane touching the sphere meets it at a point, which
510    // `exact_plane_section` returns.
511    if r - h.abs() <= TOUCH * r {
512        return Ok(vec![]);
513    }
514
515    let circle_r = (r.madd(r, -(h * h))).sqrt();
516    let circle_center = Point3::new(
517        h.madd(-normal.x(), sphere.center().x()),
518        h.madd(-normal.y(), sphere.center().y()),
519        h.madd(-normal.z(), sphere.center().z()),
520    );
521
522    let circle = Circle3D::new(circle_center, normal, circle_r)?;
523    Ok(vec![ExactIntersectionCurve::Circle(circle)])
524}
525
526/// Exact sphere-sphere intersection: the circle on the two spheres' radical
527/// plane, its normal pointing from the first centre to the second. `None`
528/// for one sphere twice (the same surface, no curve).
529///
530/// The circle is built from the smaller sphere, whose radius bounds it, and
531/// from the centres' offset alone, so neither the operands' order nor where
532/// the pair sits in space decides whether a small circle survives.
533///
534/// # Errors
535///
536/// Returns an error if the circle cannot be built.
537pub fn exact_sphere_sphere(
538    s1: &SphericalSurface,
539    s2: &SphericalSurface,
540) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
541    let delta = s2.center() - s1.center();
542    let d = delta.length();
543    let (r1, r2) = (s1.radius(), s2.radius());
544    let scale = r1.max(r2);
545    if d <= 1e-12 * scale {
546        // Concentric spheres of different radii never meet.
547        return Ok(((r1 - r2).abs() > 1e-12 * scale).then(Vec::new));
548    }
549    let normal = delta * (1.0 / d);
550    // From the smaller sphere's centre toward the larger's, the radical plane
551    // lies `along` away.
552    let (centre, toward, r_small, r_big) = if r1 <= r2 {
553        (s1.center(), normal, r1, r2)
554    } else {
555        (s2.center(), -normal, r2, r1)
556    };
557    let along = d.madd(d, r_small.madd(r_small, -(r_big * r_big))) / (2.0 * d);
558    if along.abs() > r_small - 1e-10 * scale.max(1.0) {
559        return Ok(Some(Vec::new()));
560    }
561    let radius = r_small.madd(r_small, -(along * along)).sqrt();
562    let circle = Circle3D::new(centre + toward * along, normal, radius)?;
563    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
564}
565
566/// Exact plane-cone intersection.
567///
568/// The conic type is set by the cone's half-opening angle from the axis
569/// (`γ = π/2 − half_angle`) versus the plane-axis angle `ψ`:
570/// - Plane perpendicular to axis (`ψ = π/2`) → `Circle3D`
571/// - `ψ > γ` (ellipse) → closed-form `Ellipse3D`
572/// - `ψ ≤ γ` (parabola/hyperbola) → bounded single-branch `Points` (one chain
573///   per branch — a hyperbola's two nappes never share a chain)
574fn exact_plane_cone(
575    cone: &ConicalSurface,
576    normal: Vec3,
577    d: f64,
578    reach: f64,
579) -> Result<Vec<ExactIntersectionCurve>, MathError> {
580    let axis = cone.axis();
581    let cos_theta = normal.dot(axis).abs();
582    let half_angle = cone.half_angle();
583
584    if cos_theta > 1.0 - 1e-10 {
585        // Plane perpendicular to axis → Circle
586        // Find where axis meets the plane
587        let n_dot_axis = normal.dot(axis);
588        let n_dot_apex = dot_np(normal, cone.apex());
589        let t = (d - n_dot_apex) / n_dot_axis;
590
591        // t is the signed distance from apex to plane along the axis.
592        // The real cone is a single nappe; the perpendicular-plane section is a
593        // circle whose radius follows from the axial offset |t|.
594        // |t| ≈ 0 means the plane passes through the apex → degenerate point.
595        if t.abs() < 1e-10 {
596            return Ok(vec![]);
597        }
598
599        let center = Point3::new(
600            cone.apex().x() + t * axis.x(),
601            cone.apex().y() + t * axis.y(),
602            cone.apex().z() + t * axis.z(),
603        );
604        // half_angle is the angle from the radial plane to the surface.
605        // Axial distance t = v * sin(half_angle), so v = t / sin(half_angle).
606        // Radius at v = v * cos(half_angle) = t * cos(half_angle) / sin(half_angle).
607        let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
608        if circle_r < 1e-15 {
609            return Ok(vec![]);
610        }
611
612        let circle = Circle3D::new(center, normal, circle_r)?;
613        return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
614    }
615
616    // Oblique plane. Classify the conic in the plane-aligned frame.
617    //
618    // Decompose the (unit) axis as a = c·n + p·e1, where c = n·a, e1 is the unit
619    // in-plane projection of the axis, and p = |projection| = sqrt(1−c²). Write a
620    // point Q on the plane as Q = apex + e·n + s·e1 + t·e2 (e = d − n·apex,
621    // e2 = n×e1). The cone equation (w·a)² = cos²γ·(w·w) with k = cos²γ =
622    // sin²(half_angle) reduces to (no s·t cross term, since e1/e2 align with the
623    // conic axes):
624    //     (p²−k)·s² + 2ecp·s + e²(c²−k) = k·t²
625    // The s² coefficient A = p²−k = sin²θ − sin²(half_angle) sets the type:
626    // A < 0 → ellipse, A = 0 → parabola, A > 0 → hyperbola.
627    let c = normal.dot(axis);
628    let p2 = (1.0 - c * c).max(0.0);
629    let p = p2.sqrt();
630    let k = half_angle.sin().powi(2);
631    let a_coeff = p2 - k;
632
633    // Build the plane-aligned frame e1 (in-plane axis projection), e2 = n×e1.
634    let m = Vec3::new(
635        axis.x() - c * normal.x(),
636        axis.y() - c * normal.y(),
637        axis.z() - c * normal.z(),
638    );
639    let m_len = m.length();
640    if m_len < 1e-12 {
641        // Axis parallel to normal — handled by the perpendicular branch above;
642        // fall back to sampling for safety.
643        let chains = sample_plane_cone(cone, normal, d, reach)?;
644        return Ok(chains
645            .into_iter()
646            .map(ExactIntersectionCurve::Points)
647            .collect());
648    }
649    let e1 = m * (1.0 / m_len);
650    let e2 = normal.cross(e1);
651    let apex = cone.apex();
652    let e = d - dot_np(normal, apex);
653
654    // Ellipse → closed form. A = p²−k < 0 with a margin to keep the
655    // near-parabolic regime on the robust sampled path.
656    if a_coeff < -1e-9 {
657        let abs_a = -a_coeff; // = k − p² > 0
658        // Real-nappe guard: in the ellipse regime n·g(u) keeps constant sign(c),
659        // so v = e/(n·g) ≥ 0 only when e and c share a sign. When e·c < 0 the
660        // plane is offset to the far side of the apex from the cone's opening —
661        // the section lies entirely on the phantom nappe, so there is no real
662        // curve (RHS below is positive regardless of sign, so it can't catch this).
663        if e * c < 0.0 {
664            return Ok(vec![]);
665        }
666        // |A|(s − s_c)² + k·t² = RHS, with s_c = ecp/|A| and
667        // RHS = e²·k·(1−k)/|A| (always > 0 for a real ellipse).
668        let s_c = e * c * p / abs_a;
669        let rhs = e * e * k * (1.0 - k) / abs_a;
670        if rhs <= 0.0 {
671            return Ok(vec![]);
672        }
673        let semi_s = (rhs / abs_a).sqrt(); // extent along e1
674        let semi_t = (rhs / k).sqrt(); // extent along e2
675        if semi_s < 1e-12 || semi_t < 1e-12 {
676            return Ok(vec![]);
677        }
678        let center = apex + normal * e + e1 * s_c;
679        let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
680            (semi_s, semi_t, e1, e2)
681        } else {
682            (semi_t, semi_s, e2, e1)
683        };
684        let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
685        return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
686    }
687
688    // Parabola / hyperbola (and the near-parabolic ellipse margin): the section
689    // is unbounded, so emit bounded, branch-separated sample chains.
690    let chains = sample_plane_cone(cone, normal, d, reach)?;
691    Ok(chains
692        .into_iter()
693        .map(ExactIntersectionCurve::Points)
694        .collect())
695}
696
697/// The exact arc from `from` to `to` of a plane's parabola or hyperbola
698/// section of a cone, both ends on one branch of it, as a rational quadratic
699/// NURBS.
700///
701/// A hyperbola `x = a cosh φ, y = b sinh φ` (in the plane frame of
702/// `exact_plane_cone`) is cut into pieces of at most one unit of `φ`, each
703/// a conic Bézier: its middle point is where the end tangents meet and its
704/// middle weight is the cosh of half the piece's span. A parabola is one
705/// polynomial quadratic. `None` for an elliptic or circular section, a plane
706/// through the apex, or ends off one branch of the section.
707///
708/// # Errors
709///
710/// Returns an error if the plane normal is zero or the curve cannot be built.
711#[allow(clippy::many_single_char_names)]
712pub fn plane_cone_conic_arc(
713    cone: &ConicalSurface,
714    normal: Vec3,
715    d: f64,
716    from: Point3,
717    to: Point3,
718) -> Result<Option<NurbsCurve>, MathError> {
719    let len = normal.length();
720    if len < 1e-15 {
721        return Err(MathError::ZeroVector);
722    }
723    let (normal, d) = (normal * (1.0 / len), d / len);
724    let axis = cone.axis();
725    let c = normal.dot(axis);
726    let p2 = (1.0 - c * c).max(0.0);
727    let p = p2.sqrt();
728    let k = cone.half_angle().sin().powi(2);
729    let a_coeff = p2 - k;
730    let m = Vec3::new(
731        axis.x() - c * normal.x(),
732        axis.y() - c * normal.y(),
733        axis.z() - c * normal.z(),
734    );
735    let m_len = m.length();
736    if m_len < 1e-12 || a_coeff < -1e-9 {
737        return Ok(None);
738    }
739    let e1 = m * (1.0 / m_len);
740    let e2 = normal.cross(e1);
741    let apex = cone.apex();
742    let e = d - dot_np(normal, apex);
743    let origin = apex + normal * e;
744    let plane_st = |q: Point3| {
745        let w = q - origin;
746        (w.dot(e1), w.dot(e2))
747    };
748    let ((s0, t0), (s1, t1)) = (plane_st(from), plane_st(to));
749    let scale = s0.abs().max(t0.abs()).max(s1.abs()).max(t1.abs()).max(1.0);
750    if e.abs() < 1e-9 * scale || (from - to).length() <= 1e-9 * scale {
751        return Ok(None);
752    }
753    let point = |s: f64, t: f64| origin + e1 * s + e2 * t;
754    let on_curve = |q: Point3, r: Point3| (q - r).length() <= 1e-6 * scale;
755    let (control, weights) = if a_coeff.abs() <= 1e-9 {
756        // (p² − k) s² vanishes: 2ecp·s + e²(c² − k) = k·t², s = α t² + β.
757        let lin = 2.0 * e * c * p;
758        if lin.abs() < 1e-12 * scale {
759            return Ok(None);
760        }
761        let (alpha, beta) = (k / lin, -e * e * (c * c - k) / lin);
762        if !on_curve(point(alpha * t0 * t0 + beta, t0), from)
763            || !on_curve(point(alpha * t1 * t1 + beta, t1), to)
764        {
765            return Ok(None);
766        }
767        let mid = point(alpha * t0 * t1 + beta, 0.5 * (t0 + t1));
768        (vec![from, mid, to], vec![1.0; 3])
769    } else {
770        // A (s − s_c)² − k t² = R with R = e² k (1 − k) / A.
771        let s_c = -e * c * p / a_coeff;
772        let r = e * e * k * (1.0 - k) / a_coeff;
773        if r <= 0.0 {
774            return Ok(None);
775        }
776        let (a, b) = ((r / a_coeff).sqrt(), (r / k).sqrt());
777        let (x0, x1) = (s0 - s_c, s1 - s_c);
778        if x0 * x1 <= 0.0 {
779            return Ok(None);
780        }
781        let side = x0.signum();
782        let hyperbola = |phi: f64| point(s_c + side * a * phi.cosh(), b * phi.sinh());
783        let (phi0, phi1) = ((t0 / b).asinh(), (t1 / b).asinh());
784        if !on_curve(hyperbola(phi0), from) || !on_curve(hyperbola(phi1), to) {
785            return Ok(None);
786        }
787        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
788        let pieces = ((phi1 - phi0).abs().ceil() as usize).max(1);
789        let mut control = vec![from];
790        let mut weights = vec![1.0];
791        for i in 0..pieces {
792            #[allow(clippy::cast_precision_loss)]
793            let (fa, fb) = (i as f64 / pieces as f64, (i + 1) as f64 / pieces as f64);
794            let (pa, pb) = (phi0 + (phi1 - phi0) * fa, phi0 + (phi1 - phi0) * fb);
795            let (mid, half) = (0.5 * (pa + pb), 0.5 * (pb - pa));
796            let w = half.cosh();
797            control.push(point(s_c + side * a * mid.cosh() / w, b * mid.sinh() / w));
798            weights.push(w);
799            control.push(if i + 1 == pieces { to } else { hyperbola(pb) });
800            weights.push(1.0);
801        }
802        (control, weights)
803    };
804    let pieces = (control.len() - 1) / 2;
805    let mut knots = vec![0.0; 3];
806    for i in 1..pieces {
807        #[allow(clippy::cast_precision_loss)]
808        knots.extend([i as f64; 2]);
809    }
810    #[allow(clippy::cast_precision_loss)]
811    knots.extend([pieces as f64; 3]);
812    let curve = NurbsCurve::new(2, knots, control, weights)?;
813    // The closed forms drop terms that vanish only on the exact conic (a
814    // barely elliptic section read as a parabola), so the arc must meet the
815    // cone between its ends too: a point at radius ρ and height h off the
816    // apex lies |ρ sin α − |h| cos α| from it.
817    let (sin_a, cos_a) = cone.half_angle().sin_cos();
818    let off_cone = |q: Point3| {
819        let w = q - apex;
820        let h = w.dot(axis);
821        (w - axis * h)
822            .length()
823            .madd(sin_a, -(h.abs() * cos_a))
824            .abs()
825    };
826    for i in 0..pieces {
827        for f in [0.25, 0.5, 0.75] {
828            #[allow(clippy::cast_precision_loss)]
829            if off_cone(curve.evaluate(i as f64 + f)) > 1e-9 * scale {
830                return Ok(None);
831            }
832        }
833    }
834    Ok(Some(curve))
835}
836
837/// Reference to an analytic surface for intersection dispatch.
838#[derive(Clone, Copy)]
839pub enum AnalyticSurface<'a> {
840    /// Cylindrical surface reference.
841    Cylinder(&'a CylindricalSurface),
842    /// Conical surface reference.
843    Cone(&'a ConicalSurface),
844    /// Spherical surface reference.
845    Sphere(&'a SphericalSurface),
846    /// Toroidal surface reference.
847    Torus(&'a ToroidalSurface),
848}
849
850/// Compute `n . p` treating a `Point3` as a position vector.
851fn dot_np(n: Vec3, p: Point3) -> f64 {
852    n.dot(Vec3::new(p.x(), p.y(), p.z()))
853}
854
855/// Intersect a plane with an analytic surface.
856///
857/// The plane is defined by `dot(normal, p) = d`.
858///
859/// # Errors
860///
861/// Returns an error if the intersection computation fails.
862pub fn intersect_plane_analytic(
863    surface: AnalyticSurface<'_>,
864    normal: Vec3,
865    d: f64,
866) -> Result<Vec<IntersectionCurve>, MathError> {
867    match surface {
868        AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
869        AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
870        AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
871        AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
872    }
873}
874
875/// Sample points on the plane-analytic intersection without NURBS curve fitting.
876///
877/// Returns chains of ordered 3D sample points. Each chain is one connected
878/// component of the intersection curve. This is much faster than
879/// `intersect_plane_analytic` when only sample points are needed (e.g. for
880/// boolean intersection segment generation).
881///
882/// # Errors
883///
884/// Returns an error if the intersection computation fails.
885pub fn sample_plane_analytic(
886    surface: AnalyticSurface<'_>,
887    normal: Vec3,
888    d: f64,
889) -> Result<Vec<Vec<Point3>>, MathError> {
890    match surface {
891        AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
892        AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d, 0.0),
893        AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
894        AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
895    }
896}
897
898/// Sample the plane-cylinder intersection as ordered 3D points.
899#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
900fn sample_plane_cylinder(
901    cyl: &CylindricalSurface,
902    normal: Vec3,
903    d: f64,
904) -> Result<Vec<Vec<Point3>>, MathError> {
905    let n_samples = 64_usize;
906    let mut points = Vec::with_capacity(n_samples + 1);
907
908    for i in 0..=n_samples {
909        let u = TAU * (i as f64) / (n_samples as f64);
910        let base = cyl.evaluate(u, 0.0);
911        let n_dot_axis = normal.dot(cyl.axis());
912        let n_dot_base = dot_np(normal, base);
913
914        if n_dot_axis.abs() < 1e-12 {
915            if (n_dot_base - d).abs() < 1e-6 {
916                points.push(base);
917            }
918        } else {
919            let v = (d - n_dot_base) / n_dot_axis;
920            if v.abs() <= 100.0 {
921                points.push(cyl.evaluate(u, v));
922            }
923        }
924    }
925
926    if points.len() < 2 {
927        Ok(vec![])
928    } else {
929        Ok(vec![points])
930    }
931}
932
933/// Sample the plane-sphere intersection as ordered 3D points.
934#[allow(clippy::cast_precision_loss)]
935fn sample_plane_sphere(
936    sphere: &SphericalSurface,
937    normal: Vec3,
938    d: f64,
939) -> Result<Vec<Vec<Point3>>, MathError> {
940    let h = dot_np(normal, sphere.center()) - d;
941    let r = sphere.radius();
942
943    if h.abs() > r - 1e-10 {
944        return Ok(vec![]);
945    }
946
947    let circle_r = (r.madd(r, -(h * h))).sqrt();
948    let circle_center = Point3::new(
949        h.madd(-normal.x(), sphere.center().x()),
950        h.madd(-normal.y(), sphere.center().y()),
951        h.madd(-normal.z(), sphere.center().z()),
952    );
953
954    let basis = Frame3::from_normal(circle_center, normal)?;
955    let u_dir = basis.x;
956    let v_dir = basis.y;
957
958    let n_samples = 64_usize;
959    let mut points = Vec::with_capacity(n_samples + 1);
960
961    for i in 0..=n_samples {
962        let theta = TAU * (i as f64) / (n_samples as f64);
963        let (sin_t, cos_t) = theta.sin_cos();
964        points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
965    }
966
967    Ok(vec![points])
968}
969
970/// Sample the plane-cone intersection as ordered 3D points.
971///
972/// The cone is the single real nappe `v >= 0` of `P(u,v) = apex + v·g(u)`.
973/// Along each generator `g(u)` the plane `n·P = d` is linear in `v`, so
974/// `v = (d − n·apex) / (n·g(u))`. We keep only `v >= 0` (the phantom `v < 0`
975/// nappe is geometrically absent) and `v` below a finite bound (near an
976/// asymptote `n·g(u) → 0` so `v → ∞` — those points run off the surface and
977/// must be excluded). The angular samples that survive form one contiguous arc
978/// (ellipse) or two (parabola/hyperbola, one per branch); each contiguous run
979/// is returned as a separate ordered chain so the consumer never stitches two
980/// disjoint branches into one curve.
981#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
982fn sample_plane_cone(
983    cone: &ConicalSurface,
984    normal: Vec3,
985    d: f64,
986    reach: f64,
987) -> Result<Vec<Vec<Point3>>, MathError> {
988    let apex = cone.apex();
989    let n_dot_apex = dot_np(normal, apex);
990    let e = d - n_dot_apex;
991
992    // Per-generator solve: along g(u) the plane is linear in v, v = e / (n·g(u)).
993    // Sample u densely; keep only the real nappe (v >= 0) and skip near-asymptote
994    // generators (n·g(u) ≈ 0 → v → ∞).
995    let n_samples = 512_usize;
996    let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
997    let mut v_min = f64::INFINITY;
998    for i in 0..n_samples {
999        let u = TAU * (i as f64) / (n_samples as f64);
1000        let g = cone.evaluate(u, 1.0) - apex;
1001        let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
1002        if n_dot_g.abs() < 1e-12 {
1003            vs.push(None);
1004            continue;
1005        }
1006        let v = e / n_dot_g;
1007        if v >= -1e-12 {
1008            let v = v.max(0.0);
1009            v_min = v_min.min(v);
1010            vs.push(Some(v));
1011        } else {
1012            vs.push(None);
1013        }
1014    }
1015
1016    if !v_min.is_finite() {
1017        return Ok(Vec::new());
1018    }
1019
1020    // Bound the arc around the conic vertex (closest approach to the apex, at
1021    // v_min). An ellipse is naturally bounded; a parabola/hyperbola is not, so
1022    // cap the cone radius at a generous multiple of the vertex radius. This is
1023    // scale-invariant and centred on where any finite cone face's overlap lies;
1024    // the downstream consumer trims the fitted curve to the actual face AABB, so
1025    // over-coverage is harmless. The floor handles a vertex at the apex (v_min≈0).
1026    // A caller that knows its faces asks for their reach: an open hyperbola
1027    // (a vertex close to the axis) crosses a rim far past eight vertex radii.
1028    let v_max = (8.0 * v_min).max(v_min + 4.0).max(reach);
1029
1030    // Per-sample v within the cap; the raw values stay in `vs` for the
1031    // boundary solve below.
1032    let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
1033
1034    let point_at = |u: f64, v: f64| -> Point3 {
1035        let g = cone.evaluate(u, 1.0) - apex;
1036        apex + g * v
1037    };
1038    #[allow(clippy::cast_precision_loss)]
1039    let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
1040    let n_dot_g_at = |u: f64| -> f64 {
1041        let g = cone.evaluate(u, 1.0) - apex;
1042        normal.dot(Vec3::new(g.x(), g.y(), g.z()))
1043    };
1044
1045    if kept.iter().all(Option::is_some) {
1046        // Closed loop (ellipse regime): emit all points and repeat the first.
1047        let mut pts: Vec<Point3> = kept
1048            .iter()
1049            .enumerate()
1050            .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
1051            .collect();
1052        if let Some(&first) = pts.first() {
1053            pts.push(first);
1054        }
1055        return Ok(vec![pts]);
1056    }
1057
1058    // A hyperbola/parabola tail diverges as 1/(n·g), so between the last kept
1059    // sample and its dropped neighbour v can leap far past `v_max` in one
1060    // uniform-u pitch — and any finite face window inside that leap is lost
1061    // (a taper cone grazed 0.05 by a prism plane lost its entire 0.5-tall
1062    // section to exactly this aliasing). Extend each run end to the exact
1063    // `v_max` boundary: bisect u for `n·g(u) = e/v_max` inside the dropped
1064    // pitch (n·g is monotone there — its extrema sit at the conic vertex,
1065    // far from any asymptote), then fill the tail with uniform-u samples.
1066    let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
1067        let Some(v_end) = kept[i_end] else {
1068            return Vec::new();
1069        };
1070        let u_end = u_of(i_end);
1071        #[allow(clippy::cast_precision_loss)]
1072        let pitch = TAU / (n_samples as f64);
1073        let u_next = if forward {
1074            u_end + pitch
1075        } else {
1076            u_end - pitch
1077        };
1078        let target = e / v_max;
1079        let h_end = n_dot_g_at(u_end) - target;
1080        let h_next = n_dot_g_at(u_next) - target;
1081        if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
1082            return Vec::new();
1083        }
1084        let (mut lo, mut hi) = (u_end, u_next);
1085        for _ in 0..60 {
1086            let mid = f64::midpoint(lo, hi);
1087            if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
1088                lo = mid;
1089            } else {
1090                hi = mid;
1091            }
1092        }
1093        let u_star = f64::midpoint(lo, hi);
1094        let tail_n = 8_usize;
1095        (1..=tail_n)
1096            .filter_map(|k| {
1097                #[allow(clippy::cast_precision_loss)]
1098                let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
1099                let ng = n_dot_g_at(u);
1100                if ng.abs() < 1e-12 {
1101                    return None;
1102                }
1103                let v = e / ng;
1104                (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
1105            })
1106            .collect()
1107    };
1108
1109    // Split into contiguous runs of kept samples, treating the array as
1110    // circular (rotate past a gap) so a branch straddling u=0 stays whole.
1111    let gap = kept.iter().position(Option::is_none).unwrap_or(0);
1112    let mut chains: Vec<Vec<Point3>> = Vec::new();
1113    let mut run: Vec<usize> = Vec::new();
1114    let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
1115        if run.len() >= 2 {
1116            let first = run[0];
1117            let last = run[run.len() - 1];
1118            let mut pts: Vec<Point3> = tail(first, false, &kept);
1119            pts.reverse();
1120            pts.extend(
1121                run.iter()
1122                    .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
1123            );
1124            pts.extend(tail(last, true, &kept));
1125            chains.push(pts);
1126        }
1127        run.clear();
1128    };
1129    for k in 0..n_samples {
1130        let idx = (gap + k) % n_samples;
1131        if kept[idx].is_some() {
1132            run.push(idx);
1133        } else {
1134            flush(&mut run, &mut chains);
1135        }
1136    }
1137    flush(&mut run, &mut chains);
1138    Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
1139}
1140
1141/// Sample the plane-torus intersection as ordered 3D points.
1142///
1143/// Uses the same closed-form loops as `intersect_plane_torus`
1144/// but skips NURBS curve fitting (the callers here only need the points).
1145#[allow(clippy::unnecessary_wraps)] // sibling match-arms and `?` callers need `Result`
1146fn sample_plane_torus(
1147    torus: &ToroidalSurface,
1148    normal: Vec3,
1149    d: f64,
1150) -> Result<Vec<Vec<Point3>>, MathError> {
1151    Ok(plane_torus_loops(torus, normal, d, 128)
1152        .into_iter()
1153        .map(|run| run.into_iter().map(|p| p.point).collect())
1154        .collect())
1155}
1156
1157/// Intersect a plane with a cylindrical surface.
1158///
1159/// For each `u` in `[0, 2pi)`, the cylinder point is linear in `v`,
1160/// so the plane equation `dot(normal, P(u,v)) = d` is linear in `v`
1161/// and can be solved directly.
1162///
1163/// # Errors
1164///
1165/// Returns an error if curve fitting fails.
1166#[allow(clippy::cast_precision_loss)]
1167pub fn intersect_plane_cylinder(
1168    cyl: &CylindricalSurface,
1169    normal: Vec3,
1170    d: f64,
1171) -> Result<Vec<IntersectionCurve>, MathError> {
1172    let n_samples = 64_usize;
1173    let mut points_3d = Vec::new();
1174    let mut ipoints = Vec::new();
1175
1176    for i in 0..=n_samples {
1177        let u = TAU * (i as f64) / (n_samples as f64);
1178        // P(u, v) = origin + r*(cos(u)*x + sin(u)*y) + v*axis
1179        // dot(normal, P) = d  =>  dot(normal, base(u)) + v * dot(normal, axis) = d
1180        let base = cyl.evaluate(u, 0.0);
1181        let n_dot_axis = normal.dot(cyl.axis());
1182        let n_dot_base = dot_np(normal, base);
1183
1184        if n_dot_axis.abs() < 1e-12 {
1185            // Plane parallel to axis -- check if base is on plane.
1186            if (n_dot_base - d).abs() < 1e-6 {
1187                let pt = base;
1188                points_3d.push(pt);
1189                ipoints.push(IntersectionPoint {
1190                    point: pt,
1191                    param1: (u, 0.0),
1192                    param2: (0.0, 0.0),
1193                });
1194            }
1195        } else {
1196            let v = (d - n_dot_base) / n_dot_axis;
1197            // Only keep points within a reasonable v range.
1198            if v.abs() <= 100.0 {
1199                let pt = cyl.evaluate(u, v);
1200                points_3d.push(pt);
1201                ipoints.push(IntersectionPoint {
1202                    point: pt,
1203                    param1: (u, v),
1204                    param2: (0.0, 0.0),
1205                });
1206            }
1207        }
1208    }
1209
1210    build_curves_from_points(&points_3d, ipoints)
1211}
1212
1213/// Intersect a plane with a spherical surface.
1214///
1215/// The intersection of a plane with a sphere is a circle (or empty/point).
1216/// Computes the circle center, radius, and samples points on it.
1217///
1218/// # Errors
1219///
1220/// Returns an error if curve fitting fails.
1221#[allow(clippy::cast_precision_loss)]
1222pub fn intersect_plane_sphere(
1223    sphere: &SphericalSurface,
1224    normal: Vec3,
1225    d: f64,
1226) -> Result<Vec<IntersectionCurve>, MathError> {
1227    let h = dot_np(normal, sphere.center()) - d;
1228    let r = sphere.radius();
1229
1230    // No intersection if plane is too far from center.
1231    if h.abs() > r - 1e-10 {
1232        return Ok(vec![]);
1233    }
1234
1235    let circle_r = (r.madd(r, -(h * h))).sqrt();
1236    let circle_center = Point3::new(
1237        h.madd(-normal.x(), sphere.center().x()),
1238        h.madd(-normal.y(), sphere.center().y()),
1239        h.madd(-normal.z(), sphere.center().z()),
1240    );
1241
1242    // Build a local frame on the plane.
1243    let basis = Frame3::from_normal(circle_center, normal)?;
1244    let u_dir = basis.x;
1245    let v_dir = basis.y;
1246
1247    let n_samples = 64_usize;
1248    let mut points_3d = Vec::new();
1249    let mut ipoints = Vec::new();
1250
1251    for i in 0..=n_samples {
1252        let theta = TAU * (i as f64) / (n_samples as f64);
1253        let (sin_t, cos_t) = theta.sin_cos();
1254        let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
1255        points_3d.push(pt);
1256        ipoints.push(IntersectionPoint {
1257            point: pt,
1258            param1: (theta, 0.0),
1259            param2: (0.0, 0.0),
1260        });
1261    }
1262
1263    build_curves_from_points(&points_3d, ipoints)
1264}
1265
1266/// Intersect a plane with a conical surface.
1267///
1268/// Like a cylinder, the cone is linear along each generatrix, so the plane
1269/// equation is linear in `v` for each fixed `u`.
1270///
1271/// # Errors
1272///
1273/// Returns an error if curve fitting fails.
1274#[allow(clippy::cast_precision_loss)]
1275pub fn intersect_plane_cone(
1276    cone: &ConicalSurface,
1277    normal: Vec3,
1278    d: f64,
1279) -> Result<Vec<IntersectionCurve>, MathError> {
1280    let n_samples = 64_usize;
1281    let mut points_3d = Vec::new();
1282    let mut ipoints = Vec::new();
1283
1284    for i in 0..n_samples {
1285        let u = TAU * (i as f64) / (n_samples as f64);
1286        // P(u, v) = apex + v * dir(u)
1287        // dot(normal, apex) + v * dot(normal, dir(u)) = d
1288        let apex = cone.apex();
1289        let n_dot_apex = dot_np(normal, apex);
1290        // dir(u) = P(u,1) - apex
1291        let p1 = cone.evaluate(u, 1.0);
1292        let dir = p1 - apex;
1293        let n_dot_dir = normal.dot(dir);
1294
1295        if n_dot_dir.abs() < 1e-12 {
1296            continue;
1297        }
1298
1299        let v = (d - n_dot_apex) / n_dot_dir;
1300        // Allow negative v — the cone surface extends in both directions from the apex.
1301        if v.abs() > 1e-10 && v.abs() < 100.0 {
1302            let pt = cone.evaluate(u, v);
1303            points_3d.push(pt);
1304            ipoints.push(IntersectionPoint {
1305                point: pt,
1306                param1: (u, v),
1307                param2: (0.0, 0.0),
1308            });
1309        }
1310    }
1311
1312    build_curves_from_points(&points_3d, ipoints)
1313}
1314
1315/// Intersect a plane with a toroidal surface.
1316///
1317/// The section is a degree-4 curve, but for each `v` the `u` values solve in
1318/// closed form (see `plane_torus_loops`), so it is sampled by a v-scan
1319/// and each loop is fitted to a NURBS curve.
1320///
1321/// # Errors
1322///
1323/// Never returns an error today (curve-fit failures drop the affected loop);
1324/// the `Result` is kept for signature parity with the other plane-analytic
1325/// intersectors.
1326#[allow(clippy::unnecessary_wraps)]
1327pub fn intersect_plane_torus(
1328    torus: &ToroidalSurface,
1329    normal: Vec3,
1330    d: f64,
1331) -> Result<Vec<IntersectionCurve>, MathError> {
1332    // The section satisfies a per-v closed form (see `plane_torus_loops`),
1333    // so scan v and solve u directly instead of a 2D sign-change grid with
1334    // Newton refinement: O(n) rather than O(n²), and every point is exact.
1335    let mut curves = Vec::new();
1336    for ipts in plane_torus_loops(torus, normal, d, 128) {
1337        let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
1338        if let Ok(curve) = fit_plane_torus_section(torus, normal, d, &pts) {
1339            curves.push(IntersectionCurve {
1340                curve,
1341                points: ipts,
1342            });
1343        }
1344    }
1345
1346    Ok(curves)
1347}
1348
1349/// The point of a plane's section of a torus that `p`, a point near it,
1350/// moves to across both surfaces.
1351///
1352/// Newton steps take the point onto the plane and onto the tube nearer `p`,
1353/// both to rounding. Each step is the shortest move that clears both
1354/// first-order distances, so the point moves across the section and not
1355/// along it.
1356///
1357/// `None` where the two surfaces meet at a tangent (their normals within
1358/// about 1e-6 of parallel), where `p` lies on the torus's axis or a tube's
1359/// centre circle, or where the steps do not settle.
1360#[must_use]
1361pub fn plane_torus_section_point(
1362    torus: &ToroidalSurface,
1363    normal: Vec3,
1364    d: f64,
1365    p: Point3,
1366) -> Option<Point3> {
1367    plane_torus_newton(torus, normal, d, p, 0.0)
1368}
1369
1370/// [`plane_torus_section_point`], but where the steps so far have moved `p`
1371/// by less than `short`, the point they reach: the section's point lies
1372/// within about the square of the last step times the section's curvature
1373/// of it.
1374fn plane_torus_newton(
1375    torus: &ToroidalSurface,
1376    normal: Vec3,
1377    d: f64,
1378    p: Point3,
1379    short: f64,
1380) -> Option<Point3> {
1381    let scale = normal.length();
1382    if scale <= 0.0 || !scale.is_finite() {
1383        return None;
1384    }
1385    let n = normal * (1.0 / scale);
1386    let d = d / scale;
1387    let (axis, centre) = (torus.z_axis(), torus.center());
1388    let (big, small) = (torus.major_radius(), torus.minor_radius());
1389    let radial_of = |x: Point3| {
1390        let w = x - centre;
1391        w - axis * axis.dot(w)
1392    };
1393    // The tube is held to the side `p` starts on: a spindle torus's sheet
1394    // across the axis belongs to the far tube circle.
1395    let side = {
1396        let radial = radial_of(p);
1397        let rho = radial.length();
1398        let h = axis.dot(p - centre);
1399        if (rho + big).hypot(h) - small < ((rho - big).hypot(h) - small).abs() {
1400            -1.0
1401        } else {
1402            1.0
1403        }
1404    };
1405    // Each surface's distance from `x` and the torus's normal there.
1406    let residuals = |x: Point3| -> Option<(f64, f64, Vec3)> {
1407        let radial = radial_of(x);
1408        let rho = radial.length();
1409        if rho <= 0.0 {
1410            return None;
1411        }
1412        let to = (x - centre) - radial * (side * big / rho);
1413        let reach = to.length();
1414        if reach <= 0.0 {
1415            return None;
1416        }
1417        Some((dot_np(n, x) - d, reach - small, to * (1.0 / reach)))
1418    };
1419    let rounding = 16.0 * f64::EPSILON * (big + small + (p - centre).length());
1420    let mut x = p;
1421    for _ in 0..16 {
1422        let (f_plane, f_torus, g) = residuals(x)?;
1423        if f_plane.abs() <= rounding && f_torus.abs() <= rounding {
1424            return Some(x);
1425        }
1426        let c = n.dot(g);
1427        let det = c.madd(-c, 1.0);
1428        if det < 1e-12 {
1429            return None;
1430        }
1431        let along_n = c.madd(-f_torus, f_plane) / det;
1432        let along_g = c.madd(-f_plane, f_torus) / det;
1433        x = x - n * along_n - g * along_g;
1434        if (x - p).length() < short {
1435            return Some(x);
1436        }
1437    }
1438    let (f_plane, f_torus, _) = residuals(x)?;
1439    (f_plane.abs() <= 1e3 * rounding && f_torus.abs() <= 1e3 * rounding).then_some(x)
1440}
1441
1442/// How far a fitted plane x torus section may stray from the true section
1443/// between its points, as a fraction of the torus's outer radius.
1444const PLANE_TORUS_FIT: f64 = 1e-9;
1445
1446/// The most points a fitted plane x torus section takes.
1447const PLANE_TORUS_FIT_POINTS: usize = 4096;
1448
1449/// A cubic through `points`, points of a plane's section of a torus in order
1450/// along it, and through more points of the section where it needs them.
1451///
1452/// The cubic meets the section only at its points, and between two of them
1453/// it strays by about the fourth power of their spacing, which a tight turn
1454/// of the section makes large: 25 points along the section of a wall 0.4
1455/// outside the inner equator of a torus of radii 4 and 1.5 leave the cubic
1456/// 8e-5 off it. Each pass checks the cubic halfway between each two points:
1457/// where that point moves onto the section, within half the points'
1458/// spacing, by more than 1e-9 of the torus's outer radius, the section's
1459/// point there goes between them. Where it does not move onto the section
1460/// (on the axis, or where the plane all but touches the torus), it must lie
1461/// on both the plane and the torus within that bound itself.
1462///
1463/// # Errors
1464///
1465/// Returns an error if the interpolation fails (fewer than 2 points, or
1466/// repeated points), if a middle neither moves onto the section nor lies
1467/// on both surfaces, or if the cubic needs more than 4096 points.
1468pub fn fit_plane_torus_section(
1469    torus: &ToroidalSurface,
1470    normal: Vec3,
1471    d: f64,
1472    points: &[Point3],
1473) -> Result<NurbsCurve, MathError> {
1474    let tol = PLANE_TORUS_FIT.madd(
1475        torus.major_radius() + torus.minor_radius(),
1476        64.0 * f64::EPSILON * (torus.center() - Point3::new(0.0, 0.0, 0.0)).length(),
1477    );
1478    // How far a point lies from the plane, or from the torus, whichever is
1479    // farther.
1480    let strays = |p: Point3| {
1481        let w = p - torus.center();
1482        let height = torus.z_axis().dot(w);
1483        let rho = (w - torus.z_axis() * height).length();
1484        let off_torus = [1.0, -1.0]
1485            .into_iter()
1486            .map(|side: f64| {
1487                (side.madd(-torus.major_radius(), rho).hypot(height) - torus.minor_radius()).abs()
1488            })
1489            .fold(f64::INFINITY, f64::min);
1490        ((dot_np(normal, p) - d) / normal.length())
1491            .abs()
1492            .max(off_torus)
1493    };
1494    let mut pts = points.to_vec();
1495    let mut passes = 0;
1496    loop {
1497        passes += 1;
1498        let curve = interpolate(&pts, 3.min(pts.len().saturating_sub(1)))?;
1499        let params = crate::nurbs::fitting::chord_length_params(&pts);
1500        let mut finer = Vec::with_capacity(2 * pts.len());
1501        let mut added = false;
1502        for (i, pair) in pts.windows(2).enumerate() {
1503            finer.push(pair[0]);
1504            let gap = (pair[1] - pair[0]).length();
1505            let middle = curve.evaluate(f64::midpoint(params[i], params[i + 1]));
1506            // A point of the section half a spacing or more away lies on
1507            // another stretch of it (a thin tube's other loop).
1508            let on = plane_torus_newton(torus, normal, d, middle, 0.25 * tol)
1509                .filter(|on| (*on - middle).length() < 0.5 * gap);
1510            match on {
1511                Some(on) if (on - middle).length() <= tol => {}
1512                Some(on) => {
1513                    finer.push(on);
1514                    added = true;
1515                }
1516                None if strays(middle) <= tol => {}
1517                None => return Err(MathError::ConvergenceFailure { iterations: passes }),
1518            }
1519        }
1520        if !added {
1521            return Ok(curve);
1522        }
1523        if let Some(&last) = pts.last() {
1524            finer.push(last);
1525        }
1526        if finer.len() > PLANE_TORUS_FIT_POINTS {
1527            return Err(MathError::ConvergenceFailure { iterations: passes });
1528        }
1529        pts = finer;
1530    }
1531}
1532
1533/// The fewest and most steps along each branch of a loop a plane cuts from
1534/// a torus between its two turns.
1535const PLANE_TORUS_LOOP_SAMPLES: (f64, f64) = (24.0, 512.0);
1536
1537/// The loops a plane cuts from a torus, each as points on the torus in
1538/// order, closed by repeating its first point.
1539///
1540/// In the torus's own frame let `a = n·X`, `b = n·Y`, `c = n·Z`,
1541/// `s = hypot(a, b)`, `phi = atan2(b, a)`. Substituting the torus
1542/// parameterization into `n·P = d` gives
1543///   `(R + r·cos v)·s·cos(u − phi) + r·c·sin v = d − n·center`,
1544/// so at each tube angle `v` where `|rhs(v)| <= 1`, with
1545/// `rhs(v) = (d − n·center − r·c·sin v) / (s·(R + r·cos v))`, the section's
1546/// two branches are `u = phi ± acos(rhs(v))`. Each run of `v` where the
1547/// section exists is one loop: out along one branch to where the run ends
1548/// and the branches meet, and back along the other. A section present at
1549/// every `v` is two loops winding the tube, one per branch. Every point
1550/// comes from the closed form, so the loops need no chaining.
1551///
1552/// Where the branches touch inside a run (a plane tangent to the tube's
1553/// inner side, at a saddle) the section crosses itself: each branch passes
1554/// through that node, and each loop there starts and ends on it.
1555///
1556/// When `s ≈ 0` the plane is perpendicular to the axis and the section is up
1557/// to two full circles at the `v` values solving `r·c·sin v = d − n·center`,
1558/// sampled by scanning `u`.
1559#[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
1560fn plane_torus_loops(
1561    torus: &ToroidalSurface,
1562    normal: Vec3,
1563    d: f64,
1564    n_v: usize,
1565) -> Vec<Vec<IntersectionPoint>> {
1566    let big_r = torus.major_radius();
1567    let small_r = torus.minor_radius();
1568    let a = normal.dot(torus.x_axis());
1569    let b = normal.dot(torus.y_axis());
1570    let c = normal.dot(torus.z_axis());
1571    let s = a.hypot(b);
1572    let phi = b.atan2(a);
1573    let d_local = d - dot_np(normal, torus.center());
1574    let point = |u: f64, v: f64| IntersectionPoint {
1575        point: torus.evaluate(u, v),
1576        param1: (u, v.rem_euclid(TAU)),
1577        param2: (0.0, 0.0),
1578    };
1579    let closed = |mut run: Vec<IntersectionPoint>| {
1580        run.push(run[0]);
1581        run
1582    };
1583
1584    // Plane perpendicular to the axis: the section is up to two full circles.
1585    if s < 1e-12 {
1586        if c.abs() < 1e-12 {
1587            return Vec::new();
1588        }
1589        let sin_v = d_local / (small_r * c);
1590        if sin_v.abs() > 1.0 + 1e-9 {
1591            return Vec::new();
1592        }
1593        let v0 = sin_v.clamp(-1.0, 1.0).asin();
1594        let v1 = std::f64::consts::PI - v0;
1595        let mut vs = vec![v0];
1596        // Skip the mirror circle when the plane is tangent: at the tube's top
1597        // v0 == v1, and at its bottom they differ by a whole turn.
1598        let apart = (v1 - v0).rem_euclid(TAU);
1599        if apart.min(TAU - apart) > 1e-9 {
1600            vs.push(v1);
1601        }
1602        return vs
1603            .into_iter()
1604            .map(|v| {
1605                closed(
1606                    (0..n_v)
1607                        .map(|i| point(TAU * (i as f64) / (n_v as f64), v))
1608                        .collect(),
1609                )
1610            })
1611            .collect();
1612    }
1613
1614    // R + r·cos v > 0 on a ring torus.
1615    let length = normal.length();
1616    TorusSection {
1617        torus,
1618        phi,
1619        num: [d_local, 0.0, -small_r * c],
1620        den: [s * big_r, s * small_r],
1621        clearance: |p: Point3| (dot_np(normal, p) - d) / length,
1622        slack: 64.0 * f64::EPSILON * (big_r + small_r + d_local.abs() / length),
1623    }
1624    .loops(n_v, PLANE_TORUS_LOOP_SAMPLES)
1625}
1626
1627/// A surface's section of a ring torus that holds, at each tube angle `v`,
1628/// the torus's points with `cos(u − phi) = rhs(v)`: the two branches
1629/// `u = phi ± acos(rhs(v))` wherever `|rhs(v)| <= 1`, as for a plane
1630/// ([`plane_torus_loops`]) or a sphere off the axis ([`sphere_torus_section`]).
1631/// For both, `rhs(v) = (n0 + n1·cos v + n2·sin v) / (d0 + d1·cos v)` with a
1632/// positive denominator, so `rhs` meets `±1` where a sum of `cos v` and
1633/// `sin v` vanishes, at up to four tube angles in closed form.
1634struct TorusSection<'a, F> {
1635    torus: &'a ToroidalSurface,
1636    phi: f64,
1637    /// `n0`, `n1`, `n2`.
1638    num: [f64; 3],
1639    /// `d0`, `d1`.
1640    den: [f64; 2],
1641    /// A point's signed distance from the surface cutting the torus.
1642    clearance: F,
1643    /// The distance rounding can make or hide between the two surfaces.
1644    slack: f64,
1645}
1646
1647impl<F: Fn(Point3) -> f64> TorusSection<'_, F> {
1648    fn rhs(&self, v: f64) -> f64 {
1649        let [n0, n1, n2] = self.num;
1650        let [d0, d1] = self.den;
1651        let (sin, cos) = v.sin_cos();
1652        n2.madd(sin, n1.madd(cos, n0)) / d1.madd(cos, d0)
1653    }
1654
1655    fn point(&self, u: f64, v: f64) -> IntersectionPoint {
1656        IntersectionPoint {
1657            point: self.torus.evaluate(u, v),
1658            param1: (u.rem_euclid(TAU), v.rem_euclid(TAU)),
1659            param2: (0.0, 0.0),
1660        }
1661    }
1662
1663    fn branch(&self, v: f64, sign: f64) -> IntersectionPoint {
1664        self.point(sign.madd(self.rhs(v).clamp(-1.0, 1.0).acos(), self.phi), v)
1665    }
1666
1667    /// Where both branches meet at `v`: `acos` is 0 or π there.
1668    fn node(&self, v: f64) -> IntersectionPoint {
1669        let u = if self.rhs(v) >= 0.0 {
1670            self.phi
1671        } else {
1672            self.phi + std::f64::consts::PI
1673        };
1674        self.point(u, v)
1675    }
1676
1677    /// How far the surface lies from the point where the branches would meet
1678    /// at `v`: zero where the section's run ends, and where it only touches.
1679    fn depth(&self, v: f64) -> f64 {
1680        (self.clearance)(self.node(v).point).abs()
1681    }
1682
1683    /// The tube angles in `[0, 2π)` where `rhs` is `±1`, in order. Each solves
1684    /// `α + β·cos v + γ·sin v = 0`, so `cos(v − atan2(γ, β)) = −α / hypot(β, γ)`;
1685    /// a ratio past 1 by rounding alone is a double root, a touch.
1686    fn crossings(&self) -> Vec<f64> {
1687        let [n0, n1, n2] = self.num;
1688        let [d0, d1] = self.den;
1689        let mut roots = Vec::with_capacity(4);
1690        for c in [1.0_f64, -1.0] {
1691            let (alpha, beta, gamma) = (c.madd(-d0, n0), c.madd(-d1, n1), n2);
1692            let m = beta.hypot(gamma);
1693            let ratio = -alpha / m;
1694            if !ratio.is_finite() || ratio.abs() > 1.0 + 1e-12 {
1695                continue;
1696            }
1697            let theta = gamma.atan2(beta);
1698            let delta = ratio.clamp(-1.0, 1.0).acos();
1699            roots.push((theta - delta).rem_euclid(TAU));
1700            roots.push((theta + delta).rem_euclid(TAU));
1701        }
1702        roots.sort_by(f64::total_cmp);
1703        roots
1704    }
1705
1706    /// Each run of `v` where the section lies, from `lo` to `hi` unwrapped,
1707    /// with the node inside it where its branches touch, and whether it
1708    /// takes the whole turn. Between two crossings `|rhs|` stays on one side
1709    /// of 1; a stretch the surface clears or cuts by no more than `slack` is
1710    /// a touch, a node inside a run and nothing between runs.
1711    fn runs(&self) -> Vec<(f64, f64, Option<f64>, bool)> {
1712        let roots = self.crossings();
1713        let n = roots.len();
1714        if n == 0 {
1715            let whole = self.rhs(0.0).abs() <= 1.0 && self.depth(0.0) > self.slack;
1716            return if whole {
1717                vec![(0.0, TAU, None, true)]
1718            } else {
1719                Vec::new()
1720            };
1721        }
1722        let arcs: Vec<(f64, f64)> = (0..n)
1723            .map(|i| {
1724                (
1725                    roots[i],
1726                    if i + 1 < n {
1727                        roots[i + 1]
1728                    } else {
1729                        roots[0] + TAU
1730                    },
1731                )
1732            })
1733            .collect();
1734        let middle = |i: usize| f64::midpoint(arcs[i].0, arcs[i].1);
1735        let inside: Vec<bool> = (0..n).map(|i| self.rhs(middle(i)).abs() <= 1.0).collect();
1736        let shallow: Vec<bool> = (0..n)
1737            .map(|i| self.depth(middle(i)) <= self.slack)
1738            .collect();
1739        let deep_beside = |i: usize, back: bool| {
1740            (1..n)
1741                .map(|j| if back { (i + n - j) % n } else { (i + j) % n })
1742                .find(|&j| !shallow[j])
1743        };
1744        let kept: Vec<bool> = (0..n)
1745            .map(|i| {
1746                if !shallow[i] {
1747                    return inside[i];
1748                }
1749                matches!(
1750                    (deep_beside(i, true), deep_beside(i, false)),
1751                    (Some(a), Some(b)) if inside[a] && inside[b]
1752                )
1753            })
1754            .collect();
1755        let node_in = |from: usize, len: usize| {
1756            (0..len).find_map(|j| {
1757                let i = (from + j) % n;
1758                let wraps = if from + j >= n { TAU } else { 0.0 };
1759                shallow[i].then(|| middle(i) + wraps)
1760            })
1761        };
1762        let Some(first) = (0..n).find(|&i| kept[i] && !kept[(i + n - 1) % n]) else {
1763            return if kept.iter().all(|&k| k) {
1764                let node = node_in(0, n);
1765                let lo = node.unwrap_or(roots[0]);
1766                vec![(lo, lo + TAU, node, true)]
1767            } else {
1768                Vec::new()
1769            };
1770        };
1771        let mut runs = Vec::new();
1772        let mut j = 0;
1773        while j < n {
1774            let i = (first + j) % n;
1775            if !kept[i] {
1776                j += 1;
1777                continue;
1778            }
1779            let len = (0..n - j).take_while(|&k| kept[(i + k) % n]).count();
1780            let last = i + len - 1;
1781            let hi = arcs[last % n].1 + if last >= n { TAU } else { 0.0 };
1782            runs.push((arcs[i].0, hi, node_in(i, len), false));
1783            j += len;
1784        }
1785        runs
1786    }
1787
1788    /// Each run of the section as one loop, out along one branch to where
1789    /// the run ends and back along the other, closed by repeating its first
1790    /// point; a run taking the whole turn is two loops winding the tube.
1791    /// Where the branches touch inside a run the section crosses itself:
1792    /// each branch passes through that node, and each loop there starts and
1793    /// ends on it.
1794    #[allow(
1795        clippy::cast_precision_loss,
1796        clippy::cast_possible_truncation,
1797        clippy::cast_sign_loss
1798    )]
1799    fn loops(&self, n_v: usize, (fewest, most): (f64, f64)) -> Vec<Vec<IntersectionPoint>> {
1800        let closed = |mut run: Vec<IntersectionPoint>| {
1801            run.push(run[0]);
1802            run
1803        };
1804        let step = TAU / (n_v as f64);
1805        let mut loops = Vec::new();
1806        for (t_lo, t_hi, at_node, whole) in self.runs() {
1807            if whole {
1808                for sign in [1.0, -1.0] {
1809                    loops.push(closed(match at_node {
1810                        Some(v_node) => std::iter::once(self.node(v_node))
1811                            .chain(
1812                                (1..n_v).map(|i| self.branch((i as f64).madd(step, v_node), sign)),
1813                            )
1814                            .collect(),
1815                        None => (0..n_v)
1816                            .map(|i| self.branch((i as f64 + 0.5).madd(step, t_lo), sign))
1817                            .collect(),
1818                    }));
1819                }
1820                continue;
1821            }
1822            // `u` moves like the square root of the distance in `v` to a turn,
1823            // so the loop is sampled at `v = t_lo + (t_hi - t_lo) (1 - cos θ) / 2`
1824            // for even steps of `θ`: `v` then moves like `θ²` at each turn and
1825            // the points fall at near-even steps along the curve, turns
1826            // included. A loop that sweeps far round the axis on a short run of
1827            // `v` (a plane through the centre, tilted a little) takes a step per
1828            // half scan step of `u` its branches sweep.
1829            let len = ((t_hi - t_lo) / step).ceil();
1830            let probes = (len as usize).max(8);
1831            let (u_lo, u_hi) = (0..=probes)
1832                .map(|k| (t_hi - t_lo).madd(k as f64 / probes as f64, t_lo))
1833                .map(|v| self.rhs(v).clamp(-1.0, 1.0).acos())
1834                .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), u| {
1835                    (lo.min(u), hi.max(u))
1836                });
1837            let m = len
1838                .max((n_v as f64) * (u_hi - u_lo) / std::f64::consts::PI)
1839                .max(fewest)
1840                .min(most)
1841                .ceil();
1842            let steps = m as usize;
1843            if let Some(v_node) = at_node {
1844                // Out along one branch from the node to a turn and back along
1845                // the other, once each side of the node.
1846                for (from, to) in [(v_node, t_lo), (v_node, t_hi)] {
1847                    let along = |k: usize| {
1848                        let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1849                        (to - from).madd(f, from)
1850                    };
1851                    let mut pts = vec![self.node(v_node)];
1852                    pts.extend((1..=steps).map(|k| self.branch(along(k), 1.0)));
1853                    pts.extend((1..steps).rev().map(|k| self.branch(along(k), -1.0)));
1854                    loops.push(closed(pts));
1855                }
1856            } else {
1857                let at = |k: usize| {
1858                    let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1859                    (t_hi - t_lo).madd(f, t_lo)
1860                };
1861                let mut pts: Vec<IntersectionPoint> =
1862                    (0..=steps).map(|k| self.branch(at(k), 1.0)).collect();
1863                pts.extend((1..steps).rev().map(|k| self.branch(at(k), -1.0)));
1864                loops.push(closed(pts));
1865            }
1866        }
1867        loops
1868    }
1869
1870    /// The section's point halfway in `v` between two of its points, given
1871    /// by their `(u, v)` on the torus, on the branch nearer their middle `u`.
1872    fn between(&self, a: (f64, f64), b: (f64, f64)) -> IntersectionPoint {
1873        let half = |from: f64, to: f64| {
1874            let gap = (to - from + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
1875            0.5_f64.madd(gap, from)
1876        };
1877        let (u, v) = (half(a.0, b.0), half(a.1, b.1));
1878        let off = self.rhs(v).clamp(-1.0, 1.0).acos();
1879        let miss =
1880            |w: f64| ((w - u + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI).abs();
1881        let sign = if miss(self.phi + off) <= miss(self.phi - off) {
1882            1.0
1883        } else {
1884            -1.0
1885        };
1886        self.branch(v, sign)
1887    }
1888}
1889
1890/// The two sections of a plane that crosses every tube cross-section of a
1891/// torus twice (one parallel to the axis within `R − r` of it, or tilted a
1892/// little from that): both branches `u = phi ± acos(rhs(v))` of
1893/// [`plane_torus_loops`] are then defined for every `v`, so each closes
1894/// into a loop that winds once around the tube. Sampled at `n_v` steps from
1895/// `v = 0`, the outer equator, so every such loop on a torus starts on one
1896/// latitude, as the tube cross-sections of a plane through the axis do.
1897/// `None` when a branch lapses somewhere or the two come close to meeting.
1898#[allow(clippy::cast_precision_loss)]
1899fn plane_torus_winding_loops(
1900    torus: &ToroidalSurface,
1901    normal: Vec3,
1902    d: f64,
1903    n_v: usize,
1904) -> Option<Vec<Vec<Point3>>> {
1905    let big_r = torus.major_radius();
1906    let small_r = torus.minor_radius();
1907    let a = normal.dot(torus.x_axis());
1908    let b = normal.dot(torus.y_axis());
1909    let c = normal.dot(torus.z_axis());
1910    let s = a.hypot(b);
1911    if s < 1e-12 * normal.length() || small_r >= big_r {
1912        return None;
1913    }
1914    let phi = b.atan2(a);
1915    let d_local = d - dot_np(normal, torus.center());
1916    let rhs = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.madd(v.cos(), big_r));
1917    let dense = 8 * n_v;
1918    if (0..dense).any(|i| rhs(TAU * i as f64 / dense as f64).abs() > 1.0 - 1e-3) {
1919        return None;
1920    }
1921    let mut loops = [Vec::with_capacity(n_v + 1), Vec::with_capacity(n_v + 1)];
1922    for i in 0..n_v {
1923        let v = TAU * i as f64 / n_v as f64;
1924        let delta = rhs(v).acos();
1925        loops[0].push(torus.evaluate(phi + delta, v));
1926        loops[1].push(torus.evaluate(phi - delta, v));
1927    }
1928    Some(
1929        loops
1930            .into_iter()
1931            .map(|mut run| {
1932                run.push(run[0]);
1933                run
1934            })
1935            .collect(),
1936    )
1937}
1938
1939/// Real intersection parameters `t` of the line `origin + t·dir` with a torus.
1940///
1941/// A line meets a torus in up to four points (degree-4). Substituting the line
1942/// into the torus implicit `(a² + b² + c² + R² − r²)² = 4R²(a² + b²)` — where
1943/// `(a, b, c)` are the line point's coordinates in the torus frame — gives a
1944/// quartic in `t`, solved here for its real roots, each refined by Newton steps
1945/// on the tube it lies nearer (on a spindle torus, the near tube or the one
1946/// swung across the axis). `dir` need not be unit length; `t` is in units of
1947/// `dir`. Returns the roots sorted ascending (0–4 of them).
1948///
1949/// Used by the boolean section trimmer to find where a plane×torus oval exits a
1950/// box face's straight boundary edge — the exact crossing shared by the two
1951/// adjacent faces, which is what makes the notch watertight.
1952#[must_use]
1953pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1954    let c = torus.center();
1955    let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1956    let big_r = torus.major_radius();
1957    let small_r = torus.minor_radius();
1958
1959    // Line point in torus frame: a(t)=a0+a1 t, b(t)=b0+b1 t, c(t)=c0+c1 t.
1960    let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1961    let (a0, a1) = (xa.dot(o), xa.dot(dir));
1962    let (b0, b1) = (ya.dot(o), ya.dot(dir));
1963    let (c0, c1) = (za.dot(o), za.dot(dir));
1964
1965    // G(t) = a² + b² + c² + R² − r²  (quadratic: g2 t² + g1 t + g0)
1966    let g2 = a1.madd(a1, b1.madd(b1, c1 * c1));
1967    let g1 = 2.0 * a1.madd(a0, b1.madd(b0, c1 * c0));
1968    let g0 = a0.madd(
1969        a0,
1970        b0.madd(b0, c0.madd(c0, big_r.madd(big_r, -small_r * small_r))),
1971    );
1972
1973    // H(t) = 4R² (a² + b²)  (quadratic: h2 t² + h1 t + h0)
1974    let four_rr = 4.0 * big_r * big_r;
1975    let h2 = four_rr * a1.madd(a1, b1 * b1);
1976    let h1 = four_rr * (2.0 * a1.madd(a0, b1 * b0));
1977    let h0 = four_rr * a0.madd(a0, b0 * b0);
1978
1979    // Quartic G² − H = 0:  e4 t⁴ + e3 t³ + e2 t² + e1 t + e0.
1980    let e4 = g2 * g2;
1981    let e3 = 2.0 * g2 * g1;
1982    let e2 = g1.madd(g1, 2.0 * g2 * g0) - h2;
1983    let e1 = 2.0f64.madd(g1 * g0, -h1);
1984    let e0 = g0.madd(g0, -h0);
1985
1986    let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1987    // The quartic also holds a spindle torus's tube swung across the axis
1988    // (`G = -sqrt(H)`), whose roots pair up with the tube's own a few hundredths
1989    // apart when `R` is small: the solver leaves them loose, and polishing one
1990    // against the near tube carries it beside the other root. Each root is
1991    // polished on the tube it lies nearer.
1992    let tube = |t: f64, across: bool| -> f64 {
1993        let p = origin + dir * t;
1994        let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1995        let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1996        let centre = if across { -big_r } else { big_r };
1997        (a.hypot(b) - centre).hypot(cc) - small_r
1998    };
1999    for t in &mut roots {
2000        let across = big_r < small_r && tube(*t, true).abs() < tube(*t, false).abs();
2001        for _ in 0..8 {
2002            let eps = 1e-7;
2003            let f = tube(*t, across);
2004            let df = (tube(*t + eps, across) - tube(*t - eps, across)) / (2.0 * eps);
2005            if df.abs() <= 1e-12 {
2006                break;
2007            }
2008            let step = f / df;
2009            *t -= step;
2010            if step.abs() < 1e-14 * (1.0 + t.abs()) {
2011                break;
2012            }
2013        }
2014    }
2015    roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
2016    roots.dedup_by(|a, b| (*a - *b).abs() < 1e-9 * (1.0 + b.abs()));
2017    roots
2018}
2019
2020/// Real roots of `c4 x⁴ + c3 x³ + c2 x² + c1 x + c0` via Durand–Kerner, falling
2021/// back to the lower-degree solvers when the leading coefficients vanish.
2022fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
2023    // Degenerate leading coefficient → lower degree.
2024    if c4.abs() < 1e-14 {
2025        return real_roots_cubic(c3, c2, c1, c0);
2026    }
2027    // Monic: x⁴ + a x³ + b x² + c x + d.
2028    let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
2029    let eval = |z: Complex| -> Complex {
2030        // Horner.
2031        let mut acc = Complex::new(1.0, 0.0);
2032        acc = acc * z + Complex::new(a, 0.0);
2033        acc = acc * z + Complex::new(b, 0.0);
2034        acc = acc * z + Complex::new(c, 0.0);
2035        acc * z + Complex::new(d, 0.0)
2036    };
2037    // Durand–Kerner: four roots seeded on a circle, iterated to convergence.
2038    let seed = Complex::new(0.4, 0.9);
2039    let mut r = [
2040        Complex::new(1.0, 0.0),
2041        seed,
2042        seed * seed,
2043        seed * seed * seed,
2044    ];
2045    for _ in 0..100 {
2046        let mut max_step = 0.0_f64;
2047        for i in 0..4 {
2048            let mut denom = Complex::new(1.0, 0.0);
2049            for j in 0..4 {
2050                if i != j {
2051                    denom = denom * (r[i] - r[j]);
2052                }
2053            }
2054            if denom.norm() < 1e-300 {
2055                continue;
2056            }
2057            let step = eval(r[i]) / denom;
2058            r[i] = r[i] - step;
2059            max_step = max_step.max(step.norm());
2060        }
2061        if max_step < 1e-14 {
2062            break;
2063        }
2064    }
2065    // Keep roots with negligible imaginary part AND a small REAL-polynomial
2066    // residual — Durand–Kerner stops after a fixed iteration cap whether or not
2067    // it converged, so a non-converged iterate could otherwise be returned as a
2068    // spurious root. Evaluate the monic quartic at each candidate (real part) and
2069    // keep only |p(x)| below a magnitude-scaled tolerance; de-dup near-equal
2070    // roots (a double root converges to two near-identical iterates).
2071    let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
2072    let mut out: Vec<f64> = Vec::new();
2073    for z in r {
2074        if z.im.abs() >= 1e-7 {
2075            continue;
2076        }
2077        let x = z.re;
2078        // Residual tolerance scales with the polynomial's coefficient magnitude
2079        // and |x|^4 so large-coefficient quartics are not over-rejected.
2080        let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
2081        if p_real(x).abs() > 1e-6 * scale {
2082            continue;
2083        }
2084        if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
2085            continue;
2086        }
2087        out.push(x);
2088    }
2089    out
2090}
2091
2092/// Real roots of `a x³ + b x² + c x + d` (Cardano), with quadratic fallback.
2093fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
2094    if a.abs() < 1e-14 {
2095        return real_roots_quadratic(b, c, d);
2096    }
2097    // Depressed cubic t³ + p t + q via x = t − b/(3a).
2098    let (b, c, d) = (b / a, c / a, d / a);
2099    let p = c - b * b / 3.0;
2100    let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
2101    let shift = -b / 3.0;
2102    let disc = q * q / 4.0 + p * p * p / 27.0;
2103    if disc > 1e-14 {
2104        let sq = disc.sqrt();
2105        let u = (-q / 2.0 + sq).cbrt();
2106        let v = (-q / 2.0 - sq).cbrt();
2107        vec![u + v + shift]
2108    } else if disc < -1e-14 {
2109        // Three real roots (trigonometric).
2110        let m = 2.0 * (-p / 3.0).sqrt();
2111        let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
2112        (0..3)
2113            .map(|k| {
2114                m.madd(
2115                    (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
2116                    shift,
2117                )
2118            })
2119            .collect()
2120    } else {
2121        // Repeated roots.
2122        let u = (-q / 2.0).cbrt();
2123        vec![2.0 * u + shift, -u + shift]
2124    }
2125}
2126
2127/// Real roots of `a x² + b x + c`, with linear fallback.
2128fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
2129    if a.abs() < 1e-14 {
2130        if b.abs() < 1e-14 {
2131            return Vec::new();
2132        }
2133        return vec![-c / b];
2134    }
2135    let disc = b * b - 4.0 * a * c;
2136    if disc < 0.0 {
2137        Vec::new()
2138    } else {
2139        let sq = disc.sqrt();
2140        vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
2141    }
2142}
2143
2144/// Minimal complex number for the quartic root finder.
2145#[derive(Clone, Copy)]
2146struct Complex {
2147    re: f64,
2148    im: f64,
2149}
2150
2151impl Complex {
2152    const fn new(re: f64, im: f64) -> Self {
2153        Self { re, im }
2154    }
2155    fn norm(self) -> f64 {
2156        self.re.hypot(self.im)
2157    }
2158}
2159
2160impl std::ops::Add for Complex {
2161    type Output = Self;
2162    fn add(self, o: Self) -> Self {
2163        Self::new(self.re + o.re, self.im + o.im)
2164    }
2165}
2166
2167impl std::ops::Sub for Complex {
2168    type Output = Self;
2169    fn sub(self, o: Self) -> Self {
2170        Self::new(self.re - o.re, self.im - o.im)
2171    }
2172}
2173
2174impl std::ops::Mul for Complex {
2175    type Output = Self;
2176    fn mul(self, o: Self) -> Self {
2177        Self::new(
2178            self.re.madd(o.re, -(self.im * o.im)),
2179            self.re.madd(o.im, self.im * o.re),
2180        )
2181    }
2182}
2183
2184impl std::ops::Div for Complex {
2185    type Output = Self;
2186    fn div(self, o: Self) -> Self {
2187        let den = o.re.madd(o.re, o.im * o.im);
2188        Self::new(
2189            self.re.madd(o.re, self.im * o.im) / den,
2190            self.im.madd(o.re, -(self.re * o.im)) / den,
2191        )
2192    }
2193}
2194
2195/// Build intersection curves from a collection of ordered 3D points.
2196///
2197/// If there are enough points, fits a NURBS curve through them.
2198fn build_curves_from_points(
2199    points_3d: &[Point3],
2200    ipoints: Vec<IntersectionPoint>,
2201) -> Result<Vec<IntersectionCurve>, MathError> {
2202    if points_3d.len() < 2 {
2203        return Ok(vec![]);
2204    }
2205
2206    let degree = 3.min(points_3d.len() - 1);
2207    let curve = interpolate(points_3d, degree)?;
2208    Ok(vec![IntersectionCurve {
2209        curve,
2210        points: ipoints,
2211    }])
2212}
2213
2214// -- Analytic-Analytic Intersection -------------------------------------------
2215
2216/// Intersect two analytic surfaces using a general marching approach.
2217///
2218/// Seeds intersection points by sampling both parameter spaces on a grid,
2219/// then marches along the intersection curve using the cross product of
2220/// the two surface normals as the tangent direction.
2221///
2222/// # Errors
2223///
2224/// Returns an error if curve fitting fails.
2225#[allow(
2226    clippy::cast_precision_loss,
2227    clippy::too_many_lines,
2228    clippy::similar_names,
2229    clippy::unnecessary_wraps,
2230    clippy::type_complexity
2231)]
2232pub fn intersect_analytic_analytic(
2233    a: AnalyticSurface<'_>,
2234    b: AnalyticSurface<'_>,
2235    grid_res: usize,
2236) -> Result<Vec<IntersectionCurve>, MathError> {
2237    intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
2238}
2239
2240/// Intersect two analytic surfaces with optional v-range overrides.
2241///
2242/// When `v_range_hint_a` or `v_range_hint_b` is `Some((min, max))`, the
2243/// marching algorithm searches that v-range instead of the hardcoded default.
2244/// This is essential for cylinders and cones whose default v-range is small
2245/// (-1..1 or 0.01..2) but whose actual face may extend much further.
2246///
2247/// # Errors
2248///
2249/// Returns `MathError` if algebraic intersection fails or marching diverges.
2250pub fn intersect_analytic_analytic_bounded(
2251    a: AnalyticSurface<'_>,
2252    b: AnalyticSurface<'_>,
2253    grid_res: usize,
2254    v_range_hint_a: Option<(f64, f64)>,
2255    v_range_hint_b: Option<(f64, f64)>,
2256) -> Result<Vec<IntersectionCurve>, MathError> {
2257    intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, None)
2258}
2259
2260/// [`intersect_analytic_analytic_bounded`] with its general marcher confined
2261/// to `region`.
2262///
2263/// The marcher starts only from seeds that converge into the region (with a
2264/// margin of about two grid cells) and stops where a curve leaves it. Pairs
2265/// solved in closed form are returned whole, as by the unconfined call. Two
2266/// bounded faces meet only inside both their boxes, so their overlap is a
2267/// sound region for a face pair.
2268///
2269/// # Errors
2270///
2271/// Returns `MathError` if algebraic intersection fails or marching diverges.
2272pub fn intersect_analytic_analytic_in_region(
2273    a: AnalyticSurface<'_>,
2274    b: AnalyticSurface<'_>,
2275    grid_res: usize,
2276    v_range_hint_a: Option<(f64, f64)>,
2277    v_range_hint_b: Option<(f64, f64)>,
2278    region: Aabb3,
2279) -> Result<Vec<IntersectionCurve>, MathError> {
2280    intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, Some(region))
2281}
2282
2283fn intersect_analytic_analytic_impl(
2284    a: AnalyticSurface<'_>,
2285    b: AnalyticSurface<'_>,
2286    grid_res: usize,
2287    v_range_hint_a: Option<(f64, f64)>,
2288    v_range_hint_b: Option<(f64, f64)>,
2289    region: Option<Aabb3>,
2290) -> Result<Vec<IntersectionCurve>, MathError> {
2291    // Try algebraic specialization for known surface pairs before falling
2292    // back to the general marching approach.
2293    if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
2294        return Ok(result);
2295    }
2296    marched_sections(a, b, grid_res, v_range_hint_a, v_range_hint_b, region)
2297}
2298
2299/// `x + y t` with one rounding, at the end: Dekker's split product and
2300/// Knuth's two-sum keep the rounding of `y t` and of the sum, and the last
2301/// addition rounds their total once.
2302fn add_product(x: f64, y: f64, t: f64) -> f64 {
2303    let split = |v: f64| {
2304        let c = 134_217_729.0 * v;
2305        let hi = c - (c - v);
2306        (hi, v - hi)
2307    };
2308    let p = y * t;
2309    let ((yh, yl), (th, tl)) = (split(y), split(t));
2310    let p_err = yl.madd(tl, yl.madd(th, yh.madd(tl, yh.madd(th, -p))));
2311    let s = x + p;
2312    let back = s - x;
2313    let s_err = (x - (s - back)) + (p - back);
2314    s + (s_err + p_err)
2315}
2316
2317/// An analytic surface moved by a vector, held while the marcher works on it.
2318enum Moved {
2319    Cylinder(CylindricalSurface),
2320    Cone(ConicalSurface),
2321    Sphere(SphericalSurface),
2322    Torus(ToroidalSurface),
2323}
2324
2325impl Moved {
2326    /// `surface` moved so that `anchor` lies at the origin, how far its `v`
2327    /// moved, and a bound on how far the move's rounding shifted it.
2328    ///
2329    /// A cylinder's frame, which can sit anywhere along its axis, goes to
2330    /// the point of the axis nearest `anchor`, so the surface reads alike
2331    /// wherever its frame sat, and its `v` drops by as much. That point is
2332    /// the old frame plus a multiple of the axis, each coordinate summed with
2333    /// one rounding at the end ([`add_product`]), so it lies within a float
2334    /// step of the axis however far the old frame sat: moved by plain sums,
2335    /// a frame 1e12 along a tilted axis landed 4.7e-6 off it. Each other
2336    /// surface's frame point (an apex or a centre) is fixed by its shape and
2337    /// moves by one subtraction, rounding each coordinate by up to half its
2338    /// float spacing.
2339    fn new(surface: &AnalyticSurface<'_>, anchor: Point3) -> (Self, f64, f64) {
2340        let size = |p: Point3| p.x().abs().max(p.y().abs()).max(p.z().abs());
2341        let shift = Point3::new(0.0, 0.0, 0.0) - anchor;
2342        match surface {
2343            AnalyticSurface::Cylinder(c) => {
2344                let (o, a) = (c.origin(), c.axis());
2345                let along = a.dot(anchor - o);
2346                let foot = Point3::new(
2347                    add_product(o.x(), a.x(), along),
2348                    add_product(o.y(), a.y(), along),
2349                    add_product(o.z(), a.z(), along),
2350                );
2351                let near = foot + shift;
2352                let error = 4.0 * f64::EPSILON * (size(foot) + size(near));
2353                (Self::Cylinder(c.framed_at(near)), along, error)
2354            }
2355            AnalyticSurface::Cone(c) => {
2356                let near = c.translated(shift);
2357                let error = 2.0 * f64::EPSILON * size(near.apex());
2358                (Self::Cone(near), 0.0, error)
2359            }
2360            AnalyticSurface::Sphere(s) => {
2361                let near = s.translated(shift);
2362                let error = 2.0 * f64::EPSILON * size(near.center());
2363                (Self::Sphere(near), 0.0, error)
2364            }
2365            AnalyticSurface::Torus(t) => {
2366                let near = t.translated(shift);
2367                let error = 2.0 * f64::EPSILON * size(near.center());
2368                (Self::Torus(near), 0.0, error)
2369            }
2370        }
2371    }
2372
2373    const fn surface(&self) -> AnalyticSurface<'_> {
2374        match self {
2375            Self::Cylinder(c) => AnalyticSurface::Cylinder(c),
2376            Self::Cone(c) => AnalyticSurface::Cone(c),
2377            Self::Sphere(s) => AnalyticSurface::Sphere(s),
2378            Self::Torus(t) => AnalyticSurface::Torus(t),
2379        }
2380    }
2381}
2382
2383/// The sections of `a` and `b` that the general marcher traces from seeds
2384/// on a grid over `a`, confined to `region` when one is given.
2385///
2386/// The marcher works with both surfaces moved by the same vector to the
2387/// middle of the region, or of `a`'s patch, each cylinder's frame moved
2388/// along its axis to there, and moves its curves back. Far
2389/// from the origin the spacing of floats in one coordinate would otherwise
2390/// decide whether a point lies on both surfaces and whether they cross
2391/// there, and a pair moved there would not read as it does near the origin:
2392/// a touch as a crossing, a shallow crossing as a touch. Moving a curve back
2393/// rounds each coordinate by up to half its spacing there, and moving each
2394/// surface shifts it by a bound [`Moved::new`] gives, so each fit is held
2395/// that much within the linear tolerance; where that leaves less than half
2396/// of it, a traced section is refused before its fit.
2397fn marched_sections(
2398    a: AnalyticSurface<'_>,
2399    b: AnalyticSurface<'_>,
2400    grid_res: usize,
2401    v_range_hint_a: Option<(f64, f64)>,
2402    v_range_hint_b: Option<(f64, f64)>,
2403    region: Option<Aabb3>,
2404) -> Result<Vec<IntersectionCurve>, MathError> {
2405    let size = |p: Point3| p.x().abs().max(p.y().abs()).max(p.z().abs());
2406    let (anchor, reach) = if let Some(r) = region {
2407        (r.min + (r.max - r.min) * 0.5, (r.max - r.min).length())
2408    } else {
2409        let (surf_a, _, (u0, u1), default_v_a) = surface_closures(&a);
2410        let (v0, v1) = v_range_hint_a.unwrap_or(default_v_a);
2411        let (first, last) = (surf_a(u0, v0), surf_a(u1, v1));
2412        let reach = patch_diagonal(surf_a.as_ref(), (u0, u1), (v0, v1));
2413        (first + (last - first) * 0.5, reach)
2414    };
2415    let shift = anchor - Point3::new(0.0, 0.0, 0.0);
2416    let ((near_a, dv_a, moved_a), (near_b, dv_b, moved_b)) =
2417        (Moved::new(&a, anchor), Moved::new(&b, anchor));
2418    let v_range = |surface: &AnalyticSurface<'_>, hint: Option<(f64, f64)>, dv: f64| {
2419        let (lo, hi) = hint.unwrap_or_else(|| surface_closures(surface).3);
2420        Some((lo - dv, hi - dv))
2421    };
2422    let linear = Tolerance::new().linear;
2423    let fit_tol =
2424        ((-f64::EPSILON).madd(size(anchor) + reach, linear) - moved_a - moved_b).min(linear);
2425    let near_region = region.map(|r| Aabb3 {
2426        min: r.min - shift,
2427        max: r.max - shift,
2428    });
2429    let curves = marched_sections_near(
2430        near_a.surface(),
2431        near_b.surface(),
2432        grid_res,
2433        v_range(&a, v_range_hint_a, dv_a),
2434        v_range(&b, v_range_hint_b, dv_b),
2435        near_region,
2436        fit_tol,
2437    )?;
2438    curves
2439        .into_iter()
2440        .map(|c| {
2441            let ctrl = c
2442                .curve
2443                .control_points()
2444                .iter()
2445                .map(|&p| p + shift)
2446                .collect();
2447            let curve = NurbsCurve::new(
2448                c.curve.degree(),
2449                c.curve.knots().to_vec(),
2450                ctrl,
2451                c.curve.weights().to_vec(),
2452            )?;
2453            let points = c
2454                .points
2455                .into_iter()
2456                .map(|ip| IntersectionPoint {
2457                    point: ip.point + shift,
2458                    ..ip
2459                })
2460                .collect();
2461            Ok(IntersectionCurve { curve, points })
2462        })
2463        .collect()
2464}
2465
2466/// [`marched_sections`] on surfaces near the origin, each fit held within
2467/// `fit_tol` of both surfaces. A traced section is refused before its fit
2468/// where `fit_tol` is less than half the linear tolerance.
2469#[allow(clippy::too_many_lines, clippy::similar_names)]
2470fn marched_sections_near(
2471    a: AnalyticSurface<'_>,
2472    b: AnalyticSurface<'_>,
2473    grid_res: usize,
2474    v_range_hint_a: Option<(f64, f64)>,
2475    v_range_hint_b: Option<(f64, f64)>,
2476    region: Option<Aabb3>,
2477    fit_tol: f64,
2478) -> Result<Vec<IntersectionCurve>, MathError> {
2479    let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
2480    let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
2481    let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
2482    let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
2483
2484    // Compute characteristic surface dimensions for adaptive parameters.
2485    let diag_a = patch_diagonal(surf_a.as_ref(), u_range_a, v_range_a);
2486    let diag_b = patch_diagonal(surf_b.as_ref(), u_range_b, v_range_b);
2487    let char_size = diag_a.min(diag_b).max(0.1);
2488
2489    let march_step = (char_size * 0.02).clamp(0.005, 0.5);
2490    let meet = region;
2491    #[allow(clippy::cast_precision_loss)]
2492    let margin = 2.0 * char_size / grid_res as f64;
2493    let region = region.map(|r| r.expanded(margin));
2494
2495    // Seeds: the middle of each cell of a grid over a patch whose distance
2496    // from the other surface is within the cell's reach from its middle (see
2497    // [`cell_reach`]), and the box of those cells. Every point of the section
2498    // lies in a cell of each patch, no farther from its middle than that, so
2499    // each cell it crosses gives a seed. A cell whose distance or reach
2500    // cannot be read (its middle on the other surface's axis, centre or apex)
2501    // may hold the section: it is kept, its middle its seed, and where its
2502    // reach is unknown its box is all of space.
2503    let cells = |surface: &AnalyticSurface<'_>,
2504                 surf: &dyn Fn(f64, f64) -> Point3,
2505                 (u_range, v_range): ((f64, f64), (f64, f64)),
2506                 other: &AnalyticSurface<'_>,
2507                 near: Option<Aabb3>| {
2508        #[allow(clippy::cast_precision_loss)]
2509        let n = grid_res as f64;
2510        let (du, dv) = ((u_range.1 - u_range.0) / n, (v_range.1 - v_range.0) / n);
2511        let mut found = Vec::new();
2512        let mut kept = Vec::new();
2513        let mut held: Option<Aabb3> = None;
2514        for i in 0..grid_res {
2515            for j in 0..grid_res {
2516                #[allow(clippy::cast_precision_loss)]
2517                let (u, v) = (
2518                    du.madd(i as f64 + 0.5, u_range.0),
2519                    dv.madd(j as f64 + 0.5, v_range.0),
2520                );
2521                let middle = surf(u, v);
2522                let reach = cell_reach(surface, (0.5 * du, 0.5 * dv), v);
2523                let placed = reach.is_finite()
2524                    && middle.x().is_finite()
2525                    && middle.y().is_finite()
2526                    && middle.z().is_finite();
2527                if placed && near.is_some_and(|r| !r.expanded(reach).contains_point(middle)) {
2528                    continue;
2529                }
2530                let reading = section_fit::Carrier::distance(other, middle)
2531                    .filter(|(d, n)| d.is_finite() && n.length().is_finite());
2532                // The rounding of the distance, so a cell is dropped only
2533                // where it surely holds no point of the other surface.
2534                let slack = || {
2535                    let size = middle.x().abs().max(middle.y().abs()).max(middle.z().abs());
2536                    128.0
2537                        * f64::EPSILON
2538                        * (section_fit::Carrier::scale(surface, middle)
2539                            + section_fit::Carrier::scale(other, middle)
2540                            + size)
2541                };
2542                let (dist, seed) = match reading {
2543                    Some((d, _))
2544                        if placed
2545                            && d.abs() > reach
2546                            && (d.abs() > 2.0 * reach || d.abs() - slack() > reach) =>
2547                    {
2548                        continue;
2549                    }
2550                    Some((d, n)) => (d.abs(), middle - n * (0.5 * d)),
2551                    None => (f64::INFINITY, middle),
2552                };
2553                found.push((dist, seed));
2554                kept.push((i, j));
2555                let cell = if placed {
2556                    Aabb3 {
2557                        min: middle,
2558                        max: middle,
2559                    }
2560                    .expanded(reach)
2561                } else {
2562                    Aabb3 {
2563                        min: Point3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2564                        max: Point3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2565                    }
2566                };
2567                held = Some(held.map_or(cell, |h| h.union(cell)));
2568            }
2569        }
2570        (found, held, kept)
2571    };
2572    let (mut candidates, held, kept_a) =
2573        cells(&a, surf_a.as_ref(), (u_range_a, v_range_a), &b, region);
2574
2575    // With no seed on A, no point of the section lies on A's patch. A test
2576    // on the nearest cell's distance to B against three cells of the smaller
2577    // patch's size read a rod's shallow crossing of a cone's patch, whose
2578    // cells are each 4900 across, as no crossing.
2579    let Some(held) = held else {
2580        return Ok(vec![]);
2581    };
2582    // The seeds below come from cells' middles, and a cell's seed settles
2583    // on one curve: a second loop in the same cells of both patches had
2584    // none. Cut A's kept cells until each is proved to hold no point of
2585    // the section, or at most one arc of it, or is too small for a fit to
2586    // resolve (see [`cover::Cover`]). Each class of linked cells holds one
2587    // arc of a part of the section: after the march, a marched point lies
2588    // in it, or a seed from it settles on a marched curve or starts a march.
2589    let mut cover = cover::Cover::new(
2590        &a,
2591        &b,
2592        (u_range_a, v_range_a),
2593        v_range_b,
2594        grid_res,
2595        &kept_a,
2596        meet.zip(region),
2597        Tolerance::new().linear,
2598        cover::MOST_LEAVES,
2599    );
2600    // Where the cuts did not all settle, two loops in one cell of one patch
2601    // can lie in two cells of the other, which lie within their reach of
2602    // A's seeds' cells.
2603    if !cover.complete() {
2604        candidates.extend(cells(&b, surf_b.as_ref(), (u_range_b, v_range_b), &a, Some(held)).0);
2605    }
2606    candidates.sort_by(|p, q| p.0.total_cmp(&q.0));
2607
2608    // A seed is only near the intersection; settle it onto the curve before
2609    // asking whether it lies in the region, so a coarse grid point beside a
2610    // short in-region span still starts its march, and march from there, so
2611    // the march does not begin outside the region and stop at once. The
2612    // projections from one surface to the other also settle where the two
2613    // pass closest without meeting, with both normals along the gap: a
2614    // seed there lies on no curve, and a march from it never closes on it.
2615    // Nor does a seed where the two surfaces touch without crossing (their
2616    // normals within about 1e-6 of parallel): the section there can be a
2617    // lone point, and no direction along it is defined.
2618    let settle = |mid: Point3| {
2619        let on = settle_on_section(&a, &b, mid).or_else(|| {
2620            let mut p = mid;
2621            for _ in 0..8 {
2622                let (ua, va) = project_analytic(&a, p, u_range_a, v_range_a);
2623                let pa = surf_a(ua, va);
2624                let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2625                let pb = surf_b(ub, vb);
2626                p = Point3::new(
2627                    (pa.x() + pb.x()) * 0.5,
2628                    (pa.y() + pb.y()) * 0.5,
2629                    (pa.z() + pb.z()) * 0.5,
2630                );
2631                if (pa - pb).length() < 1e-9 {
2632                    break;
2633                }
2634            }
2635            settle_on_section(&a, &b, p)
2636        });
2637        // The steps settle on the section of the whole surfaces, which can
2638        // lie on a part neither patch holds (a cone's other nappe).
2639        let near_patches = |q: Point3| {
2640            let (ua, va) = project_analytic(&a, q, u_range_a, v_range_a);
2641            let (ub, vb) = project_analytic(&b, q, u_range_b, v_range_b);
2642            (q - surf_a(ua, va)).length() <= march_step
2643                && (q - surf_b(ub, vb)).length() <= march_step
2644        };
2645        let Some(on) = on.filter(|&on| {
2646            crosses_at(&a, &b, on)
2647                && near_patches(on)
2648                && region.is_none_or(|r| r.contains_point(on))
2649        }) else {
2650            return Ok(None);
2651        };
2652        // A crossing whose curvature cannot be read cannot be marched; the
2653        // section is refused, not traced without it.
2654        station(&a, &b, on, Vec3::new(0.0, 0.0, 0.0))
2655            .map(Some)
2656            .ok_or(MathError::ConvergenceFailure { iterations: 0 })
2657    };
2658    let off_patch = |q: Point3| {
2659        let (ua, va) = project_analytic(&a, q, u_range_a, v_range_a);
2660        let (ub, vb) = project_analytic(&b, q, u_range_b, v_range_b);
2661        (!is_u_periodic(&a) && (ua <= u_range_a.0 || ua >= u_range_a.1))
2662            || va <= v_range_a.0
2663            || va >= v_range_a.1
2664            || (!is_u_periodic(&b) && (ub <= u_range_b.0 || ub >= u_range_b.1))
2665            || vb <= v_range_b.0
2666            || vb >= v_range_b.1
2667    };
2668
2669    // March from each seed, nearest first, unless it settles on a curve
2670    // already marched. Seeds on both patches march first: one just past a
2671    // patch's edge marches along a curve that one inside may already have
2672    // marched, which its middle then lies on.
2673    // March from a seed on the section and fit what the march traces,
2674    // unless its middle lies on a curve already marched. The march's points
2675    // where its branch is then marched, `None` where it traces no curve. A
2676    // march is kept among the marched only with its curve: a march with no
2677    // curve reaches no part of the section.
2678    let trace = |seed: Point3,
2679                 marched: &mut Vec<Vec<Point3>>,
2680                 curves: &mut Vec<IntersectionCurve>|
2681     -> Result<Option<Vec<Point3>>, MathError> {
2682        let march_result = march_analytic_intersection(
2683            &a,
2684            &b,
2685            surf_a.as_ref(),
2686            norm_a.as_ref(),
2687            surf_b.as_ref(),
2688            norm_b.as_ref(),
2689            seed,
2690            u_range_a,
2691            v_range_a,
2692            u_range_b,
2693            v_range_b,
2694            march_step,
2695            is_u_periodic(&a),
2696            is_u_periodic(&b),
2697            region,
2698        )
2699        .ok_or(MathError::ConvergenceFailure {
2700            iterations: MARCH_STEPS,
2701        })?;
2702        if march_result.len() < 2 {
2703            return Ok(None);
2704        }
2705        let middle = march_result[march_result.len() / 2];
2706        if marched.iter().any(|m| on_march(&a, &b, middle, m)) {
2707            return Ok(Some(march_result));
2708        }
2709
2710        // Two points far closer than a step only crowd the fit.
2711        let crowd = 1e-3 * march_step;
2712        let mut spaced: Vec<Point3> = Vec::with_capacity(march_result.len());
2713        for (k, &p) in march_result.iter().enumerate() {
2714            let last = k + 1 == march_result.len();
2715            match spaced.last() {
2716                Some(&q) if (p - q).length() < crowd => {
2717                    if last && spaced.len() > 1 {
2718                        spaced.pop();
2719                        spaced.push(p);
2720                    }
2721                }
2722                _ => spaced.push(p),
2723            }
2724        }
2725        if spaced.len() < 2 {
2726            // A march shorter than that, clipped to a short piece of the
2727            // section, keeps both its ends.
2728            match (march_result.first(), march_result.last()) {
2729                (Some(&first), Some(&last)) if (last - first).length() > 0.0 => {
2730                    spaced = vec![first, last];
2731                }
2732                _ => return Ok(None),
2733            }
2734        }
2735        if fit_tol < 0.5 * Tolerance::new().linear {
2736            return Err(MathError::ConvergenceFailure { iterations: 0 });
2737        }
2738        let (curve, points) = fit_section(&a, &b, &spaced, fit_tol)?;
2739        let ipts: Vec<IntersectionPoint> = points
2740            .iter()
2741            .map(|&pt| IntersectionPoint {
2742                point: pt,
2743                param1: (0.0, 0.0),
2744                param2: (0.0, 0.0),
2745            })
2746            .collect();
2747        marched.push(march_result.clone());
2748        curves.push(IntersectionCurve {
2749            curve,
2750            points: ipts,
2751        });
2752        Ok(Some(march_result))
2753    };
2754
2755    let mut curves = Vec::new();
2756    let mut marched: Vec<Vec<Point3>> = Vec::new();
2757    let mut past_edges = Vec::new();
2758    let mut k = 0;
2759    while k < candidates.len() + past_edges.len() {
2760        let seed = if k < candidates.len() {
2761            let mid = candidates[k].1;
2762            k += 1;
2763            let Some(seed) = settle(mid)? else {
2764                continue;
2765            };
2766            if off_patch(seed.p) {
2767                past_edges.push(seed);
2768                continue;
2769            }
2770            seed
2771        } else {
2772            k += 1;
2773            past_edges[k - 1 - candidates.len()]
2774        };
2775        if marched.iter().any(|m| on_march(&a, &b, seed.p, m)) {
2776            continue;
2777        }
2778        trace(seed.p, &mut marched, &mut curves)?;
2779    }
2780
2781    for m in &marched {
2782        cover.mark_marched(m);
2783    }
2784    let (marched, curves) = (RefCell::new(marched), RefCell::new(curves));
2785    // A probe whose nearest point on a fitted curve lies, as near as that
2786    // fit's bound, on the class's arc. Near a node a march from the probe
2787    // itself can stall.
2788    let fitted = |cover: &cover::Cover<'_, '_>, class: &[usize], z: Point3| {
2789        curves.borrow().iter().any(|c| {
2790            crate::nurbs::projection::project_point_to_curve(&c.curve, z, 1e-12)
2791                .is_ok_and(|f| cover.holds(class, f.point, fit_tol))
2792        })
2793    };
2794    // A probe settled on the section, on a marched branch or marched from.
2795    let mut seed = |z: Point3| -> Result<Option<Vec<Point3>>, MathError> {
2796        let Some(seed) = settle(z)? else {
2797            return Ok(None);
2798        };
2799        if marched.borrow().iter().any(|m| on_march(&a, &b, seed.p, m)) {
2800            return Ok(Some(vec![seed.p]));
2801        }
2802        let traced = trace(seed.p, &mut marched.borrow_mut(), &mut curves.borrow_mut())?;
2803        Ok(Some(traced.unwrap_or_default()))
2804    };
2805    // Where the cuts did not all settle, the cover proves nothing, and the
2806    // two patches' seeds above stand as they are.
2807    while cover.complete() {
2808        let classes = cover.classes();
2809        if classes.is_empty() {
2810            break;
2811        }
2812        for class in classes {
2813            cover.resolve(&class, &fitted, &mut seed)?;
2814        }
2815    }
2816
2817    Ok(curves.into_inner())
2818}
2819
2820/// How far a point of the patch of `surface` within `du` and `dv` of
2821/// parameter from `(u, v)` can lie from that point: the steps times the
2822/// greatest rates at which the surface moves with each parameter there.
2823fn cell_reach(surface: &AnalyticSurface<'_>, (du, dv): (f64, f64), v: f64) -> f64 {
2824    match surface {
2825        AnalyticSurface::Cylinder(c) => du.madd(c.radius(), dv),
2826        AnalyticSurface::Cone(c) => (du * c.half_angle().cos()).madd(v.abs() + dv, dv),
2827        AnalyticSurface::Sphere(s) => (du + dv) * s.radius(),
2828        AnalyticSurface::Torus(t) => {
2829            du.madd(t.major_radius() + t.minor_radius(), dv * t.minor_radius())
2830        }
2831    }
2832}
2833
2834/// Whether `p`, a point of the section of `a` and `b`, lies on the branch
2835/// a march traced through `points`. The chord of the march nearest `p` must
2836/// pass no farther from it than a fifth of its length, four times the sag
2837/// of an arc that turns as far as a step may (twice [`MARCH_TURN`]). From
2838/// that chord's nearest point, Newton steps move onto the section and along
2839/// its tangent toward `p`, each on the sheets `p` and the chord's ends lie
2840/// on (a cone's nappe, a torus's tube): `p` lies on the branch where they
2841/// come within the linear tolerance of it. A point of another branch,
2842/// however near the chord (another nappe 1e-4 away), stays that far from
2843/// where they settle.
2844fn on_march(
2845    a: &AnalyticSurface<'_>,
2846    b: &AnalyticSurface<'_>,
2847    p: Point3,
2848    points: &[Point3],
2849) -> bool {
2850    use section_fit::Carrier;
2851    let nearest = points
2852        .windows(2)
2853        .map(|w| {
2854            let chord = w[1] - w[0];
2855            let len2 = chord.dot(chord);
2856            let s = if len2 > 0.0 {
2857                ((p - w[0]).dot(chord) / len2).clamp(0.0, 1.0)
2858            } else {
2859                0.0
2860            };
2861            let foot = w[0] + chord * s;
2862            ((p - foot).length(), len2.sqrt(), foot, w)
2863        })
2864        .min_by(|x, y| x.0.total_cmp(&y.0));
2865    let Some((off, len, foot, w)) = nearest else {
2866        return false;
2867    };
2868    let sheets = |q: Point3| (a.sheet(q), b.sheet(q));
2869    if off > MARCH_TURN * len || sheets(w[0]) != sheets(p) || sheets(w[1]) != sheets(p) {
2870        return false;
2871    }
2872    let tol = Tolerance::new().linear;
2873    let mut guess = foot;
2874    for _ in 0..8 {
2875        let Some(q) = settle_on_section(a, b, guess) else {
2876            return false;
2877        };
2878        if sheets(q) != sheets(p) {
2879            return false;
2880        }
2881        let miss = p - q;
2882        if miss.length() <= tol {
2883            return true;
2884        }
2885        let (Some((_, na)), Some((_, nb))) = (a.distance(q), b.distance(q)) else {
2886            return false;
2887        };
2888        let t = na.cross(nb);
2889        let sin = t.length();
2890        if sin <= 0.0 {
2891            return false;
2892        }
2893        let t = t * (1.0 / sin);
2894        guess = q + t * miss.dot(t);
2895    }
2896    false
2897}
2898
2899/// The diagonal of the patch `surf` spans over `u_range` by `v_range`: the
2900/// chord between its first and last corners, or, for a patch closed both
2901/// ways (a whole torus, whose last corner is its first), the chord from its
2902/// first corner to its middle.
2903fn patch_diagonal(
2904    surf: &dyn Fn(f64, f64) -> Point3,
2905    (u0, u1): (f64, f64),
2906    (v0, v1): (f64, f64),
2907) -> f64 {
2908    let corner = (surf(u0, v0) - surf(u1, v1)).length();
2909    let middle = (surf(u0, v0) - surf(f64::midpoint(u0, u1), f64::midpoint(v0, v1))).length();
2910    if corner > 1e-9 * middle {
2911        corner
2912    } else {
2913        middle
2914    }
2915}
2916
2917/// Try algebraic (closed-form or semi-algebraic) intersection for known
2918/// surface pairs before falling back to general marching.
2919///
2920/// Returns `Some(curves)` if a specialized method exists, `None` otherwise.
2921///
2922/// Currently handles:
2923/// - **Sphere-sphere**: intersection is a circle (plane through the two centers)
2924/// - **Coaxial cylinders**: same axis → circle(s) or empty
2925/// - **Sphere-cylinder**: reduce to quadratic in one parameter
2926/// - **Cone-cylinder**: parallel axes in the cone's own `v`, other axes
2927///   along the cylinder's rulings
2928/// - **Cone-sphere**: off the cone's axis, along the cone's generators
2929/// - **Torus-cylinder**: along the cylinder's rulings
2930#[allow(clippy::too_many_lines)]
2931fn try_algebraic_intersection(
2932    a: &AnalyticSurface<'_>,
2933    b: &AnalyticSurface<'_>,
2934    v_range_a: Option<(f64, f64)>,
2935    v_range_b: Option<(f64, f64)>,
2936) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2937    match (a, b) {
2938        (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => Ok(
2939            algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)?
2940                .or_else(|| ruling_cone_cylinder(cone, cyl, true)),
2941        ),
2942        (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => Ok(
2943            algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)?
2944                .or_else(|| ruling_cone_cylinder(cone, cyl, false)),
2945        ),
2946        (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
2947            algebraic_sphere_sphere(s1, s2).map(Some)
2948        }
2949        (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
2950            let axis_dot = c1.axis().dot(c2.axis()).abs();
2951            if axis_dot > 1.0 - 1e-10 {
2952                // Axes are parallel — check if they're the same line.
2953                let delta = c2.origin() - c1.origin();
2954                let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2955                let along = delta_vec.dot(c1.axis());
2956                let perp = (delta_vec - c1.axis() * along).length();
2957                if perp < 1e-8 {
2958                    // Coaxial: same axis, different radii → no intersection
2959                    // (unless equal radius → degenerate overlap, skip)
2960                    if (c1.radius() - c2.radius()).abs() < 1e-8 {
2961                        return Ok(None); // Overlapping — let marcher handle
2962                    }
2963                    return Ok(Some(vec![])); // Coaxial, different radii
2964                }
2965                if let Some(rulings) = parallel_cylinders(c1, c2, v_range_a, v_range_b)? {
2966                    return Ok(Some(rulings));
2967                }
2968            }
2969            // Non-coaxial: algebraic quadratic in v.
2970            algebraic_cylinder_cylinder(c1, c2)
2971        }
2972        // Sphere-cylinder (both orderings).
2973        (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c)) => {
2974            algebraic_sphere_cylinder(s, c, true)
2975        }
2976        (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
2977            algebraic_sphere_cylinder(s, c, false)
2978        }
2979        (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => {
2980            if let Some(rulings) = shared_apex_cones(c1, c2, v_range_a, v_range_b)? {
2981                return Ok(Some(rulings));
2982            }
2983            if let Some(curves) = algebraic_cone_cone(c1, c2)? {
2984                return Ok(Some(curves));
2985            }
2986            Ok(algebraic_parallel_cone_cone(c1, c2, v_range_a, v_range_b))
2987        }
2988        (AnalyticSurface::Cone(cone), AnalyticSurface::Sphere(sphere)) => {
2989            Ok(ruling_cone_sphere(cone, sphere, true))
2990        }
2991        (AnalyticSurface::Sphere(sphere), AnalyticSurface::Cone(cone)) => {
2992            Ok(ruling_cone_sphere(cone, sphere, false))
2993        }
2994        (AnalyticSurface::Torus(t), AnalyticSurface::Cylinder(c)) => {
2995            if let Some(exacts) = exact_cylinder_torus(c, t)? {
2996                return exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p)))
2997                    .map(Some);
2998            }
2999            Ok(parallel_axis_torus_cylinder(t, c, true)
3000                .or_else(|| ruling_torus_cylinder(t, c, true)))
3001        }
3002        (AnalyticSurface::Cylinder(c), AnalyticSurface::Torus(t)) => {
3003            if let Some(exacts) = exact_cylinder_torus(c, t)? {
3004                return exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p)))
3005                    .map(Some);
3006            }
3007            Ok(parallel_axis_torus_cylinder(t, c, false)
3008                .or_else(|| ruling_torus_cylinder(t, c, false)))
3009        }
3010        (AnalyticSurface::Sphere(s), AnalyticSurface::Torus(t)) => {
3011            match exact_sphere_torus(s, t)? {
3012                Some(exacts) => {
3013                    exact_circle_curves(exacts, |p| (s.project_point(p), t.project_point(p)))
3014                        .map(Some)
3015                }
3016                None => Ok(sphere_torus_curves(s, t, true)),
3017            }
3018        }
3019        (AnalyticSurface::Torus(t), AnalyticSurface::Sphere(s)) => {
3020            match exact_sphere_torus(s, t)? {
3021                Some(exacts) => {
3022                    exact_circle_curves(exacts, |p| (t.project_point(p), s.project_point(p)))
3023                        .map(Some)
3024                }
3025                None => Ok(sphere_torus_curves(s, t, false)),
3026            }
3027        }
3028        (AnalyticSurface::Torus(t1), AnalyticSurface::Torus(t2)) => exact_torus_torus(t1, t2)?
3029            .map(|exacts| {
3030                exact_circle_curves(exacts, |p| (t1.project_point(p), t2.project_point(p)))
3031            })
3032            .transpose(),
3033        (AnalyticSurface::Cone(c), AnalyticSurface::Torus(t)) => exact_cone_torus(c, t)?
3034            .map(|exacts| exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p))))
3035            .transpose(),
3036        (AnalyticSurface::Torus(t), AnalyticSurface::Cone(c)) => exact_cone_torus(c, t)?
3037            .map(|exacts| exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p))))
3038            .transpose(),
3039    }
3040}
3041
3042/// A torus and a cylinder whose axes are parallel but distinct (a drill
3043/// through a ring parallel to its axis), traced along the cylinder's
3044/// rulings. A ruling stays at one distance `ρ` from the torus axis, so it
3045/// meets the tube where `(ρ − R)² + z² = r²`: a quadratic in its axial
3046/// parameter. `None` for any other pair (tilted or coaxial axes) and when
3047/// the sampling misses a window narrower than itself.
3048fn parallel_axis_torus_cylinder(
3049    torus: &ToroidalSurface,
3050    cyl: &CylindricalSurface,
3051    torus_first: bool,
3052) -> Option<Vec<IntersectionCurve>> {
3053    let axis = torus.z_axis();
3054    let along = cyl.axis().dot(axis);
3055    if along.abs() < 1.0 - 1e-10 {
3056        return None;
3057    }
3058    let offset = cyl.origin() - torus.center();
3059    if (offset - axis * offset.dot(axis)).length() < Tolerance::new().linear {
3060        return None;
3061    }
3062    let (major, minor) = (torus.major_radius(), torus.minor_radius());
3063    let roots = |u: f64| {
3064        let q = cyl.evaluate(u, 0.0) - torus.center();
3065        let height = q.dot(axis);
3066        let rho = (q - axis * height).length();
3067        let reach = minor * minor - (rho - major) * (rho - major);
3068        ruling_quadratic(1.0, 2.0 * along.signum() * height, height * height - reach)
3069    };
3070    let samples = ruling_samples(cyl, &roots);
3071    let loops = if samples.iter().all(Option::is_some) {
3072        closed_ruling_loops(cyl, &roots, &samples)
3073    } else {
3074        partial_ruling_loops(cyl, &roots, &samples)
3075    };
3076    if loops.is_empty() {
3077        return None;
3078    }
3079    Some(fit_ruling_loops(&loops, |p| {
3080        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
3081    }))
3082}
3083
3084/// Where two circles in a half-plane through an axis cross, as `(rho, z)`
3085/// pairs (distance from the axis, height along it): each sweeps a circle
3086/// about the axis. Two crossings closer than the linear tolerance are the
3087/// one point where the circles touch, side by side or one inside the
3088/// other. `None` (defer to the marcher) when the circles coincide or a
3089/// crossing lands on or past the axis; `Some` of none when they miss.
3090fn meridian_crossings(
3091    first: (f64, f64, f64),
3092    second: (f64, f64, f64),
3093    scale: f64,
3094) -> Option<Vec<(f64, f64)>> {
3095    let ((x1, z1, r1), (x2, z2, r2)) = (first, second);
3096    let (dx, dz) = (x2 - x1, z2 - z1);
3097    let dist = dx.hypot(dz);
3098    let slack = 1e-9 * scale;
3099    if dist < slack {
3100        return None;
3101    }
3102    let rounding = 8.0 * f64::EPSILON * (x1.abs() + x2.abs() + z1.abs() + z2.abs() + r1 + r2);
3103    if dist > r1 + r2 + rounding || dist < (r1 - r2).abs() - rounding {
3104        return Some(Vec::new());
3105    }
3106    let along = r2.madd(-r2, r1.madd(r1, dist * dist)) / (2.0 * dist);
3107    let across = r1.madd(r1, -(along * along)).max(0.0).sqrt();
3108    let (ux, uz) = (dx / dist, dz / dist);
3109    let sides: &[f64] = if 2.0 * across <= Tolerance::new().linear {
3110        &[0.0]
3111    } else {
3112        &[1.0, -1.0]
3113    };
3114    let mut crossings = Vec::with_capacity(sides.len());
3115    for side in sides {
3116        let rho = x1 + along * ux - side * across * uz;
3117        if rho <= slack {
3118            return None;
3119        }
3120        crossings.push((rho, z1 + along * uz + side * across * ux));
3121    }
3122    Some(crossings)
3123}
3124
3125/// Exact circles as intersection curves, each sampled at 33 points that
3126/// carry both surfaces' parameters, and a lone touching point as a curve
3127/// that stays on it.
3128fn exact_circle_curves(
3129    exacts: Vec<ExactIntersectionCurve>,
3130    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3131) -> Result<Vec<IntersectionCurve>, MathError> {
3132    let mut curves = Vec::with_capacity(exacts.len());
3133    for exact in exacts {
3134        match exact {
3135            ExactIntersectionCurve::Circle(circle) => {
3136                let points = (0..=32)
3137                    .map(|i| {
3138                        let point = circle.evaluate(TAU * f64::from(i) / 32.0);
3139                        let (param1, param2) = params(point);
3140                        IntersectionPoint {
3141                            point,
3142                            param1,
3143                            param2,
3144                        }
3145                    })
3146                    .collect();
3147                let r = circle.radius();
3148                let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
3149                curves.push(IntersectionCurve { curve, points });
3150            }
3151            // A lone point is where the surfaces touch.
3152            ExactIntersectionCurve::Points(points) if points.len() == 1 => {
3153                let point = points[0];
3154                let (param1, param2) = params(point);
3155                curves.push(IntersectionCurve {
3156                    curve: interpolate(&[point, point], 1)?,
3157                    points: vec![IntersectionPoint {
3158                        point,
3159                        param1,
3160                        param2,
3161                    }],
3162                });
3163            }
3164            ExactIntersectionCurve::Ellipse(_) | ExactIntersectionCurve::Points(_) => {}
3165        }
3166    }
3167    Ok(curves)
3168}
3169
3170/// Circles about an axis through `base`, at the given `(rho, z)` crossings.
3171fn circles_about_axis(
3172    base: Point3,
3173    axis: Vec3,
3174    crossings: &[(f64, f64)],
3175) -> Result<Vec<ExactIntersectionCurve>, MathError> {
3176    crossings
3177        .iter()
3178        .map(|&(rho, z)| {
3179            Circle3D::new(base + axis * z, axis, rho).map(ExactIntersectionCurve::Circle)
3180        })
3181        .collect()
3182}
3183
3184/// Exact intersection of two tori sharing an axis: their tube cross-sections
3185/// in a half-plane through the axis cross in up to two points, and each sweeps
3186/// a circle about the axis.
3187///
3188/// Cross-sections that touch meet at one point, sweeping one circle. `None`
3189/// (defer to the marcher) unless the axes lie on one line, or when the
3190/// cross-sections coincide.
3191///
3192/// # Errors
3193///
3194/// Returns an error if a section circle cannot be built.
3195pub fn exact_torus_torus(
3196    first: &ToroidalSurface,
3197    second: &ToroidalSurface,
3198) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3199    let axis = first.z_axis();
3200    let scale = first.major_radius() + second.major_radius();
3201    let offset = second.center() - first.center();
3202    // A spindle torus's tube also crosses the far side of the axis.
3203    if first.minor_radius() >= first.major_radius()
3204        || second.minor_radius() >= second.major_radius()
3205        || axis.cross(second.z_axis()).length() > 1e-9
3206        || offset.cross(axis).length() > 1e-9 * scale
3207    {
3208        return Ok(None);
3209    }
3210    let Some(crossings) = meridian_crossings(
3211        (first.major_radius(), 0.0, first.minor_radius()),
3212        (
3213            second.major_radius(),
3214            offset.dot(axis),
3215            second.minor_radius(),
3216        ),
3217        scale,
3218    ) else {
3219        return Ok(None);
3220    };
3221    circles_about_axis(first.center(), axis, &crossings).map(Some)
3222}
3223
3224/// Exact intersection of a torus with a cylinder sharing its axis.
3225///
3226/// The wall line and the tube's cross-section in a half-plane through the
3227/// axis cross in up to two points, each sweeping a circle about the axis. A
3228/// wall touching the tube's outer equator, ring or spindle, or a ring torus's
3229/// inner equator meets it along the one circle at the torus's centre.
3230///
3231/// `None` (defer to the marcher) unless the axes lie on one line, or when
3232/// the wall reaches the part of a spindle torus's tube across the axis.
3233///
3234/// # Errors
3235///
3236/// Returns an error if a section circle cannot be built.
3237pub fn exact_cylinder_torus(
3238    cylinder: &CylindricalSurface,
3239    torus: &ToroidalSurface,
3240) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3241    let axis = torus.z_axis();
3242    let scale = torus.major_radius() + cylinder.radius();
3243    let offset = cylinder.origin() - torus.center();
3244    let linear = crate::tolerance::Tolerance::default().linear;
3245    if axis.cross(cylinder.axis()).length() > 1e-9
3246        || offset.cross(axis).length() > 1e-9 * scale
3247        || cylinder.radius() + torus.major_radius() <= torus.minor_radius() + linear
3248    {
3249        return Ok(None);
3250    }
3251    let gap = cylinder.radius() - torus.major_radius();
3252    let small = torus.minor_radius();
3253    // The equator circle lies on the torus within the wall's distance from
3254    // the tube, so it stands for the section while that distance is within
3255    // the linear tolerance, whatever the scale.
3256    if (gap.abs() - small).abs() <= linear {
3257        return circles_about_axis(torus.center(), axis, &[(cylinder.radius(), 0.0)]).map(Some);
3258    }
3259    if gap.abs() > small {
3260        return Ok(Some(Vec::new()));
3261    }
3262    let height = small.madd(small, -(gap * gap)).sqrt();
3263    circles_about_axis(
3264        torus.center(),
3265        axis,
3266        &[(cylinder.radius(), height), (cylinder.radius(), -height)],
3267    )
3268    .map(Some)
3269}
3270
3271/// Exact intersection of a ring torus with a cone sharing its axis.
3272///
3273/// In a half-plane through the axis, a generator of the cone runs from the
3274/// apex at the half angle `a` from the radial direction, and the tube's
3275/// cross-section is a circle of the minor radius `r` about `(R, h)`: `R` the
3276/// major radius, `h` the torus centre's height above the apex along the
3277/// cone's axis. The generator meets that circle at `v = t ± √(r² − p²)`
3278/// along it, `t = R cos a + h sin a` the foot of the perpendicular from the
3279/// centre and `p = |R sin a − h cos a|` its length. Each root ahead of the
3280/// apex sweeps a circle about the axis. A generator within the linear
3281/// tolerance of tangent to the cross-section touches the tube along the one
3282/// circle at its foot.
3283///
3284/// `None` (defer to the marcher) unless the axes lie on one line, and for a
3285/// horn or spindle torus, whose tube reaches the axis.
3286///
3287/// # Errors
3288///
3289/// Returns an error if a section circle cannot be built.
3290pub fn exact_cone_torus(
3291    cone: &ConicalSurface,
3292    torus: &ToroidalSurface,
3293) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3294    let axis = cone.axis();
3295    let (major, minor) = (torus.major_radius(), torus.minor_radius());
3296    let offset = torus.center() - cone.apex();
3297    // The cone's axis must pass the torus's centre within the torus's own
3298    // scale: an apex far away does not widen the band.
3299    if minor >= major
3300        || axis.cross(torus.z_axis()).length() > 1e-9
3301        || offset.cross(axis).length() > 1e-9 * (major + minor)
3302    {
3303        return Ok(None);
3304    }
3305    let linear = Tolerance::new().linear;
3306    let (sin_a, cos_a) = cone.half_angle().sin_cos();
3307    let height = offset.dot(axis);
3308    let foot = major.madd(cos_a, height * sin_a);
3309    let reach = major.madd(sin_a, -(height * cos_a)).abs();
3310    let roots = if (reach - minor).abs() <= linear {
3311        vec![foot]
3312    } else if reach > minor {
3313        Vec::new()
3314    } else {
3315        let half = ((minor - reach) * (minor + reach)).sqrt();
3316        vec![foot - half, foot + half]
3317    };
3318    let crossings: Vec<(f64, f64)> = roots
3319        .into_iter()
3320        .filter(|&v| v * cos_a > linear)
3321        .map(|v| (v * cos_a, v * sin_a))
3322        .collect();
3323    circles_about_axis(cone.apex(), axis, &crossings).map(Some)
3324}
3325
3326/// Exact intersection of a torus with a sphere centred on its axis.
3327///
3328/// The sphere's great circle and the tube's cross-section in a half-plane
3329/// through the axis cross in up to two points, and each sweeps a circle
3330/// about the axis; where they touch (a ball sitting in the ring's hole or
3331/// on its rim) they meet along one circle. A sphere off the axis that
3332/// touches a ring torus at one point gives that point.
3333///
3334/// `None` (defer to the marcher) for a spindle torus, and for a sphere off
3335/// the axis that does not touch the torus at one point.
3336///
3337/// # Errors
3338///
3339/// Returns an error if a section circle cannot be built.
3340pub fn exact_sphere_torus(
3341    sphere: &SphericalSurface,
3342    torus: &ToroidalSurface,
3343) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3344    let axis = torus.z_axis();
3345    let scale = torus.major_radius() + sphere.radius();
3346    let offset = sphere.center() - torus.center();
3347    // A spindle torus's tube also crosses the far side of the axis.
3348    if torus.minor_radius() >= torus.major_radius() {
3349        return Ok(None);
3350    }
3351    if offset.cross(axis).length() > 1e-9 * scale {
3352        // A sphere centred on the core circle with the tube's own radius
3353        // holds the meridian circle through its centre, and the tube round
3354        // it: they meet along that circle alone. The circle strays from the
3355        // tube by the centre's distance from the core circle and the radii's
3356        // difference, which must both be rounding and within tolerance.
3357        let radial = offset - axis * offset.dot(axis);
3358        let slack = 64.0
3359            * f64::EPSILON
3360            * (torus.major_radius() + torus.minor_radius() + sphere.radius() + offset.length());
3361        let stray = (radial.length() - torus.major_radius()).hypot(offset.dot(axis))
3362            + (sphere.radius() - torus.minor_radius()).abs();
3363        if stray <= slack.min(Tolerance::new().linear) {
3364            let along = axis.cross(radial).normalize()?;
3365            return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
3366                sphere.center(),
3367                along,
3368                sphere.radius(),
3369            )?)]));
3370        }
3371        return Ok(
3372            off_axis_touch(sphere, torus).map(|p| vec![ExactIntersectionCurve::Points(vec![p])])
3373        );
3374    }
3375    let Some(crossings) = meridian_crossings(
3376        (0.0, offset.dot(axis), sphere.radius()),
3377        (torus.major_radius(), 0.0, torus.minor_radius()),
3378        scale,
3379    ) else {
3380        return Ok(None);
3381    };
3382    circles_about_axis(torus.center(), axis, &crossings).map(Some)
3383}
3384
3385/// The fewest and most steps along each branch of a loop a sphere cuts from
3386/// a torus: its curve is fitted through them alone, so a small loop takes
3387/// enough to hold the fit to the section.
3388const SPHERE_TORUS_LOOP_SAMPLES: (f64, f64) = (128.0, 1024.0);
3389
3390/// The section a sphere off a ring torus's axis cuts from it. In the
3391/// torus's frame let the sphere's centre sit at `(a, b, h)`, with
3392/// `s = hypot(a, b)` and `phi = atan2(b, a)`. The torus's point at `(u, v)`,
3393/// with `ρ = R + r·cos v`, lies on the sphere of radius `q` when
3394/// `ρ² − 2ρs·cos(u − phi) + s² + (r·sin v − h)² = q²`, so at each `v`
3395/// `cos(u − phi) = (R² + r² + h² + s² − q² + 2Rr·cos v − 2hr·sin v) / (2s·ρ)`.
3396/// `None` for a spindle torus, whose `ρ` reaches zero, or a sphere on the
3397/// axis, whose sections are circles about it.
3398fn sphere_torus_section<'a>(
3399    sphere: &SphericalSurface,
3400    torus: &'a ToroidalSurface,
3401) -> Option<TorusSection<'a, impl Fn(Point3) -> f64>> {
3402    let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
3403    let offset = sphere.center() - torus.center();
3404    let (a, b, h) = (
3405        offset.dot(torus.x_axis()),
3406        offset.dot(torus.y_axis()),
3407        offset.dot(torus.z_axis()),
3408    );
3409    let s = a.hypot(b);
3410    if small >= big || s <= 1e-9 * (big + radius) {
3411        return None;
3412    }
3413    let centre = sphere.center();
3414    Some(TorusSection {
3415        torus,
3416        phi: b.atan2(a),
3417        num: [
3418            big.madd(
3419                big,
3420                small.madd(small, h.madd(h, s.madd(s, -radius * radius))),
3421            ),
3422            2.0 * big * small,
3423            -2.0 * h * small,
3424        ],
3425        den: [2.0 * s * big, 2.0 * s * small],
3426        clearance: move |p: Point3| (p - centre).length() - radius,
3427        slack: 64.0 * f64::EPSILON * (big + small + radius + offset.length()),
3428    })
3429}
3430
3431/// How many times a loop's fitted curve may be refined where it strays.
3432const SPHERE_TORUS_FIT_ROUNDS: usize = 6;
3433
3434/// The curves a sphere off a ring torus's axis meets it in, each fitted
3435/// through the closed-form points of [`sphere_torus_section`] and every point
3436/// given its parameters on both surfaces, the sphere's first when
3437/// `sphere_first`. Halfway between each pair of points the curve must lie
3438/// within a quarter of the linear tolerance of both surfaces; where it
3439/// strays the section's own point there joins the fit. `None`, deferring to the marcher, for a
3440/// curve that still strays, or whose points do.
3441fn sphere_torus_curves(
3442    sphere: &SphericalSurface,
3443    torus: &ToroidalSurface,
3444    sphere_first: bool,
3445) -> Option<Vec<IntersectionCurve>> {
3446    let section = sphere_torus_section(sphere, torus)?;
3447    let tol = Tolerance::new().linear;
3448    let (big, small) = (torus.major_radius(), torus.minor_radius());
3449    // The centre's least and greatest distance to the torus: the ball meets
3450    // it whenever its radius lies between them. A section that comes out
3451    // empty for such a ball has lost its loops to rounding, so the marcher
3452    // takes it rather than the pair being called apart.
3453    let offset = sphere.center() - torus.center();
3454    let rise = offset.dot(torus.z_axis());
3455    let reach = (offset - torus.z_axis() * rise).length();
3456    let (nearest, farthest) = (
3457        ((reach - big).hypot(rise) - small).abs(),
3458        (reach + big).hypot(rise) + small,
3459    );
3460    let margin = 8.0 * f64::EPSILON * (big + small + offset.length() + sphere.radius());
3461    let crosses = sphere.radius() > nearest + margin && sphere.radius() < farthest - margin;
3462    let off = |p: Point3| {
3463        let local = p - torus.center();
3464        let (x, y, z) = (
3465            local.dot(torus.x_axis()),
3466            local.dot(torus.y_axis()),
3467            local.dot(torus.z_axis()),
3468        );
3469        let on_torus = (x.hypot(y) - big).hypot(z) - small;
3470        on_torus.abs().max((section.clearance)(p).abs())
3471    };
3472    // `acos` of a ratio near 1 loses digits a small ball on a large torus
3473    // needs, so each point steps onto the sphere across the section, along
3474    // the torus, the shortest way in its own measure.
3475    let centre = sphere.center();
3476    let polish = |q: IntersectionPoint| {
3477        let (mut u, mut v) = q.param1;
3478        let mut best = q;
3479        for _ in 0..4 {
3480            let gap = (section.clearance)(best.point);
3481            let (sin_u, cos_u) = u.sin_cos();
3482            let (sin_v, cos_v) = v.sin_cos();
3483            let rho = small.madd(cos_v, big);
3484            let outward = torus.x_axis() * cos_u + torus.y_axis() * sin_u;
3485            let p_u = (torus.y_axis() * cos_u - torus.x_axis() * sin_u) * rho;
3486            let p_v = outward * (-small * sin_v) + torus.z_axis() * (small * cos_v);
3487            let away = best.point - centre;
3488            let normal = away * (1.0 / away.length());
3489            let (g_u, g_v) = (normal.dot(p_u), normal.dot(p_v));
3490            let (w_u, w_v) = (g_u / (rho * rho), g_v / (small * small));
3491            let reach = g_u.madd(w_u, g_v * w_v);
3492            if reach <= f64::MIN_POSITIVE {
3493                break;
3494            }
3495            let next = section.point(gap.madd(-w_u / reach, u), gap.madd(-w_v / reach, v));
3496            if (section.clearance)(next.point).abs() >= gap.abs() {
3497                break;
3498            }
3499            (u, v) = next.param1;
3500            best = next;
3501        }
3502        best
3503    };
3504    let loops = section.loops(256, SPHERE_TORUS_LOOP_SAMPLES);
3505    if loops.is_empty() && crosses {
3506        return None;
3507    }
3508    let mut curves = Vec::new();
3509    for points in loops {
3510        let mut points: Vec<IntersectionPoint> = points.into_iter().map(polish).collect();
3511        if points.iter().any(|q| off(q.point) > tol) {
3512            return None;
3513        }
3514        // Samples past a turn that `acos` clamped onto the same `u` all step
3515        // to the turn itself.
3516        points.dedup_by(|b, a| (b.point - a.point).length() <= 1e-3 * tol);
3517        let mut rounds = 0;
3518        let curve = loop {
3519            let positions: Vec<Point3> = points.iter().map(|q| q.point).collect();
3520            let curve = interpolate(&positions, 3.min(positions.len() - 1)).ok()?;
3521            let params = crate::nurbs::fitting::chord_length_params(&positions);
3522            let strays: Vec<usize> = (0..positions.len() - 1)
3523                .filter(|&k| {
3524                    off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))) > 0.25 * tol
3525                })
3526                .collect();
3527            if strays.is_empty() {
3528                break curve;
3529            }
3530            if rounds == SPHERE_TORUS_FIT_ROUNDS {
3531                return None;
3532            }
3533            rounds += 1;
3534            for &k in strays.iter().rev() {
3535                let mid = polish(section.between(points[k].param1, points[k + 1].param1));
3536                if off(mid.point) > tol {
3537                    return None;
3538                }
3539                points.insert(k + 1, mid);
3540            }
3541        };
3542        for q in &mut points {
3543            let (on_sphere, on_torus) = (sphere.project_point(q.point), q.param1);
3544            (q.param1, q.param2) = if sphere_first {
3545                (on_sphere, on_torus)
3546            } else {
3547                (on_torus, on_sphere)
3548            };
3549        }
3550        curves.push(IntersectionCurve { curve, points });
3551    }
3552    Some(curves)
3553}
3554
3555/// Where a sphere off a ring torus's axis touches it at one point: from
3556/// outside the tube, from inside it, or holding the whole ring. The touch
3557/// sits over the core circle's point nearest the sphere's centre, at
3558/// `d_near`, or farthest from it, at `d_far`, and the sphere's radius is
3559/// then `d_near − r`, `r − d_near` or `d_far + r`. Each is the centre's
3560/// least or greatest distance to the torus, so the point is all the two
3561/// share. `None` unless the radius matches one to rounding.
3562fn off_axis_touch(sphere: &SphericalSurface, torus: &ToroidalSurface) -> Option<Point3> {
3563    let axis = torus.z_axis();
3564    let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
3565    let offset = sphere.center() - torus.center();
3566    let radial = offset - axis * offset.dot(axis);
3567    let out = radial * (1.0 / radial.length());
3568    let near = torus.center() + out * big;
3569    let far = torus.center() - out * big;
3570    let (to_near, to_far) = (sphere.center() - near, sphere.center() - far);
3571    let (d_near, d_far) = (to_near.length(), to_far.length());
3572    let slack = 64.0 * f64::EPSILON * (big + small + radius + offset.length());
3573    // A ball centred on the core circle meets the tube along a whole
3574    // meridian, not at a point.
3575    if d_near > slack
3576        && ((d_near - small - radius).abs() <= slack || (small - d_near - radius).abs() <= slack)
3577    {
3578        return Some(near + to_near * (small / d_near));
3579    }
3580    ((d_far + small - radius).abs() <= slack).then(|| far - to_far * (small / d_far))
3581}
3582
3583/// Exact coaxial cone-cone intersection: returns the shared circle.
3584///
3585/// Two cones that share an axis are concentric circles at every axial
3586/// station, so they meet only where their radii are equal. Each cone's
3587/// radius is linear in the axial coordinate `t` (measured along the shared
3588/// axis from cone 1's apex): `r1 = m1·t` and `r2 = m2·σ·(t − d2)`, where
3589/// `m_i = cot(half_angle_i)`, `σ = sign(axis2·axis1)`, and `d2` is cone 2's
3590/// apex position in that coordinate. Equating gives a single crossing `t*`
3591/// → one circle (the shared rim). The general marcher mishandles this case:
3592/// at the radii-crossing the surfaces are nearly tangent, so a grid-seeded
3593/// march fragments the clean circle into dozens of degenerate micro-curves.
3594///
3595/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
3596/// the cones do not meet (parallel radius lines or a crossing on the wrong
3597/// nappe), and `None` for the identical-cone overlap or a degenerate
3598/// (near-flat) cone — both of which fall through to the general path.
3599/// Parallel-but-offset axes with equal half-angle tangents reduce to a
3600/// radical-plane conic (`offset_parallel_cone_cone`); other offset
3601/// configurations defer to the marcher with `None`.
3602///
3603/// # Errors
3604///
3605/// Returns [`MathError`] if the shared-rim `Circle3D` cannot be constructed
3606/// (e.g. a non-finite center or radius from a malformed cone).
3607pub fn exact_cone_cone(
3608    c1: &ConicalSurface,
3609    c2: &ConicalSurface,
3610) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3611    let axis = c1.axis();
3612    let axis2 = c2.axis();
3613
3614    // Coaxial check: parallel axes and the second apex lies on the first axis.
3615    if axis.dot(axis2).abs() < 1.0 - 1e-10 {
3616        return Ok(None); // Non-coaxial: quartic curve, let the marcher handle.
3617    }
3618    let apex1 = c1.apex();
3619    let apex2 = c2.apex();
3620    let delta = apex2 - apex1;
3621    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3622    let along = delta_v.dot(axis);
3623    if (delta_v - axis * along).length() > 1e-8 {
3624        return offset_parallel_cone_cone(c1, c2);
3625    }
3626
3627    let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3628    if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
3629        return Ok(None); // Degenerate (near-flat) cone.
3630    }
3631    let m1 = c1.half_angle().cos() / s1;
3632    let m2 = c2.half_angle().cos() / s2;
3633    let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
3634    let d2 = along; // apex2 position along `axis`, measured from apex1.
3635
3636    let denom = m1 - m2 * sigma;
3637    if denom.abs() < 1e-12 {
3638        // Parallel radius lines: identical cones (coincident apex, same opening)
3639        // overlap — defer to the general/same-domain path; otherwise no meeting.
3640        if sigma > 0.0 && d2.abs() < 1e-9 {
3641            return Ok(None);
3642        }
3643        return Ok(Some(vec![]));
3644    }
3645
3646    let t_star = (-m2 * sigma * d2) / denom;
3647    let radius = m1 * t_star;
3648    if radius < 1e-12 {
3649        return Ok(Some(vec![])); // Crossing on the wrong nappe / no real circle.
3650    }
3651
3652    let center = Point3::new(
3653        apex1.x() + axis.x() * t_star,
3654        apex1.y() + axis.y() * t_star,
3655        apex1.z() + axis.z() * t_star,
3656    );
3657    let circle = Circle3D::new(center, axis, radius)?;
3658    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3659}
3660
3661/// Parallel-axis (or anti-parallel), offset-apex cones with equal half-angle
3662/// tangents: subtracting the two quadric equations cancels both the radial
3663/// and the axial quadratic terms (their coefficients depend only on
3664/// `tan²(half_angle)`), so every intersection point lies on a plane — the
3665/// degenerate member of the quadric pencil — and plane ∩ cone is an exact
3666/// conic. The gridfinity spacer lip fuse hits this exactly: opposed 45°
3667/// corner cones offset 0.25mm, which the marcher shreds into ~64 closed
3668/// micro-loops per pair (#1570). Unequal angles keep a genuine quadratic
3669/// term, and an unbounded section (hyperbola/parabola) has no closed-form
3670/// win over the marcher — both defer with `None`.
3671fn offset_parallel_cone_cone(
3672    c1: &ConicalSurface,
3673    c2: &ConicalSurface,
3674) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3675    if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
3676        return Ok(None); // Degenerate (near-flat) cone, as in the coaxial path.
3677    }
3678    let t1 = c1.half_angle().tan();
3679    let t2 = c2.half_angle().tan();
3680    if !t1.is_finite() || !t2.is_finite() {
3681        return Ok(None);
3682    }
3683    if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
3684        return Ok(None);
3685    }
3686
3687    let w = c1.axis();
3688    let apex1 = c1.apex();
3689    let apex2 = c2.apex();
3690    let delta = apex2 - apex1;
3691    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3692    let s = delta_v.dot(w);
3693    let tm = 0.5 * (t1 + t2);
3694    let k = 1.0 + tm * tm;
3695
3696    // In the apex1 frame each cone is |P|² − k(P·w)² = 0 (shifted by δ for
3697    // cone 2; the axis SIGN drops out since only (P·w)² appears). Their
3698    // difference: P·(2δ − 2ksw) = |δ|² − ks².
3699    let n = (delta_v - w * (k * s)) * 2.0;
3700    let n_len = n.length();
3701    if n_len < 1e-12 {
3702        return Ok(None);
3703    }
3704    let n_hat = n * (1.0 / n_len);
3705    let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
3706
3707    // `exact_plane_cone` already rejects sections on cone 1's phantom nappe;
3708    // cone 2's nappe must be checked here. A conic on the shared quadric
3709    // pencil cannot cross between nappes except exactly through apex 2, so
3710    // sampled quarter-points either all pass or all fail; a mixed verdict
3711    // means an apex-touching degeneracy — defer to the marcher.
3712    let axis2 = c2.axis();
3713    let scale = 1.0 + delta_v.length();
3714    let mut out = Vec::new();
3715    for curve in exact_plane_cone(c1, n_hat, d, 0.0)? {
3716        let samples: Vec<Point3> = match &curve {
3717            ExactIntersectionCurve::Circle(c) => (0..4)
3718                .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
3719                .collect(),
3720            ExactIntersectionCurve::Ellipse(e) => (0..4)
3721                .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
3722                .collect(),
3723            ExactIntersectionCurve::Points(_) => return Ok(None),
3724        };
3725        let on_real_nappe = |p: &Point3| {
3726            let rel = *p - apex2;
3727            Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
3728        };
3729        let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
3730        match hits {
3731            0 => {}
3732            4 => out.push(curve),
3733            _ => return Ok(None),
3734        }
3735    }
3736    Ok(Some(out))
3737}
3738
3739/// Exact coaxial cone-cylinder intersection: returns the shared circle.
3740///
3741/// A cone and a cylinder sharing an axis are concentric circles at every
3742/// axial station, so they meet only where the cone's radius equals the
3743/// cylinder's. The cone radius is linear in the axial coordinate `t` from its
3744/// apex (`r = m·t`, `m = cot(half_angle)`), the cylinder radius is the
3745/// constant `R`, so `m·t = R` gives a single crossing `t*` → one circle. This
3746/// is the gridfinity lip's top knife edge (inner tapered corner = cone, outer
3747/// corner = cylinder, concentric, radii matching at `Z_PEAK`); the general
3748/// marcher fragments that near-tangent contact into dozens of degenerate
3749/// micro-curves.
3750///
3751/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
3752/// the crossing degenerates to the apex, and `None` (defer to the marcher)
3753/// when the surfaces are not coaxial or the cone is near-flat / near-axial.
3754///
3755/// # Errors
3756///
3757/// Returns [`MathError`] if the shared `Circle3D` cannot be constructed.
3758pub fn exact_cone_cylinder(
3759    cone: &ConicalSurface,
3760    cyl: &CylindricalSurface,
3761) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3762    let axis = cone.axis();
3763    let cyl_axis = cyl.axis();
3764
3765    // Coaxial check: parallel axes and the cone apex on the cylinder's axis.
3766    if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
3767        return Ok(None);
3768    }
3769    let apex = cone.apex();
3770    let delta = apex - cyl.origin();
3771    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3772    let along = delta_v.dot(cyl_axis);
3773    if (delta_v - cyl_axis * along).length() > 1e-8 {
3774        return Ok(None);
3775    }
3776
3777    let s = cone.half_angle().sin();
3778    if s.abs() < 1e-12 {
3779        return Ok(None); // near-flat cone.
3780    }
3781    let m = cone.half_angle().cos() / s; // dr/dt along the cone axis.
3782    if m.abs() < 1e-12 {
3783        return Ok(None); // near-axial cone: radius ~constant.
3784    }
3785
3786    let t_star = cyl.radius() / m; // where the cone radius m·t equals R.
3787    if t_star.abs() < 1e-12 {
3788        return Ok(Some(vec![])); // crossing at the apex — no real circle.
3789    }
3790    let center = Point3::new(
3791        apex.x() + axis.x() * t_star,
3792        apex.y() + axis.y() * t_star,
3793        apex.z() + axis.z() * t_star,
3794    );
3795    let circle = Circle3D::new(center, axis, cyl.radius())?;
3796    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3797}
3798
3799/// The exact rational quadratic NURBS of the full ellipse `centre +
3800/// a·cos(t)·u + b·sin(t)·v` (a circle when `a == b`), starting at
3801/// `centre + a·u`: four quarter arcs, each with its corner weighted by
3802/// cos 45°.
3803fn conic_loop(centre: Point3, u: Vec3, v: Vec3, a: f64, b: f64) -> Result<NurbsCurve, MathError> {
3804    let w = std::f64::consts::FRAC_1_SQRT_2;
3805    let corners: [(f64, f64); 9] = [
3806        (1.0, 0.0),
3807        (1.0, 1.0),
3808        (0.0, 1.0),
3809        (-1.0, 1.0),
3810        (-1.0, 0.0),
3811        (-1.0, -1.0),
3812        (0.0, -1.0),
3813        (1.0, -1.0),
3814        (1.0, 0.0),
3815    ];
3816    let points = corners
3817        .iter()
3818        .map(|&(x, y)| centre + u * (a * x) + v * (b * y))
3819        .collect();
3820    let weights = vec![1.0, w, 1.0, w, 1.0, w, 1.0, w, 1.0];
3821    let knots = vec![
3822        0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3823    ];
3824    NurbsCurve::new(2, knots, points, weights)
3825}
3826
3827/// Two cones sharing an apex meet only along rulings through it. A
3828/// ruling's direction `d` makes each cone's angle with its axis, `d·aᵢ =
3829/// ±sin(half_angleᵢ)` (the half-angle runs from the radial plane), a line
3830/// that crosses the unit sphere twice, touches it where the cones are
3831/// tangent along one ruling, or misses it. Along `apex + t·d` the first
3832/// cone's `v` is `t` and the second's `±t`, so each ruling runs where both
3833/// faces' `v` ranges hold it, as a straight segment cut at the apex. Two
3834/// rulings closer than the linear tolerance across the faces are one.
3835///
3836/// `None` unless both ranges are given, the axes are not parallel (the
3837/// coaxial path's case), and the apexes coincide to rounding.
3838fn shared_apex_cones(
3839    c1: &ConicalSurface,
3840    c2: &ConicalSurface,
3841    v1: Option<(f64, f64)>,
3842    v2: Option<(f64, f64)>,
3843) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3844    let (Some(v1), Some(v2)) = (v1, v2) else {
3845        return Ok(None);
3846    };
3847    let (a1, a2, apex) = (c1.axis(), c2.axis(), c1.apex());
3848    let across = a1.cross(a2);
3849    let sin = across.length();
3850    if sin < 1e-9 {
3851        return Ok(None);
3852    }
3853    let reach = v1.0.abs().max(v1.1.abs()).max(v2.0.abs()).max(v2.1.abs());
3854    let scale = reach.max((apex - Point3::new(0.0, 0.0, 0.0)).length());
3855    if (c2.apex() - apex).length() > 64.0 * f64::EPSILON * scale {
3856        return Ok(None);
3857    }
3858    let normal = across * (1.0 / sin);
3859    let tol = Tolerance::new().linear;
3860    // A ruling's part across the first axis is `(t2 − s1·cos) / sin`, whose
3861    // rounding grows as the axes close up; past a tenth of the tolerance
3862    // over the faces, the pair is left to the marcher.
3863    if f64::EPSILON * reach > 0.1 * tol * sin {
3864        return Ok(None);
3865    }
3866    // The second axis's part across the first, a unit vector.
3867    let toward = normal.cross(a1);
3868    let cos = a1.dot(a2);
3869    let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3870    // `evaluate` turns its radial direction round for negative `v`.
3871    let params = |cone: &ConicalSurface, p: Point3| {
3872        let (u, v) = cone.project_point(p);
3873        if v < 0.0 {
3874            ((u + std::f64::consts::PI).rem_euclid(TAU), v)
3875        } else {
3876            (u, v)
3877        }
3878    };
3879    let mut curves = Vec::new();
3880    for nappe in [1.0, -1.0] {
3881        let t2 = nappe * s2;
3882        let side = cos.madd(-s1, t2) / sin;
3883        let foot = a1 * s1 + toward * side;
3884        let lift_sq = s1.madd(-s1, side.madd(-side, 1.0));
3885        let rounding = 4.0 * f64::EPSILON;
3886        let lifts = if lift_sq.abs() <= rounding {
3887            // Within rounding of touching: the rulings that rounding could
3888            // hide part by up to `√(2·rounding)` radians, taken as one while
3889            // that stays within ten tolerances over the faces, and beyond
3890            // it not settled here.
3891            if (2.0 * rounding).sqrt() * reach > 10.0 * tol {
3892                return Ok(None);
3893            }
3894            vec![0.0]
3895        } else if lift_sq < 0.0 {
3896            Vec::new()
3897        } else if 2.0 * lift_sq.sqrt() * reach <= tol {
3898            vec![0.0]
3899        } else {
3900            vec![lift_sq.sqrt(), -lift_sq.sqrt()]
3901        };
3902        let along2 = if nappe > 0.0 { v2 } else { (-v2.1, -v2.0) };
3903        let (lo, hi) = (v1.0.max(along2.0), v1.1.min(along2.1));
3904        if hi - lo <= tol {
3905            continue;
3906        }
3907        for lift in lifts {
3908            let d = (foot + normal * lift).normalize()?;
3909            let pieces = if lo < 0.0 && hi > 0.0 {
3910                vec![(lo, 0.0), (0.0, hi)]
3911            } else {
3912                vec![(lo, hi)]
3913            };
3914            for (from, to) in pieces {
3915                curves.push(ruling_segment(apex + d * from, apex + d * to, |p| {
3916                    (params(c1, p), params(c2, p))
3917                })?);
3918            }
3919        }
3920    }
3921    Ok(Some(curves))
3922}
3923
3924/// Two cylinders of one radius whose axes cross meet in two ellipses, one
3925/// in each plane through the crossing that bisects the axes: a point lies
3926/// as far from both axes where its offsets along them are equal or
3927/// opposite. Both ellipses have their minor axis, of the radius, along the
3928/// axes' common normal, and meet at its two ends. They come back as two
3929/// closed loops, as the first cylinder's rulings pair them: the halves of
3930/// both ellipses on one side of the crossing along its axis, then on the
3931/// other, each exact, rational, and cornered where its halves meet. One
3932/// loop starts at each end of the common normal.
3933///
3934/// `None` unless the radii match and the axes cross to rounding: axes that
3935/// miss by `δ` part the curves at the crossings by about `√(δ·r)`.
3936fn crossing_equal_cylinders(
3937    c1: &CylindricalSurface,
3938    c2: &CylindricalSurface,
3939) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3940    let (d1, d2, r) = (c1.axis(), c2.axis(), c1.radius());
3941    if (c2.radius() - r).abs() > 8.0 * f64::EPSILON * r {
3942        return Ok(None);
3943    }
3944    // An ellipse's semi-major axis is `2r / |d1 ∓ d2|`. Rounding the axes
3945    // turns its major axis by about `ε / |d1 ∓ d2|`, which moves its far
3946    // vertices by `2rε / |d1 ∓ d2|²`; axes nearer parallel than keeps that
3947    // well inside the tolerance are left to the rulings.
3948    let bisectors = [d1 - d2, d1 + d2];
3949    let tol = Tolerance::new().linear;
3950    if bisectors
3951        .iter()
3952        .any(|b| 2.0 * r * f64::EPSILON > 1e-3 * tol * b.dot(*b))
3953    {
3954        return Ok(None);
3955    }
3956    let across = d1.cross(d2);
3957    let sin = across.length();
3958    let normal = across * (1.0 / sin);
3959    let w = c1.origin() - c2.origin();
3960    let cos = d1.dot(d2);
3961    let along = cos.madd(d2.dot(w), -d1.dot(w)) / (sin * sin);
3962    let centre = c1.origin() + d1 * along;
3963    // The miss is read at the crossing's own scale: origins far along
3964    // their axes leave it more rounding than that, and are left to the
3965    // rulings too.
3966    let scale = r.max((centre - Point3::new(0.0, 0.0, 0.0)).length());
3967    if w.dot(normal).abs() > 64.0 * f64::EPSILON * scale {
3968        return Ok(None);
3969    }
3970    // Each ellipse's major axis, turned to lean along the first axis, and
3971    // its semi-major axis.
3972    let majors = bisectors.map(|bisector| {
3973        let length = bisector.length();
3974        let major = (bisector * (1.0 / length)).cross(normal);
3975        let major = if major.dot(d1) < 0.0 { -major } else { major };
3976        (major, 2.0 * r / length)
3977    });
3978    let corner = std::f64::consts::FRAC_1_SQRT_2;
3979    let half = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)];
3980    let mut curves = Vec::with_capacity(2);
3981    for side in [1.0, -1.0] {
3982        let [(m1, a1), (m2, a2)] = majors;
3983        let out = half
3984            .iter()
3985            .map(|&(x, y)| centre + normal * (side * r * x) + m1 * (side * a1 * y));
3986        let back = half[1..]
3987            .iter()
3988            .map(|&(x, y)| centre - normal * (side * r * x) + m2 * (side * a2 * y));
3989        let curve = NurbsCurve::new(
3990            2,
3991            vec![
3992                0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3993            ],
3994            out.chain(back).collect(),
3995            vec![1.0, corner, 1.0, corner, 1.0, corner, 1.0, corner, 1.0],
3996        )?;
3997        #[allow(clippy::cast_precision_loss)]
3998        let points = (0..=32)
3999            .map(|i| {
4000                let point = curve.evaluate(i as f64 / 32.0);
4001                IntersectionPoint {
4002                    point,
4003                    param1: c1.project_point(point),
4004                    param2: c2.project_point(point),
4005                }
4006            })
4007            .collect();
4008        curves.push(IntersectionCurve { curve, points });
4009    }
4010    Ok(Some(curves))
4011}
4012
4013/// Algebraic cone-cone intersection (NURBS form for the general bounded
4014/// path). Delegates to [`exact_cone_cone`] and returns each exact conic
4015/// (coaxial circle or offset-parallel radical-plane ellipse) as an exact
4016/// rational NURBS `IntersectionCurve` with sample points along it, mirroring
4017/// the sphere-cylinder algebraic path. phase FF prefers the exact circle form
4018/// directly (so the section edge links to the coincident boundary), but a
4019/// caller of `intersect_analytic_analytic_bounded` still gets one clean
4020/// curve instead of the marcher's fragments.
4021fn algebraic_cone_cone(
4022    c1: &ConicalSurface,
4023    c2: &ConicalSurface,
4024) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4025    let Some(exacts) = exact_cone_cone(c1, c2)? else {
4026        return Ok(None);
4027    };
4028    let mut curves = Vec::new();
4029    for exact in exacts {
4030        let n_samples = 33;
4031        let mut points = Vec::with_capacity(n_samples);
4032        #[allow(clippy::cast_precision_loss)]
4033        for i in 0..n_samples {
4034            let theta = TAU * i as f64 / (n_samples - 1) as f64;
4035            let pt = match &exact {
4036                ExactIntersectionCurve::Circle(circle) => {
4037                    crate::traits::ParametricCurve::evaluate(circle, theta)
4038                }
4039                ExactIntersectionCurve::Ellipse(ellipse) => {
4040                    crate::traits::ParametricCurve::evaluate(ellipse, theta)
4041                }
4042                ExactIntersectionCurve::Points(_) => break,
4043            };
4044            points.push(IntersectionPoint {
4045                point: pt,
4046                param1: (0.0, 0.0),
4047                param2: (0.0, 0.0),
4048            });
4049        }
4050        let curve = match &exact {
4051            ExactIntersectionCurve::Circle(c) => {
4052                conic_loop(c.center(), c.u_axis(), c.v_axis(), c.radius(), c.radius())?
4053            }
4054            ExactIntersectionCurve::Ellipse(e) => conic_loop(
4055                e.center(),
4056                e.u_axis(),
4057                e.v_axis(),
4058                e.semi_major(),
4059                e.semi_minor(),
4060            )?,
4061            ExactIntersectionCurve::Points(_) => continue,
4062        };
4063        curves.push(IntersectionCurve { curve, points });
4064    }
4065    Ok(Some(curves))
4066}
4067
4068/// Exact coaxial sphere-cylinder intersection: returns the shared circle(s).
4069///
4070/// A sphere of radius `R` centered at `C` and a cylinder of radius `r` whose
4071/// axis passes through `C` meet in concentric circles of radius `r` at the
4072/// axial stations where `sqrt(R² − z²) = r`, i.e. `z = ±sqrt(R² − r²)`
4073/// measured from `C` along the axis. A proper crossing yields two circles; a
4074/// tangent contact (`r = R`) yields one; a cylinder wider than the sphere, or
4075/// a non-coaxial configuration (quartic curve), yields none/defers.
4076///
4077/// Mirrors [`exact_cone_cylinder`] so phase FF can emit the section as an
4078/// exact `Circle3D` (which the closed-circle split + seam adoption recognise)
4079/// rather than the marcher's NURBS fragments.
4080///
4081/// Returns `Some(vec![..])` (0, 1, or 2 circles) for the coaxial case, and
4082/// `None` (defer to the general marcher) when the axes are not coaxial.
4083///
4084/// # Errors
4085///
4086/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
4087pub fn exact_sphere_cylinder(
4088    sphere: &SphericalSurface,
4089    cyl: &CylindricalSurface,
4090) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
4091    let sc = sphere.center();
4092    let r_sphere = sphere.radius();
4093    let co = cyl.origin();
4094    let axis = cyl.axis();
4095    let r_cyl = cyl.radius();
4096
4097    // Project sphere center onto the cylinder axis.
4098    let delta = sc - co;
4099    let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
4100    let along = delta_vec.dot(axis);
4101    let perp_vec = delta_vec - axis * along;
4102    let d_perp = perp_vec.length();
4103
4104    // Non-coaxial sphere-cylinder intersections produce quartic curves;
4105    // defer those to the general marcher.
4106    if d_perp > 1e-7 {
4107        return Ok(None);
4108    }
4109
4110    // Coaxial: the sphere center lies on the cylinder axis. No real circle
4111    // when the cylinder is wider than the sphere or they are tangent-internal.
4112    if r_cyl > r_sphere + 1e-10 {
4113        return Ok(Some(vec![]));
4114    }
4115    let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
4116    if z_sq < 0.0 {
4117        return Ok(Some(vec![]));
4118    }
4119    let z = z_sq.sqrt();
4120
4121    // The sphere center projected onto the axis is the midpoint of the two
4122    // section circles, each offset by ±z along the axis with radius `r_cyl`.
4123    let center_axis_pt = Point3::new(
4124        co.x() + axis.x() * along,
4125        co.y() + axis.y() * along,
4126        co.z() + axis.z() * along,
4127    );
4128
4129    let mut circles = Vec::new();
4130    let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
4131    for &z_offset in offsets {
4132        let center = Point3::new(
4133            center_axis_pt.x() + axis.x() * z_offset,
4134            center_axis_pt.y() + axis.y() * z_offset,
4135            center_axis_pt.z() + axis.z() * z_offset,
4136        );
4137        let circle = Circle3D::new(center, axis, r_cyl)?;
4138        circles.push(ExactIntersectionCurve::Circle(circle));
4139    }
4140    Ok(Some(circles))
4141}
4142
4143/// Exact coaxial cone-sphere intersection: the shared circles.
4144///
4145/// When the cone's axis runs through the sphere's centre `C`, every generator
4146/// `apex + v g` (`g` a unit direction, `v` the distance from the apex) has
4147/// the same `h = g·(apex − C)`, so all of them meet the sphere at the same
4148/// roots of `v² + 2hv + |apex − C|² − R² = 0`. Each root ahead of the apex is
4149/// a circle of radius `v cos a` at `v sin a` along the axis: two for a ball
4150/// the cone passes through, one for a ball that swallows the apex, passes
4151/// through it or touches the wall, none for a ball the cone misses or that
4152/// sits inside it clear of the wall.
4153///
4154/// Returns `Some(vec![..])` for a coaxial pair and `None` (the ruling trace
4155/// or the marcher) otherwise.
4156///
4157/// # Errors
4158///
4159/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
4160pub fn exact_cone_sphere(
4161    cone: &ConicalSurface,
4162    sphere: &SphericalSurface,
4163) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
4164    let offset = cone.apex() - sphere.center();
4165    let along = offset.dot(cone.axis());
4166    if (offset - cone.axis() * along).length() > 1e-7 {
4167        return Ok(None);
4168    }
4169    let lin_tol = Tolerance::new().linear;
4170    let (sin_a, cos_a) = cone.half_angle().sin_cos();
4171    let (far_sq, radius_sq) = (offset.dot(offset), sphere.radius() * sphere.radius());
4172    let b = 2.0 * sin_a * along;
4173    let (disc, far, near) = ruling_quadratic(1.0, b, far_sq - radius_sq);
4174    // At a tangent ball `b² − 4c` cancels to a few ulps of its terms, which
4175    // can land below zero: that is a touch, not a miss.
4176    let noise = 16.0 * f64::EPSILON * 4.0f64.madd(far_sq + radius_sq, b * b);
4177    if disc < -noise {
4178        return Ok(Some(vec![]));
4179    }
4180    let roots: &[f64] = if far - near < lin_tol {
4181        &[far]
4182    } else {
4183        &[near, far]
4184    };
4185    let mut circles = Vec::new();
4186    for &v in roots {
4187        if v * cos_a > lin_tol {
4188            let centre = cone.apex() + cone.axis() * (v * sin_a);
4189            let circle = Circle3D::new(centre, cone.axis(), v * cos_a)?;
4190            circles.push(ExactIntersectionCurve::Circle(circle));
4191        }
4192    }
4193    Ok(Some(circles))
4194}
4195
4196/// Algebraic sphere-cylinder intersection (NURBS form for the general bounded
4197/// path). A coaxial pair delegates to [`exact_sphere_cylinder`] and returns
4198/// each exact circle as an exact rational NURBS `IntersectionCurve`. phase FF
4199/// prefers the exact circle form directly (so the section edge links to the
4200/// coincident boundary and the closed-circle splitter can carve the spherical
4201/// band), but a caller of `intersect_analytic_analytic_bounded` still gets
4202/// clean curves instead of the marcher's fragments. Any other pair is traced
4203/// along the cylinder's rulings ([`off_axis_sphere_cylinder`]).
4204fn algebraic_sphere_cylinder(
4205    sphere: &SphericalSurface,
4206    cyl: &CylindricalSurface,
4207    sphere_first: bool,
4208) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4209    let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
4210        return Ok(off_axis_sphere_cylinder(sphere, cyl, sphere_first));
4211    };
4212
4213    let mut curves = Vec::new();
4214    for exact in exacts {
4215        let ExactIntersectionCurve::Circle(circle) = exact else {
4216            continue;
4217        };
4218        let n_samples = 33;
4219        let mut points = Vec::with_capacity(n_samples);
4220        #[allow(clippy::cast_precision_loss)]
4221        for i in 0..n_samples {
4222            let theta = TAU * i as f64 / (n_samples - 1) as f64;
4223            let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
4224            let (param1, param2) = in_order(
4225                sphere.project_point(pt),
4226                cyl.project_point(pt),
4227                sphere_first,
4228            );
4229            points.push(IntersectionPoint {
4230                point: pt,
4231                param1,
4232                param2,
4233            });
4234        }
4235        let r = circle.radius();
4236        let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
4237        curves.push(IntersectionCurve { curve, points });
4238    }
4239
4240    Ok(Some(curves))
4241}
4242
4243/// A sphere and a cylinder whose axis misses the sphere's centre (a drill
4244/// entering a ball off its axis), traced along the cylinder's rulings: the
4245/// ruling `c(u) + v·a` meets the sphere where `v² + 2(q·a)·v + |q|² − R² = 0`,
4246/// with `q = c(u) − C`. When every ruling meets the sphere (the cylinder
4247/// passes wholly through it) the roots trace an entry and an exit loop;
4248/// otherwise each window of meeting rulings carries one loop. `Some(empty)`
4249/// when the two cannot meet, `None` when the sampling misses a window
4250/// narrower than itself.
4251fn off_axis_sphere_cylinder(
4252    sphere: &SphericalSurface,
4253    cyl: &CylindricalSurface,
4254    sphere_first: bool,
4255) -> Option<Vec<IntersectionCurve>> {
4256    let (centre, radius) = (sphere.center(), sphere.radius());
4257    let axis = cyl.axis();
4258    let offset = centre - cyl.origin();
4259    let axis_distance = (offset - axis * offset.dot(axis)).length();
4260    let lin_tol = Tolerance::new().linear;
4261    if axis_distance > radius + cyl.radius() + lin_tol
4262        || axis_distance + radius < cyl.radius() - lin_tol
4263    {
4264        return Some(Vec::new());
4265    }
4266    let roots = |u: f64| {
4267        let q = cyl.evaluate(u, 0.0) - centre;
4268        ruling_quadratic(1.0, 2.0 * q.dot(axis), q.dot(q) - radius * radius)
4269    };
4270    let samples = ruling_samples(cyl, &roots);
4271    let loops = if samples.iter().all(Option::is_some) {
4272        closed_ruling_loops(cyl, &roots, &samples)
4273    } else {
4274        partial_ruling_loops(cyl, &roots, &samples)
4275    };
4276    if loops.is_empty() {
4277        return None;
4278    }
4279    Some(fit_ruling_loops(&loops, |p| {
4280        in_order(sphere.project_point(p), cyl.project_point(p), sphere_first)
4281    }))
4282}
4283
4284/// Parameters on the pair's first and second surfaces, from those on `a`
4285/// and `b` and whether `a` came first.
4286const fn in_order(a: (f64, f64), b: (f64, f64), a_first: bool) -> ((f64, f64), (f64, f64)) {
4287    if a_first { (a, b) } else { (b, a) }
4288}
4289
4290/// Two cylinders whose axes are parallel but apart meet along rulings:
4291/// every plane across the axes cuts them in two circles `d` apart, which
4292/// cross in two points, touch in one, or miss, alike in every plane. Each
4293/// crossing sweeps a ruling, cut to the stretch of axis both faces' `v`
4294/// ranges share. Two crossings closer than the linear tolerance are the one
4295/// where the circles touch, side by side or one inside the other. `None`
4296/// (the next solver's case) when neither range is known, since a ruling has
4297/// no ends of its own, or when a ruling's end strays off the second
4298/// cylinder, its axis leaning off the first's by more than the span allows.
4299fn parallel_cylinders(
4300    c1: &CylindricalSurface,
4301    c2: &CylindricalSurface,
4302    v_range_1: Option<(f64, f64)>,
4303    v_range_2: Option<(f64, f64)>,
4304) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4305    let axis = c1.axis();
4306    let delta = c2.origin() - c1.origin();
4307    let along = delta.dot(axis);
4308    let across = delta - axis * along;
4309    let d = across.length();
4310    let (r1, r2) = (c1.radius(), c2.radius());
4311    // The second face's range, measured along the first one's axis.
4312    let flip = c2.axis().dot(axis);
4313    let ranges = [
4314        v_range_1,
4315        v_range_2.map(|(a, b)| (along + a * flip, along + b * flip)),
4316    ];
4317    let (lo, hi) = ranges
4318        .into_iter()
4319        .flatten()
4320        .fold((f64::NEG_INFINITY, f64::INFINITY), |(lo, hi), (a, b)| {
4321            (lo.max(a.min(b)), hi.min(a.max(b)))
4322        });
4323    if !lo.is_finite() || !hi.is_finite() {
4324        return Ok(None);
4325    }
4326    let rounding = 8.0 * f64::EPSILON * (r1 + r2 + d);
4327    if d > r1 + r2 + rounding || d < (r1 - r2).abs() - rounding || hi <= lo {
4328        return Ok(Some(Vec::new()));
4329    }
4330    let toward = across * (1.0 / d);
4331    let side = axis.cross(toward);
4332    let x = r2.madd(-r2, d.madd(d, r1 * r1)) / (2.0 * d);
4333    let y = r1.madd(r1, -(x * x)).max(0.0).sqrt();
4334    let linear = Tolerance::new().linear;
4335    let feet = if 2.0 * y <= linear {
4336        vec![toward * x]
4337    } else {
4338        vec![toward * x + side * y, toward * x - side * y]
4339    };
4340    let on_second = |p: Point3| {
4341        let w = p - c2.origin();
4342        ((w - c2.axis() * w.dot(c2.axis())).length() - r2).abs() <= linear
4343    };
4344    let mut rulings = Vec::with_capacity(feet.len());
4345    for foot in feet {
4346        let base = c1.origin() + foot;
4347        let (from, to) = (base + axis * lo, base + axis * hi);
4348        if !on_second(from) || !on_second(to) {
4349            return Ok(None);
4350        }
4351        rulings.push(ruling_segment(from, to, |p| {
4352            (c1.project_point(p), c2.project_point(p))
4353        })?);
4354    }
4355    Ok(Some(rulings))
4356}
4357
4358/// A straight intersection curve from `from` to `to`, carrying its ends and
4359/// middle as points.
4360fn ruling_segment(
4361    from: Point3,
4362    to: Point3,
4363    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
4364) -> Result<IntersectionCurve, MathError> {
4365    let curve = NurbsCurve::new(1, vec![0.0, 0.0, 1.0, 1.0], vec![from, to], vec![1.0, 1.0])?;
4366    let points = [from, from + (to - from) * 0.5, to]
4367        .into_iter()
4368        .map(|point| {
4369            let (param1, param2) = params(point);
4370            IntersectionPoint {
4371                point,
4372                param1,
4373                param2,
4374            }
4375        })
4376        .collect();
4377    Ok(IntersectionCurve { curve, points })
4378}
4379
4380/// Algebraic cylinder-cylinder intersection for non-coaxial cylinders.
4381///
4382/// For two cylinders with axes that are NOT parallel, the intersection
4383/// consists of up to two closed space curves. These are found by
4384/// parameterizing one cylinder's angular coordinate `u ∈ [0, 2π]` and
4385/// solving a quadratic in the axial parameter `v` to find where each
4386/// "ring" of cylinder A sits on cylinder B.
4387///
4388/// The quadratic is:
4389///   `v²·(1 - α²) + 2v·(q·a₁ - α·q·a₂) + (|q|² - (q·a₂)² - r₂²) = 0`
4390/// where `α = a₁·a₂`, `q(u)` is the radial point on cylinder 1 minus
4391/// cylinder 2's origin, `a₁`/`a₂` are the cylinder axes, and `r₂` is
4392/// cylinder 2's radius.
4393#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
4394fn algebraic_cylinder_cylinder(
4395    c1: &CylindricalSurface,
4396    c2: &CylindricalSurface,
4397) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4398    if let Some(halves) = crossing_equal_cylinders(c1, c2)? {
4399        return Ok(Some(halves));
4400    }
4401    let alpha = c1.axis().dot(c2.axis());
4402    let a_coeff = 1.0 - alpha * alpha;
4403
4404    // Should only be called for non-parallel axes.
4405    if a_coeff.abs() < 1e-12 {
4406        return Ok(None);
4407    }
4408
4409    let r1 = c1.radius();
4410    let r2 = c2.radius();
4411    let o1 = c1.origin();
4412    let o2 = c2.origin();
4413    let a1 = c1.axis();
4414    let a2 = c2.axis();
4415
4416    // Separation check: distance between axes vs sum of radii.
4417    // Closest approach of two skew lines:
4418    let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
4419    let cross = a1.cross(a2);
4420    let cross_len = cross.length();
4421    if cross_len > 1e-12 {
4422        let axis_dist = delta.dot(cross).abs() / cross_len;
4423        if axis_dist > r1 + r2 + Tolerance::new().linear {
4424            return Ok(Some(vec![])); // No intersection
4425        }
4426    }
4427
4428    // Solve every ruling of one cylinder against the other. When EVERY
4429    // ruling of the swept cylinder meets the other (the thinner of two
4430    // crossing tubes), the two roots trace the curve's two closed loops.
4431    // Swept the other way only a window of rulings meets, and each root
4432    // traces an open arc of one loop.
4433    let roots = |sweep: &CylindricalSurface, other: &CylindricalSurface| {
4434        let (o, a, radius) = (other.origin(), other.axis(), other.radius());
4435        let alpha = sweep.axis().dot(a);
4436        let quad = 1.0 - alpha * alpha;
4437        let (axis, sweep) = (sweep.axis(), sweep.clone());
4438        move |u: f64| {
4439            let q = sweep.evaluate(u, 0.0) - o;
4440            let (q_a1, q_a2) = (q.dot(axis), q.dot(a));
4441            let b = 2.0 * (q_a1 - alpha * q_a2);
4442            let c = q.dot(q) - q_a2 * q_a2 - radius * radius;
4443            ruling_quadratic(quad, b, c)
4444        }
4445    };
4446    let (roots1, roots2) = (roots(c1, c2), roots(c2, c1));
4447    let samples1 = ruling_samples(c1, &roots1);
4448    let loops = if samples1.iter().all(Option::is_some) {
4449        closed_ruling_loops(c1, &roots1, &samples1)
4450    } else {
4451        let samples2 = ruling_samples(c2, &roots2);
4452        if samples2.iter().all(Option::is_some) {
4453            closed_ruling_loops(c2, &roots2, &samples2)
4454        } else if samples1.iter().any(Option::is_some) {
4455            partial_ruling_loops(c1, &roots1, &samples1)
4456        } else {
4457            partial_ruling_loops(c2, &roots2, &samples2)
4458        }
4459    };
4460    if loops.is_empty() {
4461        return Ok(None);
4462    }
4463    Ok(Some(fit_ruling_loops(&loops, |p| {
4464        (c1.project_point(p), c2.project_point(p))
4465    })))
4466}
4467
4468/// A cone and a cylinder whose axes are not parallel, traced along the
4469/// cylinder's rulings. A ruling `q + t w` meets the cone's double quadric
4470/// `|p - apex|^2 = h^2 / sin^2(half_angle)`, with `h` the offset along the
4471/// cone's axis, where a quadratic in `t` vanishes. `None` (the marcher's
4472/// case) when a ruling meets the far nappe, where no cone face lies, when
4473/// the rulings run along the cone's generators, or when no ruling meets it.
4474fn ruling_cone_cylinder(
4475    cone: &ConicalSurface,
4476    cyl: &CylindricalSurface,
4477    cone_first: bool,
4478) -> Option<Vec<IntersectionCurve>> {
4479    let (sin_t, cos_t) = cone.half_angle().sin_cos();
4480    if sin_t < 1e-12 || cos_t < 1e-12 {
4481        return None;
4482    }
4483    let (apex, d, w) = (cone.apex(), cone.axis(), cyl.axis());
4484    let s = 1.0 / (sin_t * sin_t);
4485    let alpha = w.dot(d);
4486    let quad = 1.0 - s * alpha * alpha;
4487    if quad.abs() < 1e-9 {
4488        return None;
4489    }
4490    let roots = |u: f64| {
4491        let delta = cyl.evaluate(u, 0.0) - apex;
4492        let (dd, dw) = (delta.dot(d), delta.dot(w));
4493        let b = 2.0 * (dw - s * dd * alpha);
4494        let c = delta.dot(delta) - s * dd * dd;
4495        ruling_quadratic(quad, b, c)
4496    };
4497    let lin_tol = Tolerance::new().linear;
4498    let far_nappe = (0..WINDOW_SCAN * RULING_SAMPLES).any(|k| {
4499        #[allow(clippy::cast_precision_loss)]
4500        let u = TAU * (k as f64 + 0.5) / (WINDOW_SCAN * RULING_SAMPLES) as f64;
4501        let (disc, vp, vm) = roots(u);
4502        disc >= -lin_tol
4503            && [vp, vm]
4504                .iter()
4505                .any(|&t| (cyl.evaluate(u, t) - apex).dot(d) < -lin_tol)
4506    });
4507    if far_nappe {
4508        return None;
4509    }
4510    let samples = ruling_samples(cyl, &roots);
4511    // The samples that truly meet the cone. One that the tolerance alone
4512    // admits lies past its window's end: the end bisected from it, and a
4513    // loop traced from it, lie off the cone.
4514    let meeting: Vec<Option<(Point3, Point3)>> = samples
4515        .iter()
4516        .enumerate()
4517        .map(|(i, &pair)| pair.filter(|_| roots(ruling_u(i)).0 >= 0.0))
4518        .collect();
4519    // A window of meeting rulings that no sample truly meets would vanish
4520    // (a cone's tip just through the wall) while the others still made
4521    // loops; a finer scan finds every window, and one with no such sample
4522    // goes to the marcher. A window with one is sampled afresh between its
4523    // ends, however few samples it holds.
4524    let scan = WINDOW_SCAN * RULING_SAMPLES;
4525    #[allow(clippy::cast_precision_loss)]
4526    let scan_u = |k: usize| TAU * (k as f64 + 0.5) / scan as f64;
4527    let discs: Vec<f64> = (0..scan).map(|k| roots(scan_u(k)).0).collect();
4528    // A window narrower than the scan's step lies between two scan points
4529    // that miss, where the discriminant peaks: each such peak is found, and
4530    // one that reaches the tolerance goes to the marcher.
4531    for k in 0..scan {
4532        let (before, here, after) = (
4533            discs[(k + scan - 1) % scan],
4534            discs[k],
4535            discs[(k + 1) % scan],
4536        );
4537        if here >= -lin_tol || here < before || here < after {
4538            continue;
4539        }
4540        let (mut lo, mut hi) = (scan_u(k) - TAU / scan as f64, scan_u(k) + TAU / scan as f64);
4541        for _ in 0..100 {
4542            let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4543            if roots(a).0 < roots(b).0 {
4544                lo = a;
4545            } else {
4546                hi = b;
4547            }
4548        }
4549        if roots(f64::midpoint(lo, hi)).0 >= -lin_tol {
4550            return None;
4551        }
4552    }
4553    // Ruling sample `i` lies midway between scan points
4554    // `WINDOW_SCAN i + 7` and `WINDOW_SCAN i + 8`.
4555    let meets = |k: usize| discs[k % scan] >= -lin_tol;
4556    if let Some(start) = (0..scan).find(|&k| !meets(k)) {
4557        let mut k = start;
4558        while k < start + scan {
4559            if !meets(k) {
4560                k += 1;
4561                continue;
4562            }
4563            let first = k;
4564            while k < start + scan && meets(k) {
4565                k += 1;
4566            }
4567            let sampled = (first..k).any(|j| {
4568                j % WINDOW_SCAN == WINDOW_SCAN / 2 - 1
4569                    && meeting[(j / WINDOW_SCAN) % RULING_SAMPLES].is_some()
4570            });
4571            if !sampled {
4572                return None;
4573            }
4574        }
4575    }
4576    let loops = if samples.iter().all(Option::is_some) {
4577        closed_ruling_loops(cyl, &roots, &samples)
4578    } else {
4579        partial_ruling_loops(cyl, &roots, &meeting)
4580    };
4581    if loops.is_empty() {
4582        return None;
4583    }
4584    Some(fit_ruling_loops(&loops, |p| {
4585        in_order(cone.project_point(p), cyl.project_point(p), cone_first)
4586    }))
4587}
4588
4589/// A torus and a cylinder whose axes are not parallel, where every ruling
4590/// of the cylinder meets the torus the same nonzero even number of times (a
4591/// rod through the ring's tube): a ruling meets the torus where a quartic in
4592/// its parameter vanishes, and each of its roots, taken in order, sweeps one
4593/// closed loop around the cylinder. `None` (the marcher's case) when the
4594/// count varies between rulings, where the curve turns back between them,
4595/// checked on a scan finer than the sampling so a narrow window of missing
4596/// rulings is not stepped over, and for a spindle torus, whose quartic also
4597/// holds its inner lemon.
4598fn ruling_torus_cylinder(
4599    torus: &ToroidalSurface,
4600    cyl: &CylindricalSurface,
4601    torus_first: bool,
4602) -> Option<Vec<IntersectionCurve>> {
4603    if cyl.axis().dot(torus.z_axis()).abs() > 1.0 - 1e-9
4604        || torus.minor_radius() >= torus.major_radius()
4605    {
4606        return None;
4607    }
4608    let roots = |u: f64| intersect_line_torus(torus, cyl.evaluate(u, 0.0), cyl.axis());
4609    let rows: Vec<Vec<f64>> = (0..RULING_SAMPLES).map(|i| roots(ruling_u(i))).collect();
4610    let count = rows[0].len();
4611    let scan = WINDOW_SCAN * RULING_SAMPLES;
4612    #[allow(clippy::cast_precision_loss)]
4613    if count == 0
4614        || count % 2 == 1
4615        || (0..scan).any(|k| roots(TAU * (k as f64 + 0.5) / scan as f64).len() != count)
4616    {
4617        return None;
4618    }
4619    let loops: Vec<Vec<Point3>> = (0..count)
4620        .map(|j| {
4621            let mut pts: Vec<Point3> = rows
4622                .iter()
4623                .enumerate()
4624                .map(|(i, r)| cyl.evaluate(ruling_u(i), r[j]))
4625                .collect();
4626            pts.push(pts[0]);
4627            pts
4628        })
4629        .collect();
4630    Some(fit_ruling_loops(&loops, |p| {
4631        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
4632    }))
4633}
4634
4635/// A cone and a sphere whose centre is off the cone's axis, where every
4636/// generator of the cone crosses the sphere twice on the cone's nappe (a pin
4637/// through a ball): along a generator `apex + v g` the sphere is a quadratic
4638/// in `v`, and each of its two roots, taken in order, sweeps one closed loop
4639/// around the cone. A ball holding the apex is left once by every generator,
4640/// one loop. `None` when the centre lies on the axis (phase FF takes
4641/// [`exact_cone_sphere`]'s circles there), or the apex on the sphere. A
4642/// sphere only some generators cross goes to [`window_cone_sphere`].
4643fn ruling_cone_sphere(
4644    cone: &ConicalSurface,
4645    sphere: &SphericalSurface,
4646    cone_first: bool,
4647) -> Option<Vec<IntersectionCurve>> {
4648    let (apex, centre, radius) = (cone.apex(), sphere.center(), sphere.radius());
4649    let offset = apex - centre;
4650    let lin_tol = Tolerance::new().linear;
4651    let along = offset.dot(cone.axis());
4652    let across = (offset - cone.axis() * along).length();
4653    if across < lin_tol {
4654        return None;
4655    }
4656    // With the apex inside the ball, `v² + 2hv + K` has roots of opposite
4657    // signs (`K = |offset|² − R² < 0`): every generator leaves the ball once
4658    // ahead of the apex, at `v = √(h² − K) − h`, one loop round the cone.
4659    // Where `h > 0` the root is taken as `−K / (h + √(h² − K))`, free of the
4660    // cancellation.
4661    let k = offset.dot(offset) - radius * radius;
4662    if radius - offset.length() > lin_tol {
4663        let exit = |u: f64| {
4664            let h = (cone.evaluate(u, 1.0) - apex).dot(offset);
4665            let root = h.madd(h, -k).sqrt();
4666            cone.evaluate(u, if h > 0.0 { -k / (h + root) } else { root - h })
4667        };
4668        // A ball that barely holds the apex turns the loop sharply where it
4669        // passes the apex, at the scale of `√−K`: a step whose midpoint
4670        // strays from its chord by a hundredth of the chord (a turn of about
4671        // 0.08 radians) is halved until the turn is resolved.
4672        let mut samples: Vec<(f64, Point3)> = (0..=RULING_SAMPLES)
4673            .map(|i| (ruling_u(i), exit(ruling_u(i))))
4674            .collect();
4675        for _ in 0..10 {
4676            let mut refined = Vec::with_capacity(2 * samples.len());
4677            for pair in samples.windows(2) {
4678                let ((u0, p0), (u1, p1)) = (pair[0], pair[1]);
4679                refined.push(pair[0]);
4680                let um = 0.5 * (u0 + u1);
4681                let pm = exit(um);
4682                let chord = (p1 - p0).length();
4683                if chord > lin_tol && (pm - (p0 + (p1 - p0) * 0.5)).length() > 0.01 * chord {
4684                    refined.push((um, pm));
4685                }
4686            }
4687            refined.extend(samples.last().copied());
4688            if refined.len() == samples.len() {
4689                break;
4690            }
4691            samples = refined;
4692        }
4693        let mut pts: Vec<Point3> = samples.iter().map(|&(_, p)| p).collect();
4694        if let Some(last) = pts.last_mut() {
4695            *last = samples[0].1;
4696        }
4697        return Some(fit_ruling_loops(&[pts], |p| {
4698            in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4699        }));
4700    }
4701    // Both roots along a generator of unit direction `g` (`v` the distance
4702    // from the apex), nearer first, from `h = g·offset`, when it crosses the
4703    // sphere twice ahead of the apex.
4704    let crossing = |h: f64| {
4705        let (disc, vp, vm) = ruling_quadratic(1.0, 2.0 * h, k);
4706        (disc > lin_tol && vm >= lin_tol).then_some((vm, vp))
4707    };
4708    // Around the cone `h` runs between these bounds. Where both roots lie
4709    // ahead of the apex, raising `h` shrinks the discriminant and moves the
4710    // nearer root out, so every generator crosses when the two extreme ones
4711    // do.
4712    let (sin_a, cos_a) = cone.half_angle().sin_cos();
4713    if crossing(sin_a.madd(along, cos_a * across)).is_none()
4714        || crossing(sin_a.madd(along, -cos_a * across)).is_none()
4715    {
4716        return window_cone_sphere(cone, sphere, cone_first);
4717    }
4718    let rows: Vec<(f64, f64)> = (0..RULING_SAMPLES)
4719        .map(|i| crossing((cone.evaluate(ruling_u(i), 1.0) - apex).dot(offset)))
4720        .collect::<Option<_>>()?;
4721    let loops: Vec<Vec<Point3>> = [0, 1]
4722        .iter()
4723        .map(|&j| {
4724            let mut pts: Vec<Point3> = rows
4725                .iter()
4726                .enumerate()
4727                .map(|(i, &(near, far))| {
4728                    cone.evaluate(ruling_u(i), if j == 0 { near } else { far })
4729                })
4730                .collect();
4731            pts.push(pts[0]);
4732            pts
4733        })
4734        .collect();
4735    Some(fit_ruling_loops(&loops, |p| {
4736        in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4737    }))
4738}
4739
4740/// A cone and a sphere off its axis that only some generators cross (a ball
4741/// against the cone's side), with the apex outside the sphere: along the
4742/// generator at `u`, `h(u) = g·(apex − C)` is `c + A cos(u − φ)`, and the
4743/// generator crosses twice ahead of the apex where `h ≤ −√K`, with
4744/// `K = |apex − C|² − R²`. That is one arc of `u`, whose ends are where the
4745/// generator touches the sphere; the section is one loop, the nearer roots
4746/// out along the arc and the farther ones back. Sampled at
4747/// `u = mid − half·cos θ`, the roots' split `±√(h² − K)` changes sign with
4748/// `sin θ` and the loop stays smooth through both touching generators.
4749/// `Some(empty)` when no generator crosses ahead of the apex. `None`, the
4750/// marcher's case, when the apex lies within the sphere, when the centre is
4751/// too near the axis to place the arc, and when every generator reaches the
4752/// sphere (the extremes' test then failed on a touching generator or a root
4753/// at the apex).
4754fn window_cone_sphere(
4755    cone: &ConicalSurface,
4756    sphere: &SphericalSurface,
4757    cone_first: bool,
4758) -> Option<Vec<IntersectionCurve>> {
4759    let offset = cone.apex() - sphere.center();
4760    let lin_tol = Tolerance::new().linear;
4761    if offset.length() - sphere.radius() <= lin_tol {
4762        return None;
4763    }
4764    let k = offset.dot(offset) - sphere.radius() * sphere.radius();
4765    let (sin_a, cos_a) = cone.half_angle().sin_cos();
4766    let (ox, oy) = (offset.dot(cone.x_axis()), offset.dot(cone.y_axis()));
4767    let (c, a) = (sin_a * offset.dot(cone.axis()), cos_a * ox.hypot(oy));
4768    if a < lin_tol {
4769        return None;
4770    }
4771    let reach = (-k.sqrt() - c) / a;
4772    if reach <= -1.0 {
4773        return Some(Vec::new());
4774    }
4775    if reach >= 1.0 {
4776        return None;
4777    }
4778    let (mid, half) = (oy.atan2(ox) + std::f64::consts::PI, reach.acos());
4779    let half = std::f64::consts::PI - half;
4780    let n = RULING_SAMPLES;
4781    let mut pts: Vec<Point3> = (0..n)
4782        .map(|i| {
4783            #[allow(clippy::cast_precision_loss)]
4784            let theta = TAU * i as f64 / n as f64;
4785            let u = half.madd(-theta.cos(), mid);
4786            let h = a.madd((u - mid + std::f64::consts::PI).cos(), c);
4787            let split = h.madd(h, -k).max(0.0).sqrt();
4788            cone.evaluate(u, -h - split.copysign(theta.sin()))
4789        })
4790        .collect();
4791    pts.push(pts[0]);
4792    Some(fit_ruling_loops(&[pts], |p| {
4793        in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4794    }))
4795}
4796
4797/// Scan points per ruling sample when looking for windows of meeting
4798/// rulings.
4799const WINDOW_SCAN: usize = 16;
4800
4801/// Rulings sampled around a swept cylinder, half a step off u = 0 so the
4802/// branches of a self-touching curve (equal crossing cylinders) do not share
4803/// a sample.
4804const RULING_SAMPLES: usize = 128;
4805
4806#[allow(clippy::cast_precision_loss)]
4807fn ruling_u(i: usize) -> f64 {
4808    TAU * (i as f64 + 0.5) / RULING_SAMPLES as f64
4809}
4810
4811/// The discriminant and roots of `quad·v² + b·v + c = 0`.
4812fn ruling_quadratic(quad: f64, b: f64, c: f64) -> (f64, f64, f64) {
4813    let disc = b * b - 4.0 * quad * c;
4814    let root = disc.max(0.0).sqrt();
4815    (disc, (-b + root) / (2.0 * quad), (-b - root) / (2.0 * quad))
4816}
4817
4818/// The two points where each sampled ruling of `sweep` meets the other
4819/// surface, from `roots(u)` (the discriminant and the two axial parameters),
4820/// or `None` for a ruling that misses it.
4821fn ruling_samples(
4822    sweep: &CylindricalSurface,
4823    roots: &impl Fn(f64) -> (f64, f64, f64),
4824) -> Vec<Option<(Point3, Point3)>> {
4825    let lin_tol = Tolerance::new().linear;
4826    (0..RULING_SAMPLES)
4827        .map(|i| {
4828            let u = ruling_u(i);
4829            let (disc, vp, vm) = roots(u);
4830            (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4831        })
4832        .collect()
4833}
4834
4835/// Every ruling meets the other surface: each root traces a closed loop.
4836/// Where the loops pass closest at one ruling they are sampled from it,
4837/// closer together near it, so the fit follows the narrow neck between
4838/// them; where they touch there, they are the two halves of one curve
4839/// crossing itself, each with a corner at that point, which then falls at
4840/// their shared start and end, where the fit keeps it.
4841fn closed_ruling_loops(
4842    sweep: &CylindricalSurface,
4843    roots: &impl Fn(f64) -> (f64, f64, f64),
4844    samples: &[Option<(Point3, Point3)>],
4845) -> Vec<Vec<Point3>> {
4846    let (mut plus, mut minus): (Vec<Point3>, Vec<Point3>) =
4847        if let Some((neck, touching)) = narrowest_ruling(roots) {
4848            let count = 2 * RULING_SAMPLES;
4849            #[allow(clippy::cast_precision_loss)]
4850            (0..count)
4851                .map(|i| {
4852                    let t = i as f64 / count as f64;
4853                    let u = TAU.madd(t - 0.9 * (TAU * t).sin() / TAU, neck);
4854                    let (_, vp, vm) = roots(u);
4855                    if i == 0 && touching {
4856                        let at = sweep.evaluate(u, 0.5 * (vp + vm));
4857                        (at, at)
4858                    } else {
4859                        (sweep.evaluate(u, vp), sweep.evaluate(u, vm))
4860                    }
4861                })
4862                .unzip()
4863        } else {
4864            samples.iter().flatten().copied().unzip()
4865        };
4866    plus.push(plus[0]);
4867    minus.push(minus[0]);
4868    vec![plus, minus]
4869}
4870
4871/// The ruling where the two roots pass closest, when exactly one ruling
4872/// stands out: a local minimum of their gap, scanned finer than the
4873/// sampling and refined, that either closes to within tolerance (the
4874/// roots touch there; the tolerance scales with the widest gap, the loops'
4875/// own size, so the decision does not move with the model) or narrows
4876/// below a quarter of the widest gap while no other minimum does. Equal
4877/// crossing cylinders touch at two rulings and get `None`.
4878fn narrowest_ruling(roots: &impl Fn(f64) -> (f64, f64, f64)) -> Option<(f64, bool)> {
4879    let scan = WINDOW_SCAN * RULING_SAMPLES;
4880    #[allow(clippy::cast_precision_loss)]
4881    let step = TAU / scan as f64;
4882    let gap = |u: f64| {
4883        let (_, vp, vm) = roots(u);
4884        (vp - vm).abs()
4885    };
4886    #[allow(clippy::cast_precision_loss)]
4887    let gaps: Vec<f64> = (0..scan).map(|k| gap(step * k as f64)).collect();
4888    let widest = gaps.iter().copied().fold(0.0, f64::max);
4889    let tol = Tolerance::new().linear * (1.0 + widest);
4890    let mut necks = Vec::new();
4891    for k in 0..scan {
4892        let (before, here, after) = (gaps[(k + scan - 1) % scan], gaps[k], gaps[(k + 1) % scan]);
4893        if here > before || here >= after || here >= 0.25 * widest {
4894            continue;
4895        }
4896        #[allow(clippy::cast_precision_loss)]
4897        let (mut lo, mut hi) = (step * (k as f64 - 1.0), step * (k as f64 + 1.0));
4898        for _ in 0..100 {
4899            let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4900            if gap(a) < gap(b) {
4901                hi = b;
4902            } else {
4903                lo = a;
4904            }
4905        }
4906        let u = 0.5 * (lo + hi);
4907        necks.push((u, gap(u) <= tol));
4908    }
4909    match necks[..] {
4910        [neck] => Some(neck),
4911        _ => None,
4912    }
4913}
4914
4915/// Only windows of rulings meet the other surface: each cyclic window
4916/// carries one loop, out along one root and back along the other, the two
4917/// joined where the discriminant vanishes. Empty when no sample meets it (a
4918/// window narrower than the sampling).
4919///
4920/// Each window is sampled afresh between its two ends, closer together near
4921/// them: a window may hold only a few of the rulings sampled around the whole
4922/// turn, and the roots swing fastest where they join, so a fit through those
4923/// alone strays from the curve by far more than the tolerance (a ball beside a
4924/// wide ring's wall).
4925fn partial_ruling_loops(
4926    sweep: &CylindricalSurface,
4927    roots: &impl Fn(f64) -> (f64, f64, f64),
4928    samples: &[Option<(Point3, Point3)>],
4929) -> Vec<Vec<Point3>> {
4930    let lin_tol = Tolerance::new().linear;
4931    // Where the discriminant vanishes between a meeting ruling and a missing
4932    // one, approached from the meeting side.
4933    let branch_u = |inside: usize, outside: usize| -> f64 {
4934        let (mut lo, mut hi) = (ruling_u(inside), ruling_u(outside));
4935        if (hi - lo).abs() > std::f64::consts::PI {
4936            hi += if hi < lo { TAU } else { -TAU };
4937        }
4938        for _ in 0..60 {
4939            let mid = 0.5 * (lo + hi);
4940            if roots(mid).0 >= 0.0 {
4941                lo = mid;
4942            } else {
4943                hi = mid;
4944            }
4945        }
4946        lo
4947    };
4948    let joint = |u: f64| {
4949        let (_, vp, vm) = roots(u);
4950        sweep.evaluate(u, 0.5 * (vp + vm))
4951    };
4952    let Some(first_gap) = samples.iter().position(Option::is_none) else {
4953        return Vec::new();
4954    };
4955    let mut loops = Vec::new();
4956    let mut k = 0;
4957    while k < RULING_SAMPLES {
4958        let i = (first_gap + k) % RULING_SAMPLES;
4959        if samples[i].is_none() {
4960            k += 1;
4961            continue;
4962        }
4963        let start = i;
4964        let mut run = Vec::new();
4965        while k < RULING_SAMPLES {
4966            let j = (first_gap + k) % RULING_SAMPLES;
4967            let Some(pair) = samples[j] else { break };
4968            run.push(pair);
4969            k += 1;
4970        }
4971        let end = (start + run.len() - 1) % RULING_SAMPLES;
4972        let u_head = branch_u(start, (start + RULING_SAMPLES - 1) % RULING_SAMPLES);
4973        let u_tail = branch_u(end, (end + 1) % RULING_SAMPLES);
4974        let span = (u_tail - u_head).rem_euclid(TAU);
4975        #[allow(clippy::cast_precision_loss)]
4976        let fresh: Option<Vec<(Point3, Point3)>> = (1..RULING_SAMPLES)
4977            .map(|n| {
4978                let t = n as f64 / RULING_SAMPLES as f64;
4979                let u = span.madd(0.5 * (1.0 - (std::f64::consts::PI * t).cos()), u_head);
4980                let (disc, vp, vm) = roots(u);
4981                (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4982            })
4983            .collect();
4984        // A gap inside the window that the sampling stepped over: keep the
4985        // sampled rulings, which stay on one side of it.
4986        let run = fresh.unwrap_or(run);
4987        let (head, tail) = (joint(u_head), joint(u_head + span));
4988        let mut pts = vec![head];
4989        pts.extend(run.iter().map(|p| p.0));
4990        pts.push(tail);
4991        pts.extend(run.iter().rev().map(|p| p.1));
4992        pts.push(head);
4993        loops.push(pts);
4994    }
4995    loops
4996}
4997
4998/// Cubic interpolants through the swept loops, with `params(p)` giving each
4999/// point's parameters on the two surfaces.
5000fn fit_ruling_loops(
5001    loops: &[Vec<Point3>],
5002    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
5003) -> Vec<IntersectionCurve> {
5004    let mut curves = Vec::new();
5005    for pts in loops {
5006        if pts.len() < 4 {
5007            continue;
5008        }
5009        let ipts: Vec<IntersectionPoint> = pts
5010            .iter()
5011            .map(|&p| {
5012                let (param1, param2) = params(p);
5013                IntersectionPoint {
5014                    point: p,
5015                    param1,
5016                    param2,
5017                }
5018            })
5019            .collect();
5020        let degree = 3.min(pts.len() - 1);
5021        if let Ok(curve) = interpolate(pts, degree) {
5022            curves.push(IntersectionCurve {
5023                curve,
5024                points: ipts,
5025            });
5026        }
5027    }
5028    curves
5029}
5030
5031/// Algebraic cone-cylinder intersection for PARALLEL (or antiparallel) axes.
5032///
5033/// When the axes are parallel, every plane perpendicular to them cuts the cone
5034/// in a circle of radius `rho = v * cos(half_angle)` about a FIXED centre and
5035/// the cylinder in a circle of radius `R` about a second FIXED centre, so the
5036/// axis separation `d` is constant in `v`. Two coplanar circles meet at
5037/// `u = phi0 +/- acos((d^2 + rho^2 - R^2) / (2*d*rho))`, giving two branches
5038/// parameterised exactly by the cone's own `v`. The branches exist only where
5039/// `rho` lies in `[|d - R|, d + R]`, which bounds the curve naturally.
5040///
5041/// This replaces the general grid-seeded marcher for the configuration, which
5042/// mis-handles it badly: seeds are accepted anywhere within half the surface
5043/// diagonal of the partner, the march-result dedup only consumes seeds the
5044/// traced polyline passes near, and the survivors are dozens of overlapping
5045/// partial traces of the same curve. Those fragments carry no usable in-face
5046/// span, so a cone corner-round crossed by a boss cylinder never splits (a
5047/// counterbore/countersink meeting a pad — the gridfinity lightweight base).
5048///
5049/// Returns `None` (defer to the caller's other paths) when the axes are not
5050/// parallel, or when they are coaxial — a coaxial pair degenerates to shared
5051/// circles, which [`exact_cone_cylinder`] emits exactly and phase FF calls
5052/// directly. Note that `intersect_analytic_analytic_bounded` does NOT consult
5053/// `exact_cone_cylinder`, so a coaxial pair reaching this path through that
5054/// caller falls through to the marcher; only the FF path gets the exact circles.
5055// Result-wrapped to match the other `try_algebraic_intersection` arms' shape.
5056#[allow(clippy::unnecessary_wraps)]
5057fn algebraic_parallel_cone_cylinder(
5058    cone: &ConicalSurface,
5059    cyl: &CylindricalSurface,
5060    v_range_cone: Option<(f64, f64)>,
5061    v_range_cyl: Option<(f64, f64)>,
5062) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
5063    let axis = cone.axis();
5064    if axis.cross(cyl.axis()).length() > Tolerance::new().angular {
5065        return Ok(None); // Skew or oblique: `ruling_cone_cylinder` traces it.
5066    }
5067
5068    let apex = cone.apex();
5069    let delta = cyl.origin() - apex;
5070    let along = delta.dot(axis);
5071    let perp = delta - axis * along;
5072    let d = perp.length();
5073    if d < 1e-9 {
5074        return Ok(None); // Coaxial — `exact_cone_cylinder` owns this.
5075    }
5076
5077    let (e1, e2) = (cone.x_axis(), cone.y_axis());
5078    let phi0 = perp.dot(e2).atan2(perp.dot(e1));
5079
5080    let (sin_t, cos_t) = cone.half_angle().sin_cos();
5081    if cos_t < 1e-12 || sin_t < 1e-12 {
5082        return Ok(None);
5083    }
5084    let r = cyl.radius();
5085
5086    // Branch existence: |d - R| <= rho <= d + R, with rho = v * cos(half_angle).
5087    let mut v_min = (d - r).abs() / cos_t;
5088    let mut v_max = (d + r) / cos_t;
5089    if v_max <= v_min {
5090        return Ok(Some(vec![]));
5091    }
5092
5093    // Narrow the sampled span to the faces' own extents so the fixed sample
5094    // budget resolves the in-face part of the curve rather than spreading over
5095    // a loop that mostly lies off both patches. A face's crossing can be a
5096    // fraction of a degree of the cone's sweep (the corner-round case above),
5097    // and an unnarrowed sampling puts fewer than one sample across it.
5098    let mut lo = v_min;
5099    let mut hi = v_max;
5100    // Clip EXACTLY to the hints, not to a padded window: an endpoint that lands
5101    // exactly on the face's own v-limit lies ON that boundary rim, so the
5102    // downstream pave machinery anchors it to the rim edge instead of leaving
5103    // the section dangling just past the face.
5104    if let Some((a, b)) = v_range_cone {
5105        let (a, b) = if a <= b { (a, b) } else { (b, a) };
5106        lo = lo.max(a);
5107        hi = hi.min(b);
5108    }
5109    if let Some((a, b)) = v_range_cyl {
5110        // The cylinder's v is a signed distance along its axis from its origin;
5111        // convert both ends to the cone's v via the shared axial direction.
5112        let flip = cyl.axis().dot(axis);
5113        let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
5114        let (a, b) = (to_cone_v(a), to_cone_v(b));
5115        let (a, b) = if a <= b { (a, b) } else { (b, a) };
5116        lo = lo.max(a);
5117        hi = hi.min(b);
5118    }
5119    let (turn_lo, turn_hi) = (v_min, v_max);
5120    v_min = lo.max(v_min);
5121    v_max = hi.min(v_max);
5122    if v_max - v_min <= 1e-12 {
5123        return Ok(Some(vec![]));
5124    }
5125    // A cylinder beside the axis, with both turning points inside both faces,
5126    // meets the cone in a whole loop: traced along the cylinder's rulings,
5127    // each of which meets the nappe once, it comes back as one closed curve,
5128    // which the band split of the cylinder it winds needs. Around the axis
5129    // the loop winds the cone too and stays in two branches, and so does a
5130    // wall passing so near the axis that the loop's bend there, about
5131    // `(d - r) / sqrt(d r)` of a turn wide, spans fewer than a few rulings.
5132    let slack = Tolerance::new().linear;
5133    #[allow(clippy::cast_precision_loss)]
5134    let resolved = d - r > 3.0 * (d * r).sqrt() * TAU / RULING_SAMPLES as f64;
5135    if v_min <= turn_lo + slack && v_max >= turn_hi - slack && resolved {
5136        let mut pts: Vec<Point3> = (0..RULING_SAMPLES)
5137            .map(|i| {
5138                let (sin_u, cos_u) = ruling_u(i).sin_cos();
5139                let foot = cyl.origin() + (cyl.x_axis() * cos_u + cyl.y_axis() * sin_u) * r;
5140                let off = foot - apex;
5141                let across = off - axis * off.dot(axis);
5142                apex + across + axis * (across.length() * sin_t / cos_t)
5143            })
5144            .collect();
5145        pts.push(pts[0]);
5146        return Ok(Some(fit_ruling_loops(&[pts], |p| {
5147            (cone.project_point(p), cyl.project_point(p))
5148        })));
5149    }
5150
5151    let n_samples = 128;
5152    let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
5153    let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
5154    #[allow(clippy::cast_precision_loss)]
5155    for i in 0..=n_samples {
5156        let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
5157        let rho = v * cos_t;
5158        if rho < 1e-12 {
5159            // The apex. `cos_alpha` has rho in its denominator, so it is only
5160            // meaningful in the limit: it tends to 0 (alpha -> pi/2) when the
5161            // cylinder passes exactly through the apex (d == R), and diverges
5162            // otherwise — where the clamp would manufacture a spurious alpha of
5163            // 0 or pi. So keep the apex only in the d == R case, where it is a
5164            // genuine point of the intersection and the shared endpoint at
5165            // which the two branches meet.
5166            if (d - r).abs() < 1e-12 {
5167                let apex = cone.evaluate(phi0, v);
5168                plus.push(apex);
5169                minus.push(apex);
5170            }
5171            continue;
5172        }
5173        let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
5174        let alpha = cos_alpha.acos();
5175        plus.push(cone.evaluate(phi0 + alpha, v));
5176        minus.push(cone.evaluate(phi0 - alpha, v));
5177    }
5178
5179    let mut curves = Vec::new();
5180    for pts in [&plus, &minus] {
5181        // Fewer than four samples in range means this branch does not cross the
5182        // bounded region at all (the other branch may still).
5183        if pts.len() < 4 {
5184            continue;
5185        }
5186        let ipts: Vec<IntersectionPoint> = pts
5187            .iter()
5188            .map(|&p| IntersectionPoint {
5189                point: p,
5190                param1: cone.project_point(p),
5191                param2: cyl.project_point(p),
5192            })
5193            .collect();
5194        let degree = 3.min(pts.len() - 1);
5195        match interpolate(pts, degree) {
5196            Ok(curve) => curves.push(IntersectionCurve {
5197                curve,
5198                points: ipts,
5199            }),
5200            // Emitting only the branch that happened to fit would starve the
5201            // section chain of exactly the piece this path exists to supply —
5202            // the same silent half-answer the marcher's fragments produced.
5203            // Defer the whole pair to the caller's other paths instead.
5204            Err(_) => return Ok(None),
5205        }
5206    }
5207
5208    Ok(Some(curves))
5209}
5210
5211/// How many times a parallel cone-cone branch's fitted curve may be refined
5212/// where it strays.
5213const PARALLEL_CONES_FIT_ROUNDS: usize = 8;
5214
5215/// The distance from `p` to the nappe of `cone` nearest it, for a point near
5216/// the cone's wall: the distance in `p`'s meridian plane to the generator.
5217fn cone_wall_distance(cone: &ConicalSurface, p: Point3) -> f64 {
5218    let rel = p - cone.apex();
5219    let along = rel.dot(cone.axis());
5220    let across = (rel - cone.axis() * along).length();
5221    let (sin, cos) = cone.half_angle().sin_cos();
5222    across.madd(sin, -along * cos)
5223}
5224
5225/// Cone-cone intersection for PARALLEL (or antiparallel) axes that do not
5226/// coincide, with openings of unequal slope (equal slopes give the exact
5227/// conic of [`offset_parallel_cone_cone`]).
5228///
5229/// Every plane across the axes cuts each cone in a circle about a fixed
5230/// centre, the two centres `d` apart, and both radii change linearly with the
5231/// height. Two coplanar circles meet at
5232/// `u = phi0 +/- acos((d^2 + rho1^2 - rho2^2) / (2*d*rho1))` on the first
5233/// cone, which gives two branches parameterised exactly by its own `v`. They
5234/// exist where `|rho1 - rho2| <= d <= rho1 + rho2` on both nappes, conditions
5235/// linear in `v`, and join where one of the first holds with equality, where
5236/// the circles touch. There `u` changes like the square root of the distance
5237/// in `v`, so the samples close in on both ends of the span, and the branches
5238/// end at the one point where the circles touch.
5239///
5240/// Halfway between each pair of points the fitted curve must lie within a
5241/// quarter of the linear tolerance of both cones; where it strays, the
5242/// section's own point there joins the fit.
5243///
5244/// `None` (the marcher's case) when the axes are not parallel to the angular
5245/// tolerance or coincide, when a cone is flat or a line, when a range reaches
5246/// a cone's negative nappe, when nothing bounds the span, or when a fit still
5247/// strays.
5248fn algebraic_parallel_cone_cone(
5249    c1: &ConicalSurface,
5250    c2: &ConicalSurface,
5251    v_range_1: Option<(f64, f64)>,
5252    v_range_2: Option<(f64, f64)>,
5253) -> Option<Vec<IntersectionCurve>> {
5254    let tol = Tolerance::new();
5255    // The span below runs on both cones' positive nappes only.
5256    if [v_range_1, v_range_2]
5257        .into_iter()
5258        .flatten()
5259        .any(|(p, q)| p.min(q) < -tol.linear)
5260    {
5261        return None;
5262    }
5263    let axis = c1.axis();
5264    if axis.cross(c2.axis()).length() > tol.angular {
5265        return None;
5266    }
5267    let sigma = axis.dot(c2.axis()).signum();
5268    let delta = c2.apex() - c1.apex();
5269    let along = delta.dot(axis);
5270    let perp = delta - axis * along;
5271    let d = perp.length();
5272    if d < 1e-9 {
5273        return None;
5274    }
5275    let phi0 = perp.dot(c1.y_axis()).atan2(perp.dot(c1.x_axis()));
5276    let (sin1, cos1) = c1.half_angle().sin_cos();
5277    let (sin2, cos2) = c2.half_angle().sin_cos();
5278    if [sin1, cos1, sin2, cos2].iter().any(|&x| x < 1e-12) {
5279        return None;
5280    }
5281    // The second cone's radius at the first one's `v`, `a + b v`, from the
5282    // height `v sin1` above the first apex.
5283    let slope2 = cos2 / sin2;
5284    let (a, b) = (-sigma * along * slope2, sigma * sin1 * slope2);
5285    // The span, and whether each end is where the circles touch.
5286    let (mut lo, mut hi) = (0.0_f64, f64::INFINITY);
5287    let (mut lo_touch, mut hi_touch) = (false, false);
5288    // Each condition `k v + c >= 0`: the second nappe, then the circles
5289    // meeting (`rho1 + rho2 >= d`, `rho2 - rho1 <= d`, `rho1 - rho2 <= d`).
5290    for (k, c, touch) in [
5291        (b, a, false),
5292        (cos1 + b, a - d, true),
5293        (b - cos1, a + d, true),
5294        (cos1 - b, d - a, true),
5295    ] {
5296        // However small, a slope moves the bound: slopes nearly equal to
5297        // each other hold their condition only far out, past `-c / k`.
5298        if k > 0.0 {
5299            if -c / k > lo {
5300                (lo, lo_touch) = (-c / k, touch);
5301            }
5302        } else if k < 0.0 {
5303            if -c / k < hi {
5304                (hi, hi_touch) = (-c / k, touch);
5305            }
5306        } else if c < 0.0 {
5307            return Some(Vec::new());
5308        }
5309    }
5310    let mut clip = |p: f64, q: f64| {
5311        if p.min(q) > lo {
5312            (lo, lo_touch) = (p.min(q), false);
5313        }
5314        if p.max(q) < hi {
5315            (hi, hi_touch) = (p.max(q), false);
5316        }
5317    };
5318    if let Some((p, q)) = v_range_1 {
5319        clip(p, q);
5320    }
5321    if let Some((p, q)) = v_range_2 {
5322        let to_v1 = |v2: f64| sigma.madd(v2 * sin2, along) / sin1;
5323        clip(to_v1(p), to_v1(q));
5324    }
5325    if !hi.is_finite() {
5326        return None;
5327    }
5328    if hi - lo <= 1e-12 {
5329        return Some(Vec::new());
5330    }
5331
5332    // The two points at `v`, or `None` at the first apex off the second cone.
5333    let at = |v: f64, touch: bool| -> Option<(Point3, Point3)> {
5334        let rho1 = v * cos1;
5335        let rho2 = b.madd(v, a);
5336        if rho1 < 1e-12 {
5337            // `u` means nothing at the apex, a point of the curve only where
5338            // it lies on the second cone.
5339            return ((rho2 - d).abs() < 1e-12).then(|| (c1.apex(), c1.apex()));
5340        }
5341        let cos_alpha = (d.madd(d, rho1 * rho1) - rho2 * rho2) / (2.0 * d * rho1);
5342        if touch {
5343            // Rounding leaves `cos_alpha` off +/-1 there, and `acos` turns
5344            // that into a gap between the branches' ends.
5345            let p = c1.evaluate(
5346                if cos_alpha >= 0.0 {
5347                    phi0
5348                } else {
5349                    phi0 + std::f64::consts::PI
5350                },
5351                v,
5352            );
5353            return Some((p, p));
5354        }
5355        let alpha = cos_alpha.clamp(-1.0, 1.0).acos();
5356        Some((c1.evaluate(phi0 + alpha, v), c1.evaluate(phi0 - alpha, v)))
5357    };
5358    // Samples are spaced evenly in `t`, which runs `v` like a square from
5359    // each end, where `u` runs like the square root of `v`.
5360    let v_at = |t: f64| (hi - lo).madd(0.5 * (1.0 - (std::f64::consts::PI * t).cos()), lo);
5361    let n_samples = 128;
5362    let mut plus: Vec<(f64, Point3)> = Vec::with_capacity(n_samples + 1);
5363    let mut minus: Vec<(f64, Point3)> = Vec::with_capacity(n_samples + 1);
5364    #[allow(clippy::cast_precision_loss)]
5365    for i in 0..=n_samples {
5366        let t = i as f64 / n_samples as f64;
5367        let touch = (i == 0 && lo_touch) || (i == n_samples && hi_touch);
5368        if let Some((p, m)) = at(v_at(t), touch) {
5369            plus.push((t, p));
5370            minus.push((t, m));
5371        }
5372    }
5373
5374    let off = |p: Point3| {
5375        cone_wall_distance(c1, p)
5376            .abs()
5377            .max(cone_wall_distance(c2, p).abs())
5378    };
5379    let mut curves = Vec::new();
5380    for (branch, side) in [(&mut plus, 0), (&mut minus, 1)] {
5381        if branch.len() < 4 {
5382            continue;
5383        }
5384        let mut rounds = 0;
5385        // One branch alone would leave the section chain short of the piece
5386        // this path exists to supply: a branch that fails defers the pair.
5387        let curve = loop {
5388            let positions: Vec<Point3> = branch.iter().map(|&(_, p)| p).collect();
5389            let curve = interpolate(&positions, 3).ok()?;
5390            let params = crate::nurbs::fitting::chord_length_params(&positions);
5391            let errors: Vec<f64> = (0..positions.len() - 1)
5392                .map(|k| off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))))
5393                .collect();
5394            if errors.iter().all(|&e| e <= 0.25 * tol.linear) {
5395                break curve;
5396            }
5397            if rounds == PARALLEL_CONES_FIT_ROUNDS {
5398                return None;
5399            }
5400            rounds += 1;
5401            // Every span within a factor of four of the limit is split, and
5402            // a stray's neighbours too: the fit through new points moves the
5403            // error onto the spans beside them.
5404            let mut split: Vec<usize> = (0..errors.len())
5405                .filter(|&k| errors[k] > 0.0625 * tol.linear)
5406                .flat_map(|k| {
5407                    let stray = errors[k] > 0.25 * tol.linear;
5408                    let (first, last) = if stray {
5409                        (k.saturating_sub(1), k + 1)
5410                    } else {
5411                        (k, k)
5412                    };
5413                    first..=last.min(errors.len() - 1)
5414                })
5415                .collect();
5416            split.sort_unstable();
5417            split.dedup();
5418            for &k in split.iter().rev() {
5419                let t = f64::midpoint(branch[k].0, branch[k + 1].0);
5420                let (p, m) = at(v_at(t), false)?;
5421                branch.insert(k + 1, (t, if side == 0 { p } else { m }));
5422            }
5423        };
5424        let points = branch
5425            .iter()
5426            .map(|&(_, p)| IntersectionPoint {
5427                point: p,
5428                param1: c1.project_point(p),
5429                param2: c2.project_point(p),
5430            })
5431            .collect();
5432        curves.push(IntersectionCurve { curve, points });
5433    }
5434    Some(curves)
5435}
5436
5437/// Algebraic sphere-sphere intersection.
5438///
5439/// Two spheres intersect in a circle lying in the radical plane.
5440/// The radical plane is perpendicular to the line connecting the centers,
5441/// at a distance d1 from center1 where:
5442///   d1 = (D² + R1² - R2²) / (2D)
5443/// and D is the distance between centers.
5444fn algebraic_sphere_sphere(
5445    s1: &SphericalSurface,
5446    s2: &SphericalSurface,
5447) -> Result<Vec<IntersectionCurve>, MathError> {
5448    let c1 = s1.center();
5449    let c2 = s2.center();
5450    let r1 = s1.radius();
5451    let r2 = s2.radius();
5452
5453    let delta = c2 - c1;
5454    let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
5455    let d = d_sq.sqrt();
5456
5457    if d < 1e-12 {
5458        // Concentric spheres: no intersection (unless same radius → degenerate).
5459        return Ok(vec![]);
5460    }
5461
5462    // Check separation conditions.
5463    if d > r1 + r2 + 1e-10 {
5464        return Ok(vec![]); // Too far apart
5465    }
5466    if d + r2.min(r1) + 1e-10 < r1.max(r2) {
5467        return Ok(vec![]); // One inside the other
5468    }
5469
5470    // Distance from c1 to the radical plane along the center line.
5471    let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
5472
5473    // Radius of the intersection circle.
5474    let r_circle_sq = r1 * r1 - d1 * d1;
5475    if r_circle_sq < 0.0 {
5476        // Tangent or no intersection (numerical noise).
5477        if r_circle_sq > -1e-10 {
5478            // Tangent: single point.
5479            let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
5480            let tangent_pt = Point3::new(
5481                c1.x() + axis.x() * d1,
5482                c1.y() + axis.y() * d1,
5483                c1.z() + axis.z() * d1,
5484            );
5485            let ipt = IntersectionPoint {
5486                point: tangent_pt,
5487                param1: (0.0, 0.0),
5488                param2: (0.0, 0.0),
5489            };
5490            // Single-point "curve" — not very useful but correct.
5491            return Ok(vec![IntersectionCurve {
5492                curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
5493                points: vec![ipt],
5494            }]);
5495        }
5496        return Ok(vec![]);
5497    }
5498
5499    let r_circle = r_circle_sq.sqrt();
5500    let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
5501    let center = Point3::new(
5502        c1.x() + axis.x() * d1,
5503        c1.y() + axis.y() * d1,
5504        c1.z() + axis.z() * d1,
5505    );
5506
5507    // Build a reference frame for the circle.
5508    let basis = Frame3::from_normal(center, axis)?;
5509    let u_dir = basis.x;
5510    let v_dir = basis.y;
5511
5512    // Sample points along the circle for the IntersectionCurve.
5513    let n_samples = 33; // Odd for symmetry
5514    let mut points = Vec::with_capacity(n_samples);
5515    #[allow(clippy::cast_precision_loss)]
5516    for i in 0..n_samples {
5517        let theta = TAU * i as f64 / (n_samples - 1) as f64;
5518        let (sin_t, cos_t) = theta.sin_cos();
5519        let pt = Point3::new(
5520            center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
5521            center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
5522            center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
5523        );
5524        points.push(IntersectionPoint {
5525            point: pt,
5526            param1: (0.0, 0.0),
5527            param2: (0.0, 0.0),
5528        });
5529    }
5530
5531    let curve = conic_loop(center, u_dir, v_dir, r_circle, r_circle)?;
5532
5533    Ok(vec![IntersectionCurve { curve, points }])
5534}
5535
5536/// Newton correction: project a point back onto the intersection curve
5537/// of two analytic surfaces. Solves the 3×3 system:
5538///   δ · na = -da  (eliminate distance to surface A)
5539///   δ · nb = -db  (eliminate distance to surface B)
5540///   δ · t  = 0    (minimal correction, perpendicular to tangent)
5541#[allow(clippy::too_many_arguments)]
5542fn correct_to_intersection(
5543    a: &AnalyticSurface<'_>,
5544    b: &AnalyticSurface<'_>,
5545    surf_a: &dyn Fn(f64, f64) -> Point3,
5546    norm_a: &dyn Fn(f64, f64) -> Vec3,
5547    surf_b: &dyn Fn(f64, f64) -> Point3,
5548    norm_b: &dyn Fn(f64, f64) -> Vec3,
5549    point: Point3,
5550    u_range_a: (f64, f64),
5551    v_range_a: (f64, f64),
5552    u_range_b: (f64, f64),
5553    v_range_b: (f64, f64),
5554    max_iters: usize,
5555) -> Point3 {
5556    let mut p = point;
5557    for _ in 0..max_iters {
5558        let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
5559        let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
5560        let pa = surf_a(ua, va);
5561        let pb = surf_b(ub, vb);
5562        let na = norm_a(ua, va);
5563        let nb = norm_b(ub, vb);
5564        let pv = Vec3::new(p.x(), p.y(), p.z());
5565
5566        let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
5567        let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
5568
5569        if da.abs() < 1e-7 && db.abs() < 1e-7 {
5570            break;
5571        }
5572
5573        let t = na.cross(nb);
5574        let t_len = t.length();
5575        if t_len < 1e-10 {
5576            // Surfaces are tangent — fall back to midpoint.
5577            return Point3::new(
5578                (pa.x() + pb.x()) * 0.5,
5579                (pa.y() + pb.y()) * 0.5,
5580                (pa.z() + pb.z()) * 0.5,
5581            );
5582        }
5583        let t_hat = t * (1.0 / t_len);
5584
5585        // Solve [na; nb; t_hat] · δ = [-da, -db, 0] via Cramer's rule.
5586        let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
5587            - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
5588            + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
5589        if det.abs() < 1e-15 {
5590            return Point3::new(
5591                (pa.x() + pb.x()) * 0.5,
5592                (pa.y() + pb.y()) * 0.5,
5593                (pa.z() + pb.z()) * 0.5,
5594            );
5595        }
5596        let inv = 1.0 / det;
5597        // Cramer's rule: replace each column of A with rhs = (-da, -db, 0).
5598        let dx = inv
5599            * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
5600                + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
5601        let dy = inv
5602            * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
5603                - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
5604        let dz = inv
5605            * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
5606                + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
5607        let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
5608
5609        // Divergence guard: if the correction moves farther from both
5610        // surfaces, abandon Newton and return the best point so far.
5611        let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
5612        let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
5613        let pc_a = surf_a(uc, vc);
5614        let pc_b = surf_b(ud, vd);
5615        let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
5616        let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
5617            .dot(norm_a(uc, vc))
5618            .abs();
5619        let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
5620            .dot(norm_b(ud, vd))
5621            .abs();
5622        if da_new > da.abs() && db_new > db.abs() {
5623            return p;
5624        }
5625
5626        p = candidate;
5627    }
5628    p
5629}
5630
5631/// The most a march step turns the section's tangent, in radians.
5632const MARCH_TURN: f64 = 0.2;
5633
5634/// The share of the distance to the section's next branch that a march
5635/// step's guess may miss the section by.
5636const MARCH_BASIN: f64 = 0.25;
5637
5638/// The most steps a march takes each way.
5639const MARCH_STEPS: usize = 4096;
5640
5641/// A point of the section of two surfaces, with what a march step from it
5642/// needs.
5643#[derive(Clone, Copy)]
5644struct Station {
5645    p: Point3,
5646    /// The unit tangent of the section, along the march.
5647    t: Vec3,
5648    /// The curvature of the section.
5649    bend: f64,
5650    /// The distance, across the section, at which the two surfaces' second
5651    /// order models through `p` cross again: a lower estimate of how far
5652    /// the section's next branch lies.
5653    gap: f64,
5654}
5655
5656/// The station at `p`, a point of the section of `a` and `b`, its tangent
5657/// along `toward`; `None` where the two surfaces touch there (their
5658/// normals within about 1e-6 of parallel) or a distance has no gradient.
5659///
5660/// The section's curvature vector `k` lies across it, and the curve's
5661/// normal curvature on each surface, the second derivative of its distance
5662/// along the tangent, is `-k . n` for that surface's normal `n`. Across the
5663/// section, each surface's trace is a curve of the curvature its distance
5664/// gives along the trace; two circles that cross at angle `θ`, of
5665/// curvatures `κa` and `κb`, cross again no nearer than `2 sin θ / (κa + κb)`.
5666fn station(
5667    a: &AnalyticSurface<'_>,
5668    b: &AnalyticSurface<'_>,
5669    p: Point3,
5670    toward: Vec3,
5671) -> Option<Station> {
5672    use section_fit::Carrier;
5673    let (_, na) = a.distance(p)?;
5674    let (_, nb) = b.distance(p)?;
5675    let cross = na.cross(nb);
5676    let sin = cross.length();
5677    if sin < 1e-6 {
5678        return None;
5679    }
5680    let mut t = cross * (1.0 / sin);
5681    if t.dot(toward) < 0.0 {
5682        t = -t;
5683    }
5684    let (ka, kb) = (a.bend(p, t)?, b.bend(p, t)?);
5685    let c = na.dot(nb);
5686    let det = sin * sin;
5687    let along_a = c.madd(kb, -ka) / det;
5688    let along_b = c.madd(ka, -kb) / det;
5689    let bend = (2.0 * along_a * along_b)
5690        .madd(c, along_a.madd(along_a, along_b * along_b))
5691        .max(0.0)
5692        .sqrt();
5693    let (qa, qb) = (a.bend(p, t.cross(na))?, b.bend(p, t.cross(nb))?);
5694    let spread = qa.abs() + qb.abs();
5695    let gap = if spread > 0.0 {
5696        2.0 * sin / spread
5697    } else {
5698        f64::INFINITY
5699    };
5700    bend.is_finite().then_some(Station { p, t, bend, gap })
5701}
5702
5703impl Station {
5704    /// The longest step from here: one that turns the tangent by no more
5705    /// than [`MARCH_TURN`], and whose guess along the tangent misses the
5706    /// section by no more than [`MARCH_BASIN`] of the gap.
5707    fn reach(&self, longest: f64) -> f64 {
5708        if self.bend > 0.0 {
5709            longest
5710                .min(MARCH_TURN / self.bend)
5711                .min((2.0 * MARCH_BASIN * self.gap / self.bend).sqrt())
5712        } else {
5713            longest
5714        }
5715    }
5716}
5717
5718/// A point within `reach` of `p` where both surfaces pass and their normals
5719/// lie parallel, each within the rounding of the point's place: a point
5720/// where the section's branches meet or the surfaces touch. Both distances
5721/// must lie within the rounding of the point against the surfaces' frames,
5722/// `near`. The normals must lie within the rounding each picks up from its
5723/// curvature times its distance from its frame, or, where that is less,
5724/// within the angle whose cosine rounds to one, the square root of the
5725/// float spacing, 1.5e-8: a leg and the bend on its top, turned and moved,
5726/// touch at 4e-9 off parallel, after the rounding of the turn.
5727///
5728/// Gauss-Newton steps find the point near `p` on `a` where `b`'s normal
5729/// lies along `a`'s, from `a`'s distance and the cross product of the
5730/// normals, whose derivative along each axis comes from each distance's
5731/// second derivative (its value along `e + v` less that along `e - v` is
5732/// four times `e . H v`). Each step is taken once, twice or three times,
5733/// whichever misses least: where the touch is of higher order the cross
5734/// product falls as a power of the way left, and a single step covers only
5735/// a share of it, as Newton steps do on a double root, and then moves back
5736/// onto `a` along its normal. The steps run until they stop gaining, and
5737/// the best point is read. `None` where it fails:
5738/// two surfaces that cross at a shallow angle, 2e-6, with no touch near,
5739/// keep their normals that far apart.
5740fn singular_point(
5741    a: &AnalyticSurface<'_>,
5742    b: &AnalyticSurface<'_>,
5743    p: Point3,
5744    reach: f64,
5745) -> Option<Point3> {
5746    use section_fit::Carrier;
5747    let axes = [
5748        Vec3::new(1.0, 0.0, 0.0),
5749        Vec3::new(0.0, 1.0, 0.0),
5750        Vec3::new(0.0, 0.0, 1.0),
5751    ];
5752    let miss = |x: Point3| {
5753        let (Some((da, na)), Some((_, nb))) = (a.distance(x), b.distance(x)) else {
5754            return f64::INFINITY;
5755        };
5756        da.hypot(reach * na.cross(nb).length())
5757    };
5758    let mut best: Option<(f64, Point3, bool)> = None;
5759    let mut q = p;
5760    for _ in 0..32 {
5761        let (da, na) = a.distance(q)?;
5762        let (db, nb) = b.distance(q)?;
5763        let cross = na.cross(nb);
5764        let mut hessians = [[Vec3::new(0.0, 0.0, 0.0); 3]; 2];
5765        for (h, s) in hessians.iter_mut().zip([a, b]) {
5766            for (j, &v) in axes.iter().enumerate() {
5767                let mut row = [0.0; 3];
5768                for (k, &e) in axes.iter().enumerate() {
5769                    row[k] = 0.25 * (s.bend(q, e + v)? - s.bend(q, e - v)?);
5770                }
5771                h[j] = Vec3::new(row[0], row[1], row[2]);
5772            }
5773        }
5774        let curvature = |h: &[Vec3; 3]| h.iter().fold(0.0, |m: f64, v| m.max(v.length()));
5775        let (ka, kb) = (curvature(&hessians[0]), curvature(&hessians[1]));
5776        let near = 64.0 * f64::EPSILON * (a.scale(q) + b.scale(q));
5777        let parallel = (64.0 * f64::EPSILON * ka.madd(a.scale(q), kb.madd(b.scale(q), 2.0)))
5778            .max(f64::EPSILON.sqrt());
5779        let here = cross.length();
5780        let holds = da.abs() <= near && db.abs() <= near && here <= parallel;
5781        if best.is_none_or(|(c, _, _)| here < c) {
5782            best = Some((here, q, holds));
5783        }
5784        // Rows: `a`'s distance, then the cross product's parts, each a
5785        // length once scaled by `reach`.
5786        let mut rows = vec![(na, da)];
5787        for (k, &e) in axes.iter().enumerate() {
5788            let grad = Vec3::new(
5789                (hessians[0][0].cross(nb) + na.cross(hessians[1][0])).dot(e),
5790                (hessians[0][1].cross(nb) + na.cross(hessians[1][1])).dot(e),
5791                (hessians[0][2].cross(nb) + na.cross(hessians[1][2])).dot(e),
5792            );
5793            let value = [cross.x(), cross.y(), cross.z()][k];
5794            rows.push((grad * reach, value * reach));
5795        }
5796        let mut m = [[0.0; 3]; 3];
5797        let mut rhs = [0.0; 3];
5798        for (g, r) in &rows {
5799            let g = [g.x(), g.y(), g.z()];
5800            for i in 0..3 {
5801                rhs[i] -= g[i] * r;
5802                for j in 0..3 {
5803                    m[i][j] = g[i].madd(g[j], m[i][j]);
5804                }
5805            }
5806        }
5807        let damp = 1e-12 * (m[0][0] + m[1][1] + m[2][2]);
5808        for (i, row) in m.iter_mut().enumerate() {
5809            row[i] += damp;
5810        }
5811        let Some(step) = solve3(m, rhs) else {
5812            break;
5813        };
5814        // Each candidate moves back onto `a` along its normal, where a touch
5815        // leaves it on `b` too.
5816        let onto_a = |x: Point3| a.distance(x).map_or(x, |(d, n)| x - n * d);
5817        let next = [1.0, 2.0, 3.0]
5818            .iter()
5819            .map(|&k| onto_a(q + step * k))
5820            .min_by(|x, y| miss(*x).total_cmp(&miss(*y)))?;
5821        if (next - p).length() > reach || miss(next) >= miss(q) {
5822            break;
5823        }
5824        q = next;
5825    }
5826    best.and_then(|(_, x, holds)| holds.then_some(x))
5827}
5828
5829/// The solution of `m x = rhs` for a symmetric 3 by 3 `m`, by Cramer's rule;
5830/// `None` where `m` is singular.
5831fn solve3(m: [[f64; 3]; 3], rhs: [f64; 3]) -> Option<Vec3> {
5832    let det = |c: [[f64; 3]; 3]| {
5833        c[0][0] * c[1][1].madd(c[2][2], -c[1][2] * c[2][1])
5834            - c[0][1] * c[1][0].madd(c[2][2], -c[1][2] * c[2][0])
5835            + c[0][2] * c[1][0].madd(c[2][1], -c[1][1] * c[2][0])
5836    };
5837    let d = det(m);
5838    if d.abs() <= 0.0 || !d.is_finite() {
5839        return None;
5840    }
5841    let mut out = [0.0; 3];
5842    for (k, x) in out.iter_mut().enumerate() {
5843        let mut c = m;
5844        for (row, r) in c.iter_mut().zip(rhs) {
5845            row[k] = r;
5846        }
5847        *x = det(c) / d;
5848    }
5849    Some(Vec3::new(out[0], out[1], out[2]))
5850}
5851
5852/// March along the section of two surfaces from `seed`, a point on it, each
5853/// way, until the march comes back to the seed, leaves a patch or the
5854/// region, or stops by a point where the section's branches meet or the
5855/// surfaces touch (see [`singular_point`]); `None` where it stops anywhere
5856/// else or runs out of steps.
5857///
5858/// Each step goes along the tangent, no farther than [`Station::reach`],
5859/// and moves onto the section by Newton steps. It is taken again at half the
5860/// length unless the move onto the section stays within [`MARCH_BASIN`] of
5861/// the gap at both ends and on the sheets the seed lies on (a cone's nappe,
5862/// a torus's tube), so the step stays on its branch, the tangent turns by
5863/// less than twice [`MARCH_TURN`], and the step goes forward by at least
5864/// half its length (so it does not pass a turn of the section). A march
5865/// closes where the seed lies within its next step, ahead along the
5866/// tangent and near it, and the section there runs the way it ran from the
5867/// seed: the march comes back to the seed along the curve, from the seed's
5868/// own side.
5869#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
5870fn march_analytic_intersection(
5871    a: &AnalyticSurface<'_>,
5872    b: &AnalyticSurface<'_>,
5873    surf_a: &dyn Fn(f64, f64) -> Point3,
5874    norm_a: &dyn Fn(f64, f64) -> Vec3,
5875    surf_b: &dyn Fn(f64, f64) -> Point3,
5876    norm_b: &dyn Fn(f64, f64) -> Vec3,
5877    seed: Point3,
5878    u_range_a: (f64, f64),
5879    v_range_a: (f64, f64),
5880    u_range_b: (f64, f64),
5881    v_range_b: (f64, f64),
5882    initial_step: f64,
5883    u_periodic_a: bool,
5884    u_periodic_b: bool,
5885    region: Option<Aabb3>,
5886) -> Option<Vec<Point3>> {
5887    let h_max = initial_step * 4.0;
5888    let h_min = initial_step * 1e-6;
5889
5890    // Whether `q` lies off either patch, its feet clamped to a patch's edge.
5891    let off_patch = |q: Point3| {
5892        let (ua, va) = project_analytic(a, q, u_range_a, v_range_a);
5893        let (ub, vb) = project_analytic(b, q, u_range_b, v_range_b);
5894        (!u_periodic_a && (ua <= u_range_a.0 || ua >= u_range_a.1))
5895            || va <= v_range_a.0
5896            || va >= v_range_a.1
5897            || (!u_periodic_b && (ub <= u_range_b.0 || ub >= u_range_b.1))
5898            || vb <= v_range_b.0
5899            || vb >= v_range_b.1
5900    };
5901    // The point on the intersection that the step from `from` reaches.
5902    let on_curve = |from: Point3, step: Vec3| {
5903        correct_to_intersection(
5904            a,
5905            b,
5906            surf_a,
5907            norm_a,
5908            surf_b,
5909            norm_b,
5910            from + step,
5911            u_range_a,
5912            v_range_a,
5913            u_range_b,
5914            v_range_b,
5915            5,
5916        )
5917    };
5918    // The last point on the intersection still on both patches along the
5919    // step from `from`, whose end lies off a patch: on the patch's edge the
5920    // step crosses, bisected; `None` when the step leaves at once.
5921    let last_on_patch = |from: Point3, step: Vec3| {
5922        let (mut lo, mut hi) = (0.0, 1.0);
5923        for _ in 0..48 {
5924            let s = f64::midpoint(lo, hi);
5925            if off_patch(on_curve(from, step * s)) {
5926                hi = s;
5927            } else {
5928                lo = s;
5929            }
5930        }
5931        (lo > 0.0).then(|| on_curve(from, step * lo))
5932    };
5933
5934    let start = station(a, b, seed, Vec3::new(0.0, 0.0, 0.0))?;
5935    // The sheets of both surfaces a point lies on: a step stays on its own.
5936    let sheets = |q: Point3| {
5937        use section_fit::Carrier;
5938        (a.sheet(q), b.sheet(q))
5939    };
5940    let home_sheets = sheets(seed);
5941
5942    // March forward from seed, collecting points.
5943    let mut forward = Vec::new();
5944    // March backward from seed, collecting points (reversed at end).
5945    let mut backward = Vec::new();
5946
5947    // A loop the forward march closes is whole: marched back as well, it
5948    // would come round a second time.
5949    let mut looped = false;
5950    for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
5951        if looped {
5952            break;
5953        }
5954        let home = start.t * direction;
5955        let mut here = Station { t: home, ..start };
5956        let mut h = here.reach(h_max.min(initial_step));
5957        let mut ended = false;
5958
5959        for _ in 0..MARCH_STEPS {
5960            h = h.min(here.reach(h_max));
5961            if !points.is_empty() {
5962                let to_seed = seed - here.p;
5963                let ahead = to_seed.dot(here.t);
5964                let aside = (to_seed - here.t * ahead).length();
5965                if ahead > 0.0
5966                    && ahead <= h
5967                    && aside <= MARCH_TURN * ahead
5968                    && aside <= MARCH_BASIN * here.gap.min(start.gap)
5969                    && home.dot(here.t) >= (2.0 * MARCH_TURN).cos()
5970                {
5971                    points.push(seed);
5972                    looped = true;
5973                    ended = true;
5974                    break;
5975                }
5976            }
5977
5978            let next = loop {
5979                if h < h_min {
5980                    break None;
5981                }
5982                let guess = Point3::new(
5983                    h.madd(here.t.x(), here.p.x()),
5984                    h.madd(here.t.y(), here.p.y()),
5985                    h.madd(here.t.z(), here.p.z()),
5986                );
5987                let taken = settle_on_section(a, b, guess)
5988                    .and_then(|q| station(a, b, q, here.t))
5989                    .filter(|next| {
5990                        let missed = (next.p - guess).length();
5991                        missed <= MARCH_BASIN * here.gap.min(next.gap)
5992                            && missed <= 0.5 * h
5993                            && next.t.dot(here.t) >= (2.0 * MARCH_TURN).cos()
5994                            && (next.p - here.p).dot(here.t) >= 0.5 * h
5995                            && sheets(next.p) == home_sheets
5996                    });
5997                match taken {
5998                    Some(next) => break Some(next),
5999                    None => h *= 0.5,
6000                }
6001            };
6002            // A step a millionth of the first that still leaves its branch,
6003            // turns back, or finds no crossing ends the curve only on a
6004            // point near where the section's branches meet or the surfaces
6005            // touch, as at a patch's edge. Anywhere else the march cannot
6006            // follow the section, and the section is refused.
6007            let Some(next) = next else {
6008                let end = singular_point(a, b, here.p, initial_step)?;
6009                points.push(end);
6010                ended = true;
6011                break;
6012            };
6013
6014            if off_patch(next.p) {
6015                // The step crosses a patch's edge. End the curve on that
6016                // edge, neither a step short of it nor past it, where the
6017                // faces' other sections meet it.
6018                points.extend(last_on_patch(here.p, next.p - here.p));
6019                ended = true;
6020                break;
6021            }
6022            if region.is_some_and(|r| !r.contains_point(next.p)) {
6023                points.push(next.p);
6024                ended = true;
6025                break;
6026            }
6027            points.push(next.p);
6028            here = next;
6029            h *= 2.0;
6030        }
6031        if !ended {
6032            return None;
6033        }
6034    }
6035
6036    // Assemble result: backward (reversed) + seed + forward
6037    backward.reverse();
6038    let mut result = backward;
6039    result.push(seed);
6040    result.append(&mut forward);
6041
6042    // A seed settles onto the intersection with its feet clamped to the
6043    // patches, so one can lie just past a patch's edge and end the curve
6044    // there: move that end back onto the edge.
6045    if let [first, second, ..] = result[..]
6046        && off_patch(first)
6047        && !off_patch(second)
6048        && let Some(edge) = last_on_patch(second, first - second)
6049    {
6050        result[0] = edge;
6051    }
6052    if let [.., second, last] = result[..]
6053        && off_patch(last)
6054        && !off_patch(second)
6055        && let Some(edge) = last_on_patch(second, last - second)
6056        && let Some(end) = result.last_mut()
6057    {
6058        *end = edge;
6059    }
6060
6061    // Settle each point onto the intersection curve, to rounding where
6062    // Newton steps on both surfaces' distances converge.
6063    for pt in &mut result {
6064        let from = *pt;
6065        *pt = settle_on_section(a, b, from)
6066            .filter(|on| (*on - from).length() <= initial_step)
6067            .unwrap_or_else(|| {
6068                correct_to_intersection(
6069                    a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b,
6070                    v_range_b, 5,
6071                )
6072            });
6073    }
6074
6075    Some(result)
6076}
6077
6078/// Project a 3D point onto an analytic surface using the surface's
6079/// analytical projection method. Falls back to grid search for surface
6080/// types without analytical projection.
6081fn project_analytic(
6082    surface: &AnalyticSurface<'_>,
6083    point: Point3,
6084    u_range: (f64, f64),
6085    v_range: (f64, f64),
6086) -> (f64, f64) {
6087    match surface {
6088        AnalyticSurface::Cylinder(cyl) => {
6089            let (u, v) = cyl.project_point(point);
6090            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6091        }
6092        AnalyticSurface::Sphere(sphere) => {
6093            let (u, v) = sphere.project_point(point);
6094            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6095        }
6096        // A foot on the negative nappe lies along `-radial(u)` from the apex:
6097        // its `u` is half a turn from the point's own side of the axis.
6098        AnalyticSurface::Cone(cone) => {
6099            let (u, v) = cone.project_point(point);
6100            let v = v.clamp(v_range.0, v_range.1);
6101            let u = if v < 0.0 {
6102                (u + std::f64::consts::PI).rem_euclid(TAU)
6103            } else {
6104                u
6105            };
6106            (u.clamp(u_range.0, u_range.1), v)
6107        }
6108        AnalyticSurface::Torus(torus) => {
6109            let (u, v) = torus.project_point(point);
6110            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
6111        }
6112    }
6113}
6114
6115/// Returns `true` if the surface's u-parameter is periodic (wraps around 2π).
6116/// All current `AnalyticSurface` variants have periodic u — this is trivially
6117/// true today but exists as a guard for future non-periodic analytic types.
6118fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
6119    matches!(
6120        surface,
6121        AnalyticSurface::Cylinder(_)
6122            | AnalyticSurface::Cone(_)
6123            | AnalyticSurface::Sphere(_)
6124            | AnalyticSurface::Torus(_)
6125    )
6126}
6127
6128/// Extract closures and parameter ranges for an analytic surface.
6129#[allow(clippy::type_complexity)]
6130fn surface_closures<'a>(
6131    surface: &'a AnalyticSurface<'a>,
6132) -> (
6133    Box<dyn Fn(f64, f64) -> Point3 + 'a>,
6134    Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
6135    (f64, f64),
6136    (f64, f64),
6137) {
6138    match surface {
6139        AnalyticSurface::Cylinder(cyl) => (
6140            Box::new(|u, v| cyl.evaluate(u, v)),
6141            Box::new(|u, v| cyl.normal(u, v)),
6142            (0.0, TAU),
6143            (-1.0, 1.0),
6144        ),
6145        AnalyticSurface::Cone(cone) => (
6146            Box::new(|u, v| cone.evaluate(u, v)),
6147            Box::new(|u, v| cone.normal(u, v)),
6148            (0.0, TAU),
6149            (0.01, 2.0),
6150        ),
6151        AnalyticSurface::Sphere(sphere) => (
6152            Box::new(|u, v| sphere.evaluate(u, v)),
6153            Box::new(|u, v| sphere.normal(u, v)),
6154            (0.0, TAU),
6155            (-FRAC_PI_2, FRAC_PI_2),
6156        ),
6157        AnalyticSurface::Torus(torus) => (
6158            Box::new(|u, v| torus.evaluate(u, v)),
6159            Box::new(|u, v| torus.normal(u, v)),
6160            (0.0, TAU),
6161            (0.0, TAU),
6162        ),
6163    }
6164}
6165
6166#[cfg(test)]
6167#[allow(clippy::unwrap_used, clippy::expect_used)]
6168mod tests {
6169    use super::*;
6170    use crate::tolerance::Tolerance;
6171
6172    /// Arcs of a cone's hyperbola (a plane parallel to the axis) and parabola
6173    /// (a plane parallel to a ruling) between two of their sampled points
6174    /// stay on both the plane and the cone everywhere, not just at samples.
6175    #[test]
6176    fn plane_cone_conic_arcs_lie_on_both_surfaces() {
6177        let half_angle = 1.1_f64;
6178        let cone = ConicalSurface::new(
6179            Point3::new(0.0, 0.0, 0.0),
6180            Vec3::new(0.0, 0.0, 1.0),
6181            half_angle,
6182        )
6183        .unwrap();
6184        let ruling = Vec3::new(half_angle.sin(), 0.0, half_angle.cos());
6185        for (normal, d) in [(Vec3::new(1.0, 0.0, 0.0), 0.5), (ruling, 1.0)] {
6186            let chains =
6187                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, d, 10.0)
6188                    .unwrap();
6189            let chain = chains
6190                .iter()
6191                .find_map(|c| match c {
6192                    ExactIntersectionCurve::Points(chain) => Some(chain),
6193                    _ => None,
6194                })
6195                .expect("a parabola or hyperbola section is sampled");
6196            let (from, to) = (chain[2], chain[chain.len() - 3]);
6197            let arc = plane_cone_conic_arc(&cone, normal, d, from, to)
6198                .unwrap()
6199                .expect("an exact arc");
6200            let (t0, t1) = arc.domain();
6201            assert!((arc.evaluate(t0) - from).length() < 1e-12);
6202            assert!((arc.evaluate(t1) - to).length() < 1e-12);
6203            for i in 0..=200 {
6204                let q = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0);
6205                let w = q - Point3::new(0.0, 0.0, 0.0);
6206                let off_plane = (normal.dot(w) - d).abs();
6207                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
6208                assert!(off_plane < 1e-9, "off the plane by {off_plane}");
6209                assert!(off_cone < 1e-9, "off the cone by {off_cone}");
6210            }
6211        }
6212    }
6213
6214    /// A plane a few 1e-10 short of parallel to a ruling cuts a vast ellipse
6215    /// that the parabola's closed form only approximates: the arc is either
6216    /// declined or on the cone, and an arc with coincident ends is declined.
6217    #[test]
6218    fn plane_cone_conic_arc_declines_a_near_parabolic_ellipse() {
6219        let half_angle = 1.1_f64;
6220        let cone = ConicalSurface::new(
6221            Point3::new(0.0, 0.0, 0.0),
6222            Vec3::new(0.0, 0.0, 1.0),
6223            half_angle,
6224        )
6225        .unwrap();
6226        for shortfall in [1e-10, 3e-10, 8e-10] {
6227            let tilt = half_angle - shortfall / (2.0 * half_angle).sin();
6228            let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
6229            let chains =
6230                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, 1.0, 10.0)
6231                    .unwrap();
6232            let Some(chain) = chains.iter().find_map(|c| match c {
6233                ExactIntersectionCurve::Points(chain) => Some(chain),
6234                _ => None,
6235            }) else {
6236                continue;
6237            };
6238            let (from, to) = (chain[2], chain[chain.len() - 3]);
6239            assert!(
6240                plane_cone_conic_arc(&cone, normal, 1.0, from, from)
6241                    .unwrap()
6242                    .is_none(),
6243                "coincident ends"
6244            );
6245            let Some(arc) = plane_cone_conic_arc(&cone, normal, 1.0, from, to).unwrap() else {
6246                continue;
6247            };
6248            let (t0, t1) = arc.domain();
6249            for i in 0..=200 {
6250                let w = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0)
6251                    - Point3::new(0.0, 0.0, 0.0);
6252                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
6253                assert!(off_cone < 1e-8, "{shortfall}: off the cone by {off_cone}");
6254            }
6255        }
6256    }
6257
6258    #[test]
6259    fn plane_cylinder_perpendicular() {
6260        let cyl =
6261            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
6262                .unwrap();
6263
6264        // Horizontal plane at z=3 -- produces a circle at height 3.
6265        let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
6266        assert!(!curves.is_empty(), "should find intersection curve");
6267        assert!(
6268            curves[0].points.len() > 10,
6269            "should have many sample points"
6270        );
6271
6272        let tol = Tolerance::loose();
6273        for pt in &curves[0].points {
6274            assert!(
6275                tol.approx_eq(pt.point.z(), 3.0),
6276                "z should be ~3.0, got {}",
6277                pt.point.z()
6278            );
6279            let r = pt.point.x().hypot(pt.point.y());
6280            assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
6281        }
6282    }
6283
6284    #[test]
6285    fn plane_sphere_equator() {
6286        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
6287
6288        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
6289        assert!(!curves.is_empty());
6290
6291        let tol = Tolerance::loose();
6292        for pt in &curves[0].points {
6293            assert!(
6294                tol.approx_eq(pt.point.z(), 0.0),
6295                "z should be ~0, got {}",
6296                pt.point.z()
6297            );
6298            let r = pt.point.x().hypot(pt.point.y());
6299            assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
6300        }
6301    }
6302
6303    #[test]
6304    fn plane_sphere_no_intersection() {
6305        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
6306
6307        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
6308        assert!(curves.is_empty());
6309    }
6310
6311    #[test]
6312    fn plane_cone_cross_section() {
6313        let cone = ConicalSurface::new(
6314            Point3::new(0.0, 0.0, 0.0),
6315            Vec3::new(0.0, 0.0, 1.0),
6316            std::f64::consts::FRAC_PI_4,
6317        )
6318        .unwrap();
6319
6320        let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
6321        assert!(!curves.is_empty(), "should find intersection with cone");
6322    }
6323
6324    /// The 1u gridfinity spacer lip fuse corner (#1570): the body's lip
6325    /// recess cone (45 deg, opening downward) meets the tool's lip cone
6326    /// (45 deg, opening upward) with axes offset 0.25mm in x and y. Equal
6327    /// half-angle tangents put the whole intersection on the radical plane,
6328    /// so the section is one exact ellipse; the marcher shredded this into
6329    /// ~64 closed micro-loops per pair.
6330    #[test]
6331    fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
6332        let c1 = ConicalSurface::new(
6333            Point3::new(
6334                -16.999_999_999_999_975,
6335                -16.999_999_999_999_975,
6336                5.849_999_999_999_951,
6337            ),
6338            Vec3::new(0.0, 0.0, -1.0),
6339            0.785_398_163_397_433_5,
6340        )
6341        .unwrap();
6342        let c2 = ConicalSurface::new(
6343            Point3::new(
6344                -16.750_000_000_000_036,
6345                -16.750_000_000_000_018,
6346                0.749_999_999_999_881,
6347            ),
6348            Vec3::new(0.0, 0.0, 1.0),
6349            0.785_398_163_397_467_6,
6350        )
6351        .unwrap();
6352
6353        let curves = exact_cone_cone(&c1, &c2)
6354            .unwrap()
6355            .expect("offset parallel equal-angle cones must take the radical-plane path");
6356        assert_eq!(curves.len(), 1, "expected exactly one section conic");
6357        assert!(
6358            matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
6359            "expected an ellipse section, got {:?}",
6360            curves[0]
6361        );
6362        let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
6363            return;
6364        };
6365
6366        // Every sample must lie on BOTH cones: distance to the axis equals
6367        // tan(half_angle) times the axial distance from the apex, on the
6368        // real nappe of each.
6369        for i in 0..16 {
6370            let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
6371            for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
6372                let rel = p - cone.apex();
6373                let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
6374                let axial = rel_v.dot(cone.axis());
6375                let radial = (rel_v - cone.axis() * axial).length();
6376                assert!(
6377                    axial > 0.0,
6378                    "{label}: sample on phantom nappe (axial {axial})"
6379                );
6380                let expect = cone.half_angle().tan() * axial;
6381                assert!(
6382                    (radial - expect).abs() < 1e-9,
6383                    "{label}: sample off surface by {}",
6384                    (radial - expect).abs()
6385                );
6386            }
6387        }
6388    }
6389
6390    /// Opposed cones whose real nappes occupy disjoint half-spaces share a
6391    /// radical-plane conic only on the phantom nappe — the exact path must
6392    /// report a definitive empty intersection, not defer to the marcher.
6393    #[test]
6394    fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
6395        let c1 = ConicalSurface::new(
6396            Point3::new(0.0, 0.0, 5.0),
6397            Vec3::new(0.0, 0.0, -1.0),
6398            std::f64::consts::FRAC_PI_4,
6399        )
6400        .unwrap();
6401        let c2 = ConicalSurface::new(
6402            Point3::new(0.25, 0.25, 20.0),
6403            Vec3::new(0.0, 0.0, 1.0),
6404            std::f64::consts::FRAC_PI_4,
6405        )
6406        .unwrap();
6407        let curves = exact_cone_cone(&c1, &c2)
6408            .unwrap()
6409            .expect("radical-plane path");
6410        assert!(curves.is_empty(), "disjoint nappes must yield no curves");
6411    }
6412
6413    /// Unequal half-angles keep a quadratic term in the pencil — no plane
6414    /// reduction exists, so the exact path must defer to the marcher.
6415    #[test]
6416    fn offset_parallel_cones_with_unequal_angles_defer() {
6417        let c1 = ConicalSurface::new(
6418            Point3::new(0.0, 0.0, 5.0),
6419            Vec3::new(0.0, 0.0, -1.0),
6420            std::f64::consts::FRAC_PI_4,
6421        )
6422        .unwrap();
6423        let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
6424            .unwrap();
6425        assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
6426    }
6427
6428    /// A 45 degree cone and a radius 0.1 tube tilted 40 degrees that pierces
6429    /// both nappes, so the ruling path declines and the general marcher runs:
6430    /// the tube's axis meets the near nappe at (0.1, -1.368, 1.370).
6431    fn cone_and_tilted_tube() -> (ConicalSurface, CylindricalSurface) {
6432        let cone = ConicalSurface::new(
6433            Point3::new(0.0, 0.0, 0.0),
6434            Vec3::new(0.0, 0.0, 1.0),
6435            std::f64::consts::FRAC_PI_4,
6436        )
6437        .unwrap();
6438        let (s, c) = 40.0_f64.to_radians().sin_cos();
6439        let tube =
6440            CylindricalSurface::new(Point3::new(0.1, 0.0, 3.0), Vec3::new(0.0, s, c), 0.1).unwrap();
6441        (cone, tube)
6442    }
6443
6444    #[test]
6445    fn marcher_keeps_to_its_region() {
6446        let (cone, tube) = cone_and_tilted_tube();
6447        let run = |region: Option<Aabb3>| {
6448            let (a, b) = (
6449                AnalyticSurface::Cone(&cone),
6450                AnalyticSurface::Cylinder(&tube),
6451            );
6452            let (va, vb) = (Some((0.5, 4.0)), Some((-5.0, 5.0)));
6453            match region {
6454                Some(r) => intersect_analytic_analytic_in_region(a, b, 32, va, vb, r),
6455                None => intersect_analytic_analytic_bounded(a, b, 32, va, vb),
6456            }
6457            .unwrap()
6458        };
6459        assert!(!run(None).is_empty());
6460        let near = Aabb3 {
6461            min: Point3::new(-0.5, -2.0, 0.8),
6462            max: Point3::new(0.7, -0.7, 2.0),
6463        };
6464        let curves = run(Some(near));
6465        assert!(!curves.is_empty(), "the loop through the region is kept");
6466        // The region's margin (two grid cells) and one marching step past it.
6467        let reach = near.expanded(0.6);
6468        for curve in &curves {
6469            assert!(curve.points.iter().all(|p| reach.contains_point(p.point)));
6470        }
6471        let away = Aabb3 {
6472            min: Point3::new(5.0, 5.0, 5.0),
6473            max: Point3::new(6.0, 6.0, 6.0),
6474        };
6475        assert!(run(Some(away)).is_empty(), "nothing is marched outside it");
6476    }
6477
6478    #[test]
6479    fn coaxial_cones_cross_at_single_circle() {
6480        // Two coaxial truncated cones (outer base r10->top r8, inner r9->r8
6481        // over height 10) cross where their radii match: z=10, r=8. The
6482        // intersection must be ONE clean circle, not the dozens of degenerate
6483        // micro-curves the general marcher produces at near-tangency.
6484        let outer = ConicalSurface::new(
6485            Point3::new(0.0, 0.0, 50.0),
6486            Vec3::new(0.0, 0.0, -1.0),
6487            5.0_f64.atan(),
6488        )
6489        .unwrap();
6490        let inner = ConicalSurface::new(
6491            Point3::new(0.0, 0.0, 90.0),
6492            Vec3::new(0.0, 0.0, -1.0),
6493            10.0_f64.atan(),
6494        )
6495        .unwrap();
6496
6497        let curves = intersect_analytic_analytic_bounded(
6498            AnalyticSurface::Cone(&outer),
6499            AnalyticSurface::Cone(&inner),
6500            32,
6501            None,
6502            None,
6503        )
6504        .unwrap();
6505
6506        assert_eq!(
6507            curves.len(),
6508            1,
6509            "coaxial cones crossing at one circle must yield exactly one curve, got {}",
6510            curves.len()
6511        );
6512        for p in &curves[0].points {
6513            let r = p.point.x().hypot(p.point.y());
6514            assert!(
6515                (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
6516                "intersection point off the expected z=10,r=8 circle: {:?}",
6517                p.point
6518            );
6519        }
6520    }
6521
6522    #[test]
6523    fn plane_torus_cross_section() {
6524        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
6525
6526        let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
6527        assert!(
6528            !curves.is_empty(),
6529            "should find intersection curves with torus"
6530        );
6531    }
6532
6533    /// A plane resting on a torus's tube touches it along one circle of the
6534    /// torus's own radius, ring or spindle, at the tube's top or bottom.
6535    #[test]
6536    fn plane_tangent_to_a_tube_touches_it_along_one_circle() {
6537        for (major, minor) in [(5.0, 1.0), (0.1, 2.45)] {
6538            let torus = ToroidalSurface::new(Point3::new(1.0, 2.0, 3.0), major, minor).unwrap();
6539            for z in [3.0 - minor, 3.0 + minor] {
6540                let exact = exact_plane_analytic(
6541                    AnalyticSurface::Torus(&torus),
6542                    Vec3::new(0.0, 0.0, 1.0),
6543                    z,
6544                )
6545                .unwrap();
6546                assert_eq!(exact.len(), 1, "R={major} r={minor} z={z}");
6547                let circle = match &exact[0] {
6548                    ExactIntersectionCurve::Circle(c) => Some(c),
6549                    _ => None,
6550                };
6551                let c = circle.expect("a circle");
6552                assert!((c.radius() - major).abs() < 1e-12);
6553                assert!((c.center() - Point3::new(1.0, 2.0, z)).length() < 1e-12);
6554
6555                let sampled = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), z).unwrap();
6556                assert_eq!(sampled.len(), 1, "R={major} r={minor} z={z}");
6557            }
6558            // A tilted plane cuts no single circle of radius R.
6559            let single = |normal: Vec3, d: f64| {
6560                matches!(
6561                    exact_plane_analytic(AnalyticSurface::Torus(&torus), normal, d)
6562                        .unwrap()
6563                        .as_slice(),
6564                    [ExactIntersectionCurve::Circle(_)]
6565                )
6566            };
6567            assert!(!single(Vec3::new(1e-6, 0.0, 1.0), 3.0 + minor));
6568        }
6569    }
6570
6571    /// Tangency is read from the plane's distance to the tube's top, so it
6572    /// survives rounding on a large torus, and a plane further inside than
6573    /// the linear tolerance still cuts its two circles.
6574    #[test]
6575    fn plane_tangent_to_a_large_tube_is_read_through_rounding() {
6576        let torus = ToroidalSurface::new(Point3::new(0.3, -0.7, 3.0), 200.0, 100.1).unwrap();
6577        let level = Vec3::new(0.0, 0.0, 1.0);
6578        let curves =
6579            |d: f64| exact_plane_analytic(AnalyticSurface::Torus(&torus), level, d).unwrap();
6580        assert!(matches!(
6581            curves(3.0 + 100.1).as_slice(),
6582            [ExactIntersectionCurve::Circle(_)]
6583        ));
6584        let inside = curves(3.0 + 100.1 - 4e-7);
6585        assert!(!matches!(
6586            inside.as_slice(),
6587            [ExactIntersectionCurve::Circle(_)]
6588        ));
6589    }
6590
6591    /// Signed distance of a point to a z-axis torus centred at the origin:
6592    /// `sqrt((sqrt(x^2+y^2) - R)^2 + z^2) - r`.
6593    fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
6594        let rho = p.x().hypot(p.y());
6595        ((rho - major).hypot(p.z())) - minor
6596    }
6597
6598    /// The gridfinity lightweight base's failing corner, reduced: a cavity
6599    /// corner-round cone (apex below the floor, 45 deg, axis +z) crossed by a
6600    /// parallel-axis boss cylinder. The general marcher returned ~49 overlapping
6601    /// partial traces of one curve here; the algebraic path must return exactly
6602    /// the two branches, each ON both surfaces and inside the cone's v-hint.
6603    #[test]
6604    fn oblique_cone_cylinder_traces_curves_on_both() {
6605        use crate::traits::ParametricCurve;
6606        // A pointed cone opening down from (0, 0, 3), radius half the depth,
6607        // and a rod along y through (x0, ., 1): one loop through the wall
6608        // when the rod pokes out, two when every ruling meets the cone.
6609        let cone = ConicalSurface::new(
6610            Point3::new(0.0, 0.0, 3.0),
6611            Vec3::new(0.0, 0.0, -1.0),
6612            2.0_f64.atan(),
6613        )
6614        .unwrap();
6615        for (x0, loops) in [(0.5, 1), (0.0, 2)] {
6616            let cyl =
6617                CylindricalSurface::new(Point3::new(x0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6618                    .unwrap();
6619            for cone_first in [true, false] {
6620                let (a, b) = if cone_first {
6621                    (
6622                        AnalyticSurface::Cone(&cone),
6623                        AnalyticSurface::Cylinder(&cyl),
6624                    )
6625                } else {
6626                    (
6627                        AnalyticSurface::Cylinder(&cyl),
6628                        AnalyticSurface::Cone(&cone),
6629                    )
6630                };
6631                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6632                assert_eq!(curves.len(), loops, "x0 {x0}: loops");
6633                for c in &curves {
6634                    let (t0, t1) = c.curve.domain();
6635                    for k in 0..=64 {
6636                        let t = (t1 - t0).madd(f64::from(k) / 64.0, t0);
6637                        let p = ParametricCurve::evaluate(&c.curve, t);
6638                        // A cubic through the ruling samples, bent most at the
6639                        // loop's branch points.
6640                        let rod = (p.x() - x0).hypot(p.z() - 1.0);
6641                        assert!(
6642                            (rod - 0.6).abs() < 1e-4,
6643                            "x0 {x0}: off the rod by {}",
6644                            rod - 0.6
6645                        );
6646                        let cone_r = p.x().hypot(p.y());
6647                        assert!(
6648                            (cone_r - 0.5 * (3.0 - p.z())).abs() < 1e-4,
6649                            "x0 {x0}: off the cone at {p:?}"
6650                        );
6651                    }
6652                }
6653            }
6654        }
6655    }
6656
6657    #[test]
6658    fn a_rod_through_a_rings_tube_traces_four_loops() {
6659        use crate::traits::ParametricCurve;
6660        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6661        // Along y through (0.5, ., 0.3): every ruling enters and leaves the
6662        // tube on either side of the hole, four roots, four loops.
6663        let rod =
6664            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.3), Vec3::new(0.0, 1.0, 0.0), 0.6)
6665                .unwrap();
6666        let curves = ruling_torus_cylinder(&ring, &rod, true).unwrap();
6667        assert_eq!(curves.len(), 4);
6668        for c in &curves {
6669            let (t0, t1) = c.curve.domain();
6670            for k in 0..=64 {
6671                let p =
6672                    ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 64.0, t0));
6673                let on_rod = (p.x() - 0.5).hypot(p.z() - 0.3) - 0.6;
6674                let on_ring = (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
6675                assert!(
6676                    on_rod.abs() < 1e-4 && on_ring.abs() < 1e-4,
6677                    "off by {on_rod}, {on_ring}"
6678                );
6679            }
6680        }
6681        // Higher, the rod's top rulings pass over the tube: the count varies.
6682        let high =
6683            CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6684                .unwrap();
6685        assert!(ruling_torus_cylinder(&ring, &high, true).is_none());
6686        // Its top clears the tube only between two sampled rulings.
6687        let grazing =
6688            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.9001), Vec3::new(0.0, 1.0, 0.0), 0.6)
6689                .unwrap();
6690        assert!(ruling_torus_cylinder(&ring, &grazing, true).is_none());
6691        // A spindle torus's quartic also holds its inner lemon.
6692        let spindle = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap();
6693        let thin =
6694            CylindricalSurface::new(Point3::new(0.3, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 0.2)
6695                .unwrap();
6696        assert!(ruling_torus_cylinder(&spindle, &thin, true).is_none());
6697    }
6698
6699    #[test]
6700    fn a_pin_through_a_ball_traces_two_loops() {
6701        use crate::traits::ParametricCurve;
6702        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
6703        // A pin tapering from radius 1.2 at (1, 0.5, -5) to 0.4 at 10 up:
6704        // radial 0.08 per unit of height.
6705        let half = 0.08_f64.atan();
6706        let apex = Point3::new(1.0, 0.5, -5.0 + 1.2 / 0.08);
6707        let pin = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, -1.0), FRAC_PI_2 - half).unwrap();
6708        for cone_first in [true, false] {
6709            let (a, b) = if cone_first {
6710                (AnalyticSurface::Cone(&pin), AnalyticSurface::Sphere(&ball))
6711            } else {
6712                (AnalyticSurface::Sphere(&ball), AnalyticSurface::Cone(&pin))
6713            };
6714            let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6715            assert_eq!(curves.len(), 2, "entry and exit loops");
6716            for c in &curves {
6717                let (t0, t1) = c.curve.domain();
6718                for k in 0..=64 {
6719                    let p = ParametricCurve::evaluate(
6720                        &c.curve,
6721                        (t1 - t0).madd(f64::from(k) / 64.0, t0),
6722                    );
6723                    let on_ball = (p - Point3::new(0.0, 0.0, 0.0)).length() - 3.0;
6724                    let axial = apex.z() - p.z();
6725                    let on_pin = (p.x() - 1.0).hypot(p.y() - 0.5) - axial * half.tan();
6726                    assert!(
6727                        on_ball.abs() < 1e-4 && on_pin.abs() < 1e-4,
6728                        "off by {on_ball}, {on_pin}"
6729                    );
6730                }
6731            }
6732        }
6733        // On the ball's axis the loops are circles, which defer. A pin whose
6734        // apex is inside the ball leaves it once along every generator, and
6735        // one only partly through the ball meets it over the generators that
6736        // reach it: one loop each. One that opens away meets it not at all.
6737        let coaxial =
6738            ConicalSurface::new(Point3::new(0.0, 0.0, 10.0), Vec3::new(0.0, 0.0, -1.0), 1.4)
6739                .unwrap();
6740        assert!(ruling_cone_sphere(&coaxial, &ball, true).is_none());
6741        let aside = ConicalSurface::new(
6742            Point3::new(2.8, 0.0, 10.0),
6743            Vec3::new(0.0, 0.0, -1.0),
6744            FRAC_PI_2 - half,
6745        )
6746        .unwrap();
6747        assert_eq!(ruling_cone_sphere(&aside, &ball, true).unwrap().len(), 1);
6748        let holding = ConicalSurface::new(
6749            Point3::new(1.0, 0.5, 1.0),
6750            Vec3::new(0.0, 0.0, -1.0),
6751            FRAC_PI_2 - half,
6752        )
6753        .unwrap();
6754        assert_eq!(ruling_cone_sphere(&holding, &ball, true).unwrap().len(), 1);
6755        let away = ConicalSurface::new(
6756            Point3::new(1.0, 0.5, 10.0),
6757            Vec3::new(0.0, 0.0, 1.0),
6758            FRAC_PI_2 - half,
6759        )
6760        .unwrap();
6761        assert!(ruling_cone_sphere(&away, &ball, true).unwrap().is_empty());
6762        // Grazing: the generators that miss span about 0.002 radians,
6763        // narrower than a 2048-angle scan's step, and the near and far
6764        // roots join into one loop across them.
6765        let step = TAU / 2048.0;
6766        let grazed =
6767            SphericalSurface::new(Point3::new(step.cos(), step.sin(), 10.0), 9.255_250_971_8)
6768                .unwrap();
6769        let wide =
6770            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5).unwrap();
6771        assert_eq!(ruling_cone_sphere(&wide, &grazed, true).unwrap().len(), 1);
6772    }
6773
6774    #[test]
6775    fn a_ball_beside_a_cone_meets_it_in_one_loop() {
6776        use crate::traits::ParametricCurve;
6777        // Apex 3 up, opening downward, the radius half the depth below it.
6778        let cone = ConicalSurface::new(
6779            Point3::new(0.0, 0.0, 3.0),
6780            Vec3::new(0.0, 0.0, -1.0),
6781            2.0_f64.atan(),
6782        )
6783        .unwrap();
6784        for (centre, radius) in [
6785            (Point3::new(1.0, 0.8, 1.2), 1.1),
6786            (Point3::new(1.5, 0.0, 0.0), 0.8),
6787        ] {
6788            let ball = SphericalSurface::new(centre, radius).unwrap();
6789            let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
6790            assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
6791            let (t0, t1) = curves[0].curve.domain();
6792            for k in 0..=64 {
6793                let p = ParametricCurve::evaluate(
6794                    &curves[0].curve,
6795                    (t1 - t0).madd(f64::from(k) / 64.0, t0),
6796                );
6797                let on_ball = (p - centre).length() - radius;
6798                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6799                assert!(
6800                    on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5,
6801                    "ball at {centre:?}: off by {on_ball}, {on_cone}"
6802                );
6803            }
6804        }
6805        // A ball the nappe's generators miss, and one on the apex.
6806        let clear = SphericalSurface::new(Point3::new(4.0, 0.0, 0.0), 0.5).unwrap();
6807        assert!(ruling_cone_sphere(&cone, &clear, true).unwrap().is_empty());
6808        let on_apex = SphericalSurface::new(Point3::new(0.6, 0.0, 3.8), 1.0).unwrap();
6809        assert!(ruling_cone_sphere(&cone, &on_apex, true).is_none());
6810    }
6811
6812    #[test]
6813    fn a_ball_holding_a_cones_apex_meets_it_in_one_loop() {
6814        use crate::traits::ParametricCurve;
6815        let cone = ConicalSurface::new(
6816            Point3::new(0.0, 0.0, 3.0),
6817            Vec3::new(0.0, 0.0, -1.0),
6818            2.0_f64.atan(),
6819        )
6820        .unwrap();
6821        // Off the axis, and barely holding the apex: the generators pointing
6822        // away from the centre leave it just past the apex.
6823        for (centre, radius) in [
6824            (Point3::new(0.5, 0.0, 2.5), 2.0),
6825            (Point3::new(-0.4, 0.3, 2.0), 1.5),
6826            (Point3::new(0.0, 0.8, 3.0), 0.8001),
6827            (Point3::new(0.0, 0.8, 3.0), 0.800_001),
6828        ] {
6829            let ball = SphericalSurface::new(centre, radius).unwrap();
6830            let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
6831            assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
6832            let (t0, t1) = curves[0].curve.domain();
6833            for k in 0..=4096 {
6834                let p = ParametricCurve::evaluate(
6835                    &curves[0].curve,
6836                    (t1 - t0).madd(f64::from(k) / 4096.0, t0),
6837                );
6838                let on_ball = (p - centre).length() - radius;
6839                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6840                assert!(
6841                    on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5 && p.z() < 3.0,
6842                    "ball at {centre:?}: off by {on_ball}, {on_cone} at {p:?}"
6843                );
6844            }
6845        }
6846    }
6847
6848    /// A pin whose tip just pierces a rod's wall meets the rulings within
6849    /// 2.2e-4 of the wall's top, between two of the 128 samples. The
6850    /// sample nearest them misses the pin, its discriminant -5.9e-8 within
6851    /// the tolerance alone: a loop traced from it would lie 3e-5 off the
6852    /// pin. The window lies between two scan points too, and the rulings
6853    /// leave the pin to the marcher.
6854    #[test]
6855    fn a_pin_tip_between_two_samples_is_not_traced_from_a_miss() {
6856        use std::f64::consts::{FRAC_PI_2, PI};
6857        let slope = 0.04375_f64;
6858        let pin = ConicalSurface::new(
6859            Point3::new(0.0, 5.005, 10.0),
6860            Vec3::new(0.0, -1.0, 0.0),
6861            (1.0 / slope).atan(),
6862        )
6863        .unwrap();
6864        let turn = FRAC_PI_2 + 5e-5 - PI / 128.0;
6865        let rod = CylindricalSurface::with_ref_dir(
6866            Point3::new(0.0, 0.0, 0.0),
6867            Vec3::new(0.0, 0.0, 1.0),
6868            5.0,
6869            Vec3::new(turn.cos(), turn.sin(), 0.0),
6870        )
6871        .unwrap();
6872        assert!(ruling_cone_cylinder(&pin, &rod, true).is_none());
6873    }
6874
6875    /// A taper pin through a rod, the rod turned about its axis: the pin's
6876    /// narrow end meets fewer than 8 of the rod's 128 sampled rulings in
6877    /// some turns, and the rulings still trace both of its loops there.
6878    #[test]
6879    fn a_taper_pin_through_a_turned_rod_traces_both_loops() {
6880        use crate::traits::ParametricCurve;
6881        let slope = 0.7_f64 / 16.0;
6882        let half = (1.0 / slope).atan();
6883        for flip in [false, true] {
6884            let (apex_y, axis_y) = if flip {
6885                (-8.0 - 0.8 / slope, 1.0)
6886            } else {
6887                (-8.0 + 1.5 / slope, -1.0)
6888            };
6889            let pin = ConicalSurface::new(
6890                Point3::new(0.0, apex_y, 10.0),
6891                Vec3::new(0.0, axis_y, 0.0),
6892                half,
6893            )
6894            .unwrap();
6895            for spin in [0.0_f64, 0.3, 0.9, 1.4, 2.0, 2.6, 3.0, 3.6] {
6896                let rod = CylindricalSurface::with_ref_dir(
6897                    Point3::new(0.0, 0.0, 0.0),
6898                    Vec3::new(0.0, 0.0, 1.0),
6899                    5.0,
6900                    Vec3::new(spin.cos(), spin.sin(), 0.0),
6901                )
6902                .unwrap();
6903                let curves = ruling_cone_cylinder(&pin, &rod, true);
6904                assert!(curves.is_some(), "spin {spin} flip {flip}: no trace");
6905                let curves = curves.unwrap();
6906                assert_eq!(curves.len(), 2, "spin {spin} flip {flip}: loops");
6907                for c in &curves {
6908                    let (t0, t1) = c.curve.domain();
6909                    for k in 0..=1000 {
6910                        let p = ParametricCurve::evaluate(
6911                            &c.curve,
6912                            (t1 - t0).madd(f64::from(k) / 1000.0, t0),
6913                        );
6914                        let on_rod = p.x().hypot(p.y()) - 5.0;
6915                        let on_pin = p.x().hypot(p.z() - 10.0) - slope * (p.y() - apex_y).abs();
6916                        assert!(
6917                            on_rod.abs() < 1e-7 && on_pin.abs() < 1e-7,
6918                            "spin {spin} flip {flip}: off by {on_rod:.2e}, {on_pin:.2e}"
6919                        );
6920                    }
6921                }
6922            }
6923        }
6924    }
6925
6926    #[test]
6927    fn oblique_cone_cylinder_defers_where_rulings_cannot_trace_it() {
6928        let t = 2.0_f64.atan();
6929        let cone =
6930            ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 0.0, -1.0), t).unwrap();
6931        // A rod through the apex meets the far nappe.
6932        let through_apex =
6933            CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
6934                .unwrap();
6935        assert!(ruling_cone_cylinder(&cone, &through_apex, true).is_none());
6936        // A rod along a generator meets each ruling once.
6937        let generator = Vec3::new(t.cos(), 0.0, -t.sin());
6938        let along = CylindricalSurface::new(Point3::new(0.0, 0.3, 0.0), generator, 0.2).unwrap();
6939        assert!(ruling_cone_cylinder(&cone, &along, true).is_none());
6940        // A pin's tip just through a tube's wall: the tube's rulings that
6941        // meet it span a window narrower than the sampling.
6942        let pin =
6943            ConicalSurface::new(Point3::new(20.5, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), t).unwrap();
6944        let tube =
6945            CylindricalSurface::new(Point3::new(0.0, 0.0, -10.0), Vec3::new(0.0, 0.0, 1.0), 20.0)
6946                .unwrap();
6947        assert!(ruling_cone_cylinder(&pin, &tube, true).is_none());
6948    }
6949
6950    #[test]
6951    fn parallel_cone_cylinder_gives_two_exact_branches() {
6952        use crate::traits::ParametricCurve;
6953        let cone = ConicalSurface::new(
6954            Point3::new(-5.45, -36.55, -4.85),
6955            Vec3::new(0.0, 0.0, 1.0),
6956            std::f64::consts::FRAC_PI_4,
6957        )
6958        .unwrap();
6959        let cyl = CylindricalSurface::new(
6960            Point3::new(-8.0, -34.0, -5.0),
6961            Vec3::new(0.0, 0.0, 1.0),
6962            4.45,
6963        )
6964        .unwrap();
6965        // The cone face spans z in [-3.8, -3.0]; v = (z - apex_z) / sin(45 deg).
6966        let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
6967        let curves = intersect_analytic_analytic_bounded(
6968            AnalyticSurface::Cone(&cone),
6969            AnalyticSurface::Cylinder(&cyl),
6970            32,
6971            Some(v_hint),
6972            Some((0.0, 2.5)),
6973        )
6974        .unwrap();
6975
6976        assert_eq!(curves.len(), 2, "expected exactly the two branches");
6977        for c in &curves {
6978            let (t0, t1) = c.curve.domain();
6979            for k in 0..=32 {
6980                let t = (t1 - t0).madd(f64::from(k) / 32.0, t0);
6981                let p = ParametricCurve::evaluate(&c.curve, t);
6982                // On the cylinder: radial distance from its axis is the radius.
6983                let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
6984                assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
6985                // On the cone: radial distance from its axis is z - apex_z.
6986                let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
6987                assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
6988                // Inside the cone face's own v-window (the hint is respected).
6989                assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
6990            }
6991        }
6992    }
6993
6994    #[test]
6995    fn parallel_rod_through_a_cones_wall_closes_one_loop() {
6996        use crate::traits::ParametricCurve;
6997        // Apex 3 up, opening downward, the radius half the depth below it.
6998        let cone = ConicalSurface::new(
6999            Point3::new(0.0, 0.0, 3.0),
7000            Vec3::new(0.0, 0.0, -1.0),
7001            2.0_f64.atan(),
7002        )
7003        .unwrap();
7004        // Beside the axis: each ruling meets the nappe once.
7005        for (x, y) in [(0.0, 1.3), (1.2, 0.5)] {
7006            let rod =
7007                CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
7008                    .unwrap();
7009            let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7010                .unwrap()
7011                .unwrap();
7012            assert_eq!(curves.len(), 1, "one closed loop at ({x}, {y})");
7013            let (t0, t1) = curves[0].curve.domain();
7014            let (first, last) = (
7015                ParametricCurve::evaluate(&curves[0].curve, t0),
7016                ParametricCurve::evaluate(&curves[0].curve, t1),
7017            );
7018            assert!((first - last).length() < 1e-9, "open at ({x}, {y})");
7019            for k in 0..=64 {
7020                let p = ParametricCurve::evaluate(
7021                    &curves[0].curve,
7022                    (t1 - t0).madd(f64::from(k) / 64.0, t0),
7023                );
7024                let on_rod = (p.x() - x).hypot(p.y() - y) - 0.6;
7025                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
7026                assert!(
7027                    on_rod.abs() < 1e-5 && on_cone.abs() < 1e-5,
7028                    "({x}, {y}): off by {on_rod}, {on_cone}"
7029                );
7030            }
7031        }
7032        // Around the axis, and beside it by less than the bend the rulings
7033        // resolve: two branches.
7034        for (x, y) in [(0.3, 0.2), (0.65, 0.0)] {
7035            let rod =
7036                CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
7037                    .unwrap();
7038            let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7039                .unwrap()
7040                .unwrap();
7041            assert_eq!(curves.len(), 2, "two branches at ({x}, {y})");
7042        }
7043    }
7044
7045    /// A frustum (radius 72 to 50 over 84) and a smaller one standing beside
7046    /// its axis on the same base (radius 10 to 5 over 44, axis 70 away): the
7047    /// smaller one notches the base rim, and the section is an arch from the
7048    /// rim up to where the two circles at one height touch, in two branches
7049    /// that meet there. Each lies on both cones, between its samples too.
7050    #[test]
7051    fn parallel_cones_give_two_exact_branches() {
7052        use crate::traits::ParametricCurve;
7053        let frustum = |x: f64, r_big: f64, r_small: f64, h: f64| {
7054            let apex = h + r_small * h / (r_big - r_small);
7055            let cone = ConicalSurface::new(
7056                Point3::new(x, 0.0, apex),
7057                Vec3::new(0.0, 0.0, -1.0),
7058                apex.atan2(r_big),
7059            )
7060            .unwrap();
7061            // `v` at height `z`, from the apex down the wall.
7062            let v = move |z: f64| (apex - z) / apex.atan2(r_big).sin();
7063            (cone, v(h), v(0.0))
7064        };
7065        let (big, big_top, big_base) = frustum(0.0, 72.0, 50.0, 84.0);
7066        for (x, flip) in [(-70.0_f64, false), (70.0, true)] {
7067            let (small, small_top, small_base) = frustum(x, 10.0, 5.0, 44.0);
7068            let (first, second) = if flip {
7069                (AnalyticSurface::Cone(&small), AnalyticSurface::Cone(&big))
7070            } else {
7071                (AnalyticSurface::Cone(&big), AnalyticSurface::Cone(&small))
7072            };
7073            let (hint_first, hint_second) = if flip {
7074                ((small_top, small_base), (big_top, big_base))
7075            } else {
7076                ((big_top, big_base), (small_top, small_base))
7077            };
7078            let curves = intersect_analytic_analytic_bounded(
7079                first,
7080                second,
7081                32,
7082                Some(hint_first),
7083                Some(hint_second),
7084            )
7085            .unwrap();
7086            assert_eq!(curves.len(), 2, "x = {x}: the two branches");
7087            // The circles touch where 72 - 22 z / 84 + 10 - 5 z / 44 = 70.
7088            let touch = 12.0 / (22.0 / 84.0 + 5.0 / 44.0);
7089            let mut tops = Vec::new();
7090            for c in &curves {
7091                let (t0, t1) = c.curve.domain();
7092                let ends = [
7093                    ParametricCurve::evaluate(&c.curve, t0),
7094                    ParametricCurve::evaluate(&c.curve, t1),
7095                ];
7096                let (low, high) = if ends[0].z() < ends[1].z() {
7097                    (ends[0], ends[1])
7098                } else {
7099                    (ends[1], ends[0])
7100                };
7101                assert!(low.z().abs() < 1e-9, "x = {x}: starts at z = {}", low.z());
7102                assert!((high.z() - touch).abs() < 1e-9, "x = {x}: tops at {high:?}");
7103                tops.push(high);
7104                for k in 0..=256 {
7105                    let p = ParametricCurve::evaluate(
7106                        &c.curve,
7107                        (t1 - t0).madd(f64::from(k) / 256.0, t0),
7108                    );
7109                    let on_big = p.x().hypot(p.y()) - (72.0 - 22.0 * p.z() / 84.0);
7110                    let on_small = (p.x() - x).hypot(p.y()) - (10.0 - 5.0 * p.z() / 44.0);
7111                    assert!(
7112                        on_big.abs() < 1e-6 && on_small.abs() < 1e-6,
7113                        "x = {x}: {p:?} off by {on_big}, {on_small}"
7114                    );
7115                }
7116            }
7117            assert!((tops[0] - tops[1]).length() < 1e-9, "x = {x}: {tops:?}");
7118        }
7119    }
7120
7121    /// Apices 1 apart, radii `z` and `1.001 z` at the height `z`: the circles
7122    /// meet from `z = 1 / 2.001` up to `z = 1000`, and the two branches, fitted
7123    /// over that long span, lie on both cones between their points and meet
7124    /// at both ends.
7125    #[test]
7126    fn parallel_cones_of_nearly_equal_slope_trace_on_both() {
7127        use crate::traits::ParametricCurve;
7128        let up = Vec3::new(0.0, 0.0, 1.0);
7129        let first =
7130            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7131                .unwrap();
7132        let second =
7133            ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, (1.0 / 1.001_f64).atan()).unwrap();
7134        let curves = algebraic_parallel_cone_cone(&first, &second, None, None).unwrap();
7135        assert_eq!(curves.len(), 2, "the two branches");
7136        let mut ends = Vec::new();
7137        for c in &curves {
7138            let (t0, t1) = c.curve.domain();
7139            ends.push(ParametricCurve::evaluate(&c.curve, t0));
7140            ends.push(ParametricCurve::evaluate(&c.curve, t1));
7141            for k in 0..=4096 {
7142                let p =
7143                    ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 4096.0, t0));
7144                let on_first = p.x().hypot(p.y()) - p.z();
7145                let on_second = (p.x() - 1.0).hypot(p.y()) - 1.001 * p.z();
7146                assert!(
7147                    on_first.abs() < 1e-7 && on_second.abs() < 1e-7,
7148                    "{p:?} off by {on_first}, {on_second}"
7149                );
7150            }
7151        }
7152        let (low, high) = (1.0 / 2.001, 1000.0);
7153        for (k, z) in [(0, low), (1, high)] {
7154            let (a, b) = (ends[k], ends[2 + k]);
7155            assert!(
7156                (a.z() - z).abs() < 1e-6 * z,
7157                "branch end at {a:?}, not z = {z}"
7158            );
7159            assert!((a - b).length() < 1e-9, "branches part at {a:?} and {b:?}");
7160        }
7161    }
7162
7163    /// Two cones of one axis direction whose slopes differ by about `5e-13`:
7164    /// the narrower circle starts inside the wider one, a unit clear of its
7165    /// rim, and reaches it only near `v = 2e12`. Within a span out to `4e12`
7166    /// the cones meet, so the path does not call them apart.
7167    #[test]
7168    fn nearly_equal_slopes_meet_far_out() {
7169        let up = Vec3::new(0.0, 0.0, 1.0);
7170        let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7171            .unwrap();
7172        let (sin1, cos1) = std::f64::consts::FRAC_PI_4.sin_cos();
7173        // `rho2 - rho1 = (b - cos1) v + a`, with `b - cos1 = 5e-13` and
7174        // `a = -(d + 1)` for axes `d = 1` apart.
7175        let slope = (cos1 + 5e-13) / sin1;
7176        let along = 2.0 / slope;
7177        let narrow =
7178            ConicalSurface::new(Point3::new(1.0, 0.0, along), up, (1.0 / slope).atan()).unwrap();
7179        let curves = algebraic_parallel_cone_cone(&wide, &narrow, Some((0.0, 4e12)), None);
7180        assert!(
7181            !curves.as_ref().is_some_and(Vec::is_empty),
7182            "called apart: {:?}",
7183            curves.map(|c| c.len())
7184        );
7185    }
7186
7187    /// Two cones of one axis direction, a unit apart, bounded on their
7188    /// negative nappes: both hold `(0.125, sqrt(15)/8, -0.5)`, at `v` about
7189    /// -0.707 on the first and -1.118 on the second. The path traces positive
7190    /// nappes only, so it leaves the pair to the marcher and does not call the
7191    /// cones apart.
7192    #[test]
7193    fn parallel_cones_bounded_on_their_negative_nappes_go_to_the_marcher() {
7194        let up = Vec3::new(0.0, 0.0, 1.0);
7195        let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
7196            .unwrap();
7197        let narrow = ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, 0.5_f64.atan()).unwrap();
7198        let shared = Point3::new(0.125, 15.0_f64.sqrt() / 8.0, -0.5);
7199        for cone in [&wide, &narrow] {
7200            assert!(off_cone(cone, shared).0 < 1e-12);
7201        }
7202        let (r1, r2) = (std::f64::consts::SQRT_2, 5.0_f64.sqrt());
7203        let curves = algebraic_parallel_cone_cone(
7204            &wide,
7205            &narrow,
7206            Some((-r1, -r1 / 3.0)),
7207            Some((-r2, -r2 / 3.0)),
7208        );
7209        assert!(curves.is_none(), "{:?} curves", curves.map(|c| c.len()));
7210    }
7211
7212    /// Axes `1e-5` radians apart, which a dot product within `1e-10` of one
7213    /// read as parallel: the parallel cone-cone and cone-cylinder paths both
7214    /// decline them.
7215    #[test]
7216    fn nearly_parallel_axes_take_neither_parallel_path() {
7217        let tilt = 1e-5_f64;
7218        let down = Vec3::new(0.0, 0.0, -1.0);
7219        let tilted = Vec3::new(tilt.sin(), 0.0, -tilt.cos());
7220        let big = ConicalSurface::new(
7221            Point3::new(0.0, 0.0, 274.909_090_909),
7222            down,
7223            274.909_090_909_f64.atan2(72.0),
7224        )
7225        .unwrap();
7226        let small =
7227            ConicalSurface::new(Point3::new(-70.0, 0.0, 88.0), tilted, 88.0_f64.atan2(10.0))
7228                .unwrap();
7229        assert!(algebraic_parallel_cone_cone(&big, &small, None, None).is_none());
7230        let cone = ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), down, 2.0_f64.atan()).unwrap();
7231        let rod = CylindricalSurface::new(Point3::new(1.2, 0.5, -10.0), tilted, 0.6).unwrap();
7232        assert!(
7233            algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
7234                .unwrap()
7235                .is_none()
7236        );
7237    }
7238
7239    /// A coaxial pair has no radical line; the algebraic path must defer rather
7240    /// than divide by a zero axis separation.
7241    #[test]
7242    fn coaxial_cone_cylinder_defers_to_other_paths() {
7243        let cone = ConicalSurface::new(
7244            Point3::new(0.0, 0.0, 0.0),
7245            Vec3::new(0.0, 0.0, 1.0),
7246            std::f64::consts::FRAC_PI_4,
7247        )
7248        .unwrap();
7249        let cyl =
7250            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
7251                .unwrap();
7252        assert!(
7253            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
7254                .unwrap()
7255                .is_none()
7256        );
7257    }
7258
7259    #[test]
7260    fn oblique_cone_cylinder_defers_to_other_paths() {
7261        let cone = ConicalSurface::new(
7262            Point3::new(0.0, 0.0, 0.0),
7263            Vec3::new(0.0, 0.0, 1.0),
7264            std::f64::consts::FRAC_PI_4,
7265        )
7266        .unwrap();
7267        let cyl =
7268            CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7269                .unwrap();
7270        assert!(
7271            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
7272                .unwrap()
7273                .is_none()
7274        );
7275    }
7276
7277    #[test]
7278    fn plane_torus_lobe_closes_and_stays_on_surface() {
7279        use crate::traits::ParametricCurve;
7280        let (major, minor) = (10.0, 3.0);
7281        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7282
7283        // The census cutting planes (y=-4, x=6) each cut the +x and -x tube lobes
7284        // in a CLOSED oval. The greedy marcher stops one grid step short of
7285        // closing; the wrap-close must make every fitted lobe close exactly.
7286        for (n, d) in [
7287            (Vec3::new(0.0, -1.0, 0.0), 4.0),  // y = -4
7288            (Vec3::new(-1.0, 0.0, 0.0), -6.0), // x = 6
7289            (Vec3::new(0.0, 0.0, 1.0), 0.0),   // z = 0 -> two concentric circles
7290        ] {
7291            let curves = intersect_plane_torus(&torus, n, d).unwrap();
7292            assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
7293            for c in &curves {
7294                let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
7295                let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
7296                assert!(
7297                    (p0 - p1).length() < 1e-7,
7298                    "lobe not closed: gap={} (n={n:?} d={d})",
7299                    (p0 - p1).length()
7300                );
7301                // Every fitted sample stays on the torus (shape-preserving).
7302                for k in 0..=64 {
7303                    let t = f64::from(k) / 64.0;
7304                    let p = ParametricCurve::evaluate(&c.curve, t);
7305                    assert!(
7306                        torus_implicit(p, major, minor).abs() < 1e-2,
7307                        "off-surface point {p:?} implicit={}",
7308                        torus_implicit(p, major, minor)
7309                    );
7310                }
7311            }
7312        }
7313    }
7314
7315    /// A wall 0.4 outside the inner equator turns its loops tightly there.
7316    /// Between its points, each fitted loop stays on the torus and on the
7317    /// plane within the fit's bound.
7318    #[test]
7319    fn plane_torus_fits_stay_on_the_section_where_it_turns_tightly() {
7320        use crate::traits::ParametricCurve;
7321        let (major, minor) = (4.0, 1.5);
7322        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7323        for (n, d) in [
7324            (Vec3::new(0.0, 1.0, 0.0), 2.1),
7325            (Vec3::new(1.0, 0.0, 0.0), -1.9),
7326            (Vec3::new(0.0, 0.6, 0.8), 3.5),
7327        ] {
7328            let curves = intersect_plane_torus(&torus, n, d).unwrap();
7329            assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
7330            for c in &curves {
7331                for k in 0..=4000 {
7332                    let p = ParametricCurve::evaluate(&c.curve, f64::from(k) / 4000.0);
7333                    let off = ((p.x().hypot(p.y()) - major).hypot(p.z()) - minor).abs();
7334                    assert!(off <= 1e-8, "{off} off the torus at {p:?} (n={n:?} d={d})");
7335                    let off_plane = (n.dot(Vec3::new(p.x(), p.y(), p.z())) - d).abs();
7336                    assert!(off_plane <= 1e-12, "{off_plane} off the plane at {p:?}");
7337                }
7338            }
7339        }
7340    }
7341
7342    /// The plane `z = 0`'s section of the torus of radii 4 and 1.5 read
7343    /// from two of its points across the axis: the line between them strays
7344    /// 2.5 off the torus at its middle, on the axis, where no point moves onto
7345    /// the section. The fit cannot check that span, and is refused.
7346    #[test]
7347    fn a_plane_torus_fit_it_cannot_check_is_refused() {
7348        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7349        let across = [Point3::new(5.5, 0.0, 0.0), Point3::new(-5.5, 0.0, 0.0)];
7350        assert!(fit_plane_torus_section(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0, &across).is_err());
7351    }
7352
7353    /// The fit's check stops its Newton steps once they have moved a middle
7354    /// by less than a quarter of the bound. A middle it then reads as within
7355    /// the bound is within it, and a middle farther off moves onto the same
7356    /// point of the section as before, so the fit keeps the same points.
7357    #[test]
7358    fn a_short_newton_check_reads_each_middle_as_the_full_one_does() {
7359        let torus = ToroidalSurface::new(Point3::new(1.0, -2.0, 0.5), 4.0, 1.5).unwrap();
7360        let (n, d) = (Vec3::new(0.0, 2.0, 0.0), 2.0 * (2.1 - 2.0));
7361        let tol = PLANE_TORUS_FIT * 5.5;
7362        for ipts in plane_torus_loops(&torus, n, d, 128) {
7363            for (ip, power) in ipts.iter().zip((0..10).cycle()) {
7364                let off = Vec3::new(0.3, -0.7, 0.2) * (1e-13 * 10f64.powi(power));
7365                let p = ip.point + off;
7366                let full = plane_torus_section_point(&torus, n, d, p).unwrap();
7367                let short = plane_torus_newton(&torus, n, d, p, 0.25 * tol).unwrap();
7368                if (short - p).length() < 0.25 * tol {
7369                    assert!((full - p).length() <= tol, "{:.2e}", (full - p).length());
7370                    assert!((full - short).length() < 1e-15);
7371                } else {
7372                    assert_eq!(full, short);
7373                }
7374            }
7375        }
7376    }
7377
7378    /// Points near a plane's section of a torus move onto it, on the plane
7379    /// and the tube to rounding.
7380    #[test]
7381    fn plane_torus_section_points_lie_on_both_surfaces() {
7382        let torus = ToroidalSurface::new(Point3::new(1.0, -2.0, 0.5), 4.0, 1.5).unwrap();
7383        let (n, d) = (Vec3::new(0.0, 2.0, 0.0), 2.0 * (2.1 - 2.0));
7384        for ipts in plane_torus_loops(&torus, n, d, 128) {
7385            for ip in ipts.iter().step_by(5) {
7386                let near = ip.point + Vec3::new(1e-4, -2e-4, 3e-4);
7387                let on = plane_torus_section_point(&torus, n, d, near).unwrap();
7388                let w = on - torus.center();
7389                let off = ((w.x().hypot(w.y()) - 4.0).hypot(w.z()) - 1.5).abs();
7390                assert!(off <= 1e-14, "{off} off the torus");
7391                assert!(
7392                    (on.y() - 0.1).abs() <= 1e-14,
7393                    "{} off the plane",
7394                    on.y() - 0.1
7395                );
7396                assert!((on - near).length() < 1e-3);
7397            }
7398        }
7399    }
7400
7401    /// A plane tangent to the inner equator (x = major - minor = 7) cuts a
7402    /// figure-eight that crosses itself on that equator. It comes out as its
7403    /// two lobes, each a loop that starts and ends on the node, one either
7404    /// side of the plane y = 0, never as one loop sealed across the node.
7405    #[test]
7406    fn plane_torus_inner_tangent_figure_eight_is_two_loops_through_its_node() {
7407        let (major, minor) = (10.0, 3.0);
7408        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7409        let curves =
7410            intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
7411        assert_eq!(curves.len(), 2, "one loop per lobe");
7412        let node = Point3::new(major - minor, 0.0, 0.0);
7413        let mut sides = Vec::new();
7414        for c in &curves {
7415            let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7416            assert!((first - node).length() < 1e-6, "starts at {first:?}");
7417            assert_eq!(first, last, "closes on the node");
7418            for p in c.points.iter().map(|p| p.point) {
7419                assert!((p.x() - node.x()).abs() < 1e-9, "off the plane at {p:?}");
7420                assert!(
7421                    torus_implicit(p, major, minor).abs() < 1e-6,
7422                    "off the torus at {p:?}"
7423                );
7424            }
7425            let y: f64 = c.points.iter().map(|p| p.point.y()).sum();
7426            sides.push(y > 0.0);
7427            assert!(
7428                c.points.iter().all(|p| p.point.y() * y >= -1e-9),
7429                "a lobe crosses y = 0"
7430            );
7431        }
7432        assert_ne!(sides[0], sides[1], "the lobes lie either side of y = 0");
7433    }
7434
7435    /// A wall just off the inner tangent has no node. Just past it the
7436    /// section has a gap 0.028 wide in tube angle about the inner equator,
7437    /// between two samples inside it, and is one loop turning either side of
7438    /// the gap; just short of it the section winds the tube twice. Every
7439    /// point lies on the wall.
7440    #[test]
7441    fn a_wall_just_off_the_inner_tangent_cuts_no_node() {
7442        let (major, minor) = (3.0, 1.0);
7443        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7444        for (x, loops) in [(2.0001, 1), (1.9999, 2)] {
7445            let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), x).unwrap();
7446            assert_eq!(curves.len(), loops, "x = {x}");
7447            for c in &curves {
7448                let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7449                assert_eq!(first, last, "x = {x}: the loop closes");
7450                for p in c.points.iter().map(|p| p.point) {
7451                    assert!((p.x() - x).abs() < 1e-9, "x = {x}: off the wall at {p:?}");
7452                    assert!(
7453                        torus_implicit(p, major, minor).abs() < 1e-6,
7454                        "x = {x}: off the torus at {p:?}"
7455                    );
7456                }
7457            }
7458        }
7459        // The loop past the tangent turns either side of the gap, 0.028 apart.
7460        let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), 2.0001).unwrap();
7461        let low = curves[0]
7462            .points
7463            .iter()
7464            .map(|p| p.point)
7465            .filter(|p| p.y().abs() < 1e-6)
7466            .map(Point3::z)
7467            .collect::<Vec<_>>();
7468        let gap = (2.0001_f64 - 2.0)
7469            .madd(2.0, -(2.0001_f64 - 2.0).powi(2))
7470            .sqrt();
7471        assert!(
7472            low.iter().any(|z| (z - gap).abs() < 1e-6)
7473                && low.iter().any(|z| (z + gap).abs() < 1e-6),
7474            "turns at {low:?}, not at z = ±{gap}"
7475        );
7476    }
7477
7478    /// A plane tangent to the tube's inner side off its equator, at a saddle,
7479    /// cuts a figure-eight that crosses itself where it touches. Its lobes
7480    /// come out as two loops, each starting and ending on that node.
7481    #[test]
7482    fn a_tilted_plane_tangent_inside_the_tube_cuts_two_loops_through_its_node() {
7483        let (major, minor) = (3.0, 1.0);
7484        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7485        for v0 in [1.7_f64, 2.0, 2.5, 4.0] {
7486            let normal = Vec3::new(v0.cos(), 0.0, v0.sin());
7487            let node = torus.evaluate(0.0, v0);
7488            let d = normal.dot(Vec3::new(node.x(), node.y(), node.z()));
7489            let curves = intersect_plane_torus(&torus, normal, d).unwrap();
7490            assert_eq!(curves.len(), 2, "v0 {v0}: one loop per lobe");
7491            for c in &curves {
7492                let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
7493                assert!(
7494                    (first - node).length() < 1e-6,
7495                    "v0 {v0}: starts at {first:?}, not {node:?}"
7496                );
7497                assert_eq!(first, last, "v0 {v0}: closes on the node");
7498                for p in c.points.iter().map(|p| p.point) {
7499                    let off = normal.dot(Vec3::new(p.x(), p.y(), p.z())) - d;
7500                    assert!(off.abs() < 1e-9, "v0 {v0}: off the plane at {p:?}");
7501                    assert!(
7502                        torus_implicit(p, major, minor).abs() < 1e-6,
7503                        "v0 {v0}: off the torus at {p:?}"
7504                    );
7505                }
7506            }
7507        }
7508    }
7509
7510    /// A wall parallel to the axis cuts one loop from the ring past the
7511    /// inner equator (its two turns where the branches meet), and two loops
7512    /// winding the tube inside it; each closes, at any scale, however near
7513    /// the wall runs to an equator.
7514    #[test]
7515    fn plane_torus_wall_sections_close_into_their_loops() {
7516        for (major, minor) in [(4.0, 1.5), (100.0, 30.0), (0.05, 0.01)] {
7517            let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7518            for k in 1..200 {
7519                let (d, want) = match k.cmp(&100) {
7520                    // Within the inner equator: two loops winding the tube.
7521                    std::cmp::Ordering::Less => ((major - minor) * f64::from(k) / 100.0, 2),
7522                    // Past it, short of the outer equator: one loop.
7523                    std::cmp::Ordering::Greater => (
7524                        2.0f64.madd(minor * f64::from(k - 100) / 100.0, major - minor),
7525                        1,
7526                    ),
7527                    std::cmp::Ordering::Equal => continue,
7528                };
7529                let loops = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), d, 128);
7530                let closed = loops
7531                    .iter()
7532                    .filter(|l| (l[0].point - l[l.len() - 1].point).length() < 1e-12)
7533                    .count();
7534                assert_eq!(
7535                    (loops.len(), closed),
7536                    (want, want),
7537                    "R {major} r {minor}, wall at {d}"
7538                );
7539            }
7540        }
7541    }
7542
7543    /// A plane through the centre tilted a little from the equator cuts two
7544    /// loops that each run all the way round the axis on a short run of `v`;
7545    /// their fitted curves stay on the torus.
7546    #[test]
7547    fn plane_torus_sections_round_the_axis_stay_on_the_torus() {
7548        let (major, minor) = (4.0, 1.5);
7549        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
7550        for tilt in [0.03_f64, 0.08, 0.2] {
7551            let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
7552            let curves = intersect_plane_torus(&torus, normal, 0.0).unwrap();
7553            assert_eq!(curves.len(), 2, "tilt {tilt}");
7554            for c in &curves {
7555                let (t0, t1) = c.curve.domain();
7556                let off = (0..=400)
7557                    .map(|k| {
7558                        let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 400.0, t0));
7559                        (p.x().hypot(p.y()) - major).hypot(p.z()) - minor
7560                    })
7561                    .fold(0.0_f64, |m, e| m.max(e.abs()));
7562                assert!(
7563                    off < 1e-6,
7564                    "tilt {tilt}: fitted section {off} off the torus"
7565                );
7566            }
7567        }
7568    }
7569
7570    #[test]
7571    fn line_torus_box_edge_crossing_is_exact() {
7572        // The census box edge x=6, y=-4 (z varying) crosses the torus (R=10,r=3)
7573        // at z = ±sqrt(r² − (rho−R)²), rho = hypot(6,4) ≈ 7.2111 → z ≈ ±1.1055.
7574        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
7575        let ts = intersect_line_torus(
7576            &torus,
7577            Point3::new(6.0, -4.0, -5.0),
7578            Vec3::new(0.0, 0.0, 1.0),
7579        );
7580        // Vertical line through (6,-4) meets the tube twice.
7581        assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
7582        let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
7583        let rho = 6.0_f64.hypot(4.0);
7584        let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
7585        assert!(
7586            (zs[0] - (-z_exp)).abs() < 1e-9,
7587            "z0={} exp={}",
7588            zs[0],
7589            -z_exp
7590        );
7591        assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
7592        // Each crossing lies on the torus.
7593        for &t in &ts {
7594            let p = Point3::new(6.0, -4.0, -5.0 + t);
7595            let rho = p.x().hypot(p.y());
7596            let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
7597            assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
7598        }
7599    }
7600
7601    /// A ray out of a pocket corner's spindle torus (major 0.1, minor 2.45)
7602    /// meets the tube swung across the axis at t 0.124 and its own tube at
7603    /// 0.398: each root lies on one of the two tubes, not polished off the
7604    /// first onto a point beside the second.
7605    #[test]
7606    fn line_spindle_torus_roots_lie_on_their_tubes() {
7607        let torus = ToroidalSurface::new(Point3::new(41.0, 17.0, 4.7), 0.1, 2.45).unwrap();
7608        let origin = Point3::new(42.36, 18.31, 3.4);
7609        let dir = Vec3::new(
7610            0.573_576_436_351_046,
7611            0.740_535_693_464_567_5,
7612            0.350_889_803_483_932_2,
7613        );
7614        let ts = intersect_line_torus(&torus, origin, dir);
7615        let tube = |t: f64, across: f64| {
7616            let q = origin + dir * t;
7617            ((q.x() - 41.0).hypot(q.y() - 17.0) - across * 0.1).hypot(q.z() - 4.7) - 2.45
7618        };
7619        for &t in &ts {
7620            assert!(
7621                tube(t, 1.0).abs().min(tube(t, -1.0).abs()) < 1e-9,
7622                "root {t} off both tubes in {ts:?}"
7623            );
7624        }
7625        for want in [0.124, 0.398] {
7626            assert!(
7627                ts.iter().any(|&t| (t - want).abs() < 1e-3),
7628                "no root near {want} in {ts:?}"
7629            );
7630        }
7631    }
7632
7633    #[test]
7634    fn line_torus_miss_and_tangent() {
7635        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
7636        // A vertical line at rho beyond the outer rim (x=20) misses entirely.
7637        let miss = intersect_line_torus(
7638            &torus,
7639            Point3::new(20.0, 0.0, 0.0),
7640            Vec3::new(0.0, 0.0, 1.0),
7641        );
7642        assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
7643        // The z-axis (rho=0) passes through the hole — no intersection.
7644        let axis =
7645            intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
7646        assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
7647    }
7648
7649    #[test]
7650    fn dispatch_via_analytic_surface() {
7651        let cyl =
7652            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7653                .unwrap();
7654        let curves = intersect_plane_analytic(
7655            AnalyticSurface::Cylinder(&cyl),
7656            Vec3::new(0.0, 0.0, 1.0),
7657            0.0,
7658        )
7659        .unwrap();
7660        assert!(!curves.is_empty());
7661    }
7662
7663    #[test]
7664    fn perpendicular_cylinders_intersect() {
7665        let cyl_z =
7666            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7667                .unwrap();
7668        let cyl_x =
7669            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7670                .unwrap();
7671
7672        let curves = intersect_analytic_analytic(
7673            AnalyticSurface::Cylinder(&cyl_z),
7674            AnalyticSurface::Cylinder(&cyl_x),
7675            16,
7676        )
7677        .unwrap();
7678
7679        assert!(
7680            !curves.is_empty(),
7681            "perpendicular cylinders should intersect"
7682        );
7683
7684        for c in &curves {
7685            assert!(
7686                c.points.len() >= 2,
7687                "intersection curve should have >= 2 points, got {}",
7688                c.points.len()
7689            );
7690        }
7691    }
7692
7693    /// Neither cylinder's rulings all meet the other: the curve is one loop
7694    /// joined at its two branch points.
7695    #[test]
7696    fn partially_overlapping_cylinders_meet_in_one_closed_loop() {
7697        let cyl_z =
7698            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7699                .unwrap();
7700        let cyl_x =
7701            CylindricalSurface::new(Point3::new(0.0, 1.2, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
7702                .unwrap();
7703        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
7704            .unwrap()
7705            .unwrap();
7706        assert_eq!(curves.len(), 1);
7707        let curve = &curves[0].curve;
7708        let (t0, t1) = curve.domain();
7709        assert!((curve.evaluate(t0) - curve.evaluate(t1)).length() < 1e-9);
7710        let off = |p: Point3| {
7711            let on_z = (p.x().hypot(p.y()) - 1.0).abs();
7712            let on_x = ((p.y() - 1.2).hypot(p.z()) - 1.0).abs();
7713            on_z.max(on_x)
7714        };
7715        let worst = (0..=400)
7716            .map(|k| off(curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0)))
7717            .fold(0.0, f64::max);
7718        assert!(worst < 2e-4, "curve leaves the cylinders by {worst}");
7719    }
7720
7721    /// Near tangency the thick cylinder's window of rulings (0.02 either side
7722    /// of a quarter turn) falls between its samples; the thin one's sweep
7723    /// finds the loop.
7724    #[test]
7725    fn near_tangent_cylinders_find_their_loop_on_the_thinner_sweep() {
7726        let cyl_z =
7727            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7728                .unwrap();
7729        let cyl_x =
7730            CylindricalSurface::new(Point3::new(0.0, 1.1998, 0.0), Vec3::new(1.0, 0.0, 0.0), 0.2)
7731                .unwrap();
7732        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
7733            .unwrap()
7734            .expect("the thin cylinder's sweep finds the loop");
7735        assert_eq!(curves.len(), 1);
7736    }
7737
7738    /// Cylinders of radius 1.5 whose axes cross at 60° meet in two ellipses
7739    /// crossing at the ends of the axes' common normal: two exact loops,
7740    /// one from each end, each the halves of both ellipses on one side of
7741    /// the crossing along the first axis, on both cylinders to rounding.
7742    #[test]
7743    fn equal_cylinders_with_crossing_axes_meet_in_two_cornered_loops() {
7744        let crossing = Point3::new(1.0, 2.0, 3.0);
7745        let (s, c) = 60.0_f64.to_radians().sin_cos();
7746        let (d1, d2) = (Vec3::new(0.0, 0.0, 1.0), Vec3::new(s, 0.0, c));
7747        let c1 = CylindricalSurface::new(crossing - d1 * 2.0, d1, 1.5).unwrap();
7748        let c2 = CylindricalSurface::new(crossing + d2 * 0.7, d2, 1.5).unwrap();
7749        let curves = algebraic_cylinder_cylinder(&c1, &c2).unwrap().unwrap();
7750        assert_eq!(curves.len(), 2);
7751        let off = |p: Point3, cyl: &CylindricalSurface| {
7752            let q = p - cyl.origin();
7753            ((q - cyl.axis() * q.dot(cyl.axis())).length() - 1.5).abs()
7754        };
7755        let ends = [
7756            crossing + Vec3::new(0.0, 1.5, 0.0),
7757            crossing - Vec3::new(0.0, 1.5, 0.0),
7758        ];
7759        let mut vertices: Vec<Point3> = Vec::new();
7760        for (ic, (end, side)) in curves.iter().zip([(ends[0], 1.0), (ends[1], -1.0)]) {
7761            let (t0, t1) = ic.curve.domain();
7762            for k in 0..=400 {
7763                let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
7764                assert!(off(p, &c1).max(off(p, &c2)) < 1e-13);
7765                assert!(side * (p - crossing).dot(d1) > -1e-13);
7766            }
7767            assert!((ic.curve.evaluate(t0) - end).length() < 1e-14);
7768            assert!((ic.curve.evaluate(t1) - end).length() < 1e-14);
7769            let other = ends[usize::from(side > 0.0)];
7770            assert!((ic.curve.evaluate(0.5) - other).length() < 1e-14);
7771            for t in [0.25, 0.75] {
7772                let vertex = ic.curve.evaluate(t);
7773                assert!(vertices.iter().all(|&v| (v - vertex).length() > 1.0));
7774                vertices.push(vertex);
7775            }
7776        }
7777    }
7778
7779    /// Axes that miss each other by 1e-9, or radii that differ by as much,
7780    /// part the curves where the ellipses would cross; neither is taken for
7781    /// a pair of ellipses, nor a miss of 1e-6 read between origins 1e8
7782    /// apart along an axis.
7783    #[test]
7784    fn nearly_crossing_equal_cylinders_are_not_ellipses() {
7785        let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7786            .unwrap();
7787        let x = |(x0, y): (f64, f64), r: f64| {
7788            CylindricalSurface::new(Point3::new(x0, y, 0.0), Vec3::new(1.0, 0.0, 0.0), r).unwrap()
7789        };
7790        let taken = |c: &CylindricalSurface| crossing_equal_cylinders(&z, c).unwrap().is_some();
7791        assert!(taken(&x((-2.0, 0.0), 1.0)));
7792        assert!(!taken(&x((-2.0, 1e-9), 1.0)));
7793        assert!(!taken(&x((-2.0, 0.0), 1.0 + 1e-9)));
7794        assert!(!taken(&x((-1e8, 1e-6), 1.0)));
7795    }
7796
7797    /// Axes 1e-8 and 1.5e-5 apart in angle cross in ellipses whose far
7798    /// vertices rounding alone would move past the tolerance; they are
7799    /// left to the rulings.
7800    #[test]
7801    fn nearly_parallel_equal_cylinders_are_not_ellipses() {
7802        let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 10.0)
7803            .unwrap();
7804        for slope in [1e-8, 1.5e-5] {
7805            let tilted = CylindricalSurface::new(
7806                Point3::new(0.0, 0.0, 0.0),
7807                Vec3::new(slope, 0.0, 1.0),
7808                10.0,
7809            )
7810            .unwrap();
7811            assert!(crossing_equal_cylinders(&z, &tilted).unwrap().is_none());
7812        }
7813    }
7814
7815    #[test]
7816    fn sphere_cylinder_intersect() {
7817        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
7818        let cyl =
7819            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7820                .unwrap();
7821
7822        let curves = intersect_analytic_analytic(
7823            AnalyticSurface::Sphere(&sphere),
7824            AnalyticSurface::Cylinder(&cyl),
7825            16,
7826        )
7827        .unwrap();
7828
7829        // A sphere of radius 2 and a cylinder of radius 1, both centered
7830        // at the origin, should intersect (the cylinder passes through
7831        // the sphere).
7832        assert!(!curves.is_empty(), "sphere and cylinder should intersect");
7833    }
7834
7835    #[test]
7836    fn exact_sphere_cylinder_coaxial_two_circles() {
7837        // Sphere r=6 at origin, coaxial cylinder r=3 along z: two latitude
7838        // circles at z = ±sqrt(36-9) = ±sqrt(27), each of radius 3.
7839        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
7840        let cyl =
7841            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
7842                .unwrap();
7843        let circles = exact_sphere_cylinder(&sphere, &cyl)
7844            .unwrap()
7845            .expect("coaxial case returns Some");
7846        assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
7847        let mut zs: Vec<f64> = circles
7848            .iter()
7849            .filter_map(|c| match c {
7850                ExactIntersectionCurve::Circle(circle) => {
7851                    assert!(
7852                        (circle.radius() - 3.0).abs() < 1e-9,
7853                        "rim radius == cyl radius"
7854                    );
7855                    Some(circle.center().z())
7856                }
7857                _ => None,
7858            })
7859            .collect();
7860        assert_eq!(zs.len(), 2, "both sections must be exact circles");
7861        zs.sort_by(f64::total_cmp);
7862        let z = 27.0_f64.sqrt();
7863        assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
7864    }
7865
7866    #[test]
7867    fn exact_sphere_cylinder_non_coaxial_defers() {
7868        // Cylinder axis offset from the sphere center → quartic curve, deferred.
7869        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
7870        let cyl =
7871            CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
7872                .unwrap();
7873        assert!(
7874            exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
7875            "non-coaxial sphere/cylinder defers to the marcher"
7876        );
7877    }
7878
7879    #[test]
7880    fn a_ball_on_a_cones_axis_meets_it_in_circles() {
7881        // Apex 3 up, opening downward, the radius half the depth below it.
7882        let cone = ConicalSurface::new(
7883            Point3::new(0.0, 0.0, 3.0),
7884            Vec3::new(0.0, 0.0, -1.0),
7885            2.0_f64.atan(),
7886        )
7887        .unwrap();
7888        for (height, radius, count) in [
7889            (0.0, 2.0, 2), // through the cone's middle
7890            (2.5, 1.3, 1), // swallowing the apex
7891            (2.5, 0.5, 1), // through the apex: the apex root is no circle
7892            (0.0, 1.0, 0), // inside, clear of the wall
7893            (5.0, 1.0, 0), // on the other nappe's side
7894        ] {
7895            let centre = Point3::new(0.0, 0.0, height);
7896            let ball = SphericalSurface::new(centre, radius).unwrap();
7897            let curves = exact_cone_sphere(&cone, &ball).unwrap().unwrap();
7898            let circles = circles_of(&curves);
7899            assert_eq!(circles.len(), count, "ball at {height}, radius {radius}");
7900            for circle in circles {
7901                for k in 0..16 {
7902                    let p = circle.evaluate(TAU * f64::from(k) / 16.0);
7903                    let on_ball = (p - centre).length() - radius;
7904                    let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
7905                    assert!(
7906                        on_ball.abs() < 1e-9 && on_cone.abs() < 1e-9,
7907                        "ball at {height}: off by {on_ball}, {on_cone}"
7908                    );
7909                }
7910            }
7911        }
7912        let aside = SphericalSurface::new(Point3::new(0.5, 0.0, 0.0), 2.0).unwrap();
7913        assert!(exact_cone_sphere(&cone, &aside).unwrap().is_none());
7914        // A ball touching a wide cone a million units out, where the
7915        // discriminant cancels to a few ulps below zero.
7916        let wide =
7917            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.3).unwrap();
7918        let far = SphericalSurface::new(Point3::new(0.0, 0.0, 1e6), 1e6 * 0.3_f64.cos()).unwrap();
7919        let curves = exact_cone_sphere(&wide, &far).unwrap().unwrap();
7920        let circles = circles_of(&curves);
7921        assert_eq!(circles.len(), 1, "the touch");
7922        let touch = 1e6 * 0.3_f64.sin() * 0.3_f64.cos();
7923        assert!(
7924            (circles[0].radius() - touch).abs() < 1e-3,
7925            "{}",
7926            circles[0].radius()
7927        );
7928    }
7929
7930    /// The circles among exact section curves.
7931    fn circles_of(curves: &[ExactIntersectionCurve]) -> Vec<&Circle3D> {
7932        curves
7933            .iter()
7934            .filter_map(|c| match c {
7935                ExactIntersectionCurve::Circle(circle) => Some(circle),
7936                _ => None,
7937            })
7938            .collect()
7939    }
7940
7941    /// Worst distance of a circle's points from a torus and from a second
7942    /// surface given by its own distance function.
7943    fn worst_off(
7944        circles: &[&Circle3D],
7945        torus: &ToroidalSurface,
7946        other: impl Fn(Point3) -> f64,
7947    ) -> f64 {
7948        let mut worst = 0.0_f64;
7949        for circle in circles {
7950            for k in 0..16 {
7951                let p = circle.evaluate(TAU * f64::from(k) / 16.0);
7952                let q = p - torus.center();
7953                let along = q.dot(torus.z_axis());
7954                let rho = (q - torus.z_axis() * along).length();
7955                let off = ((rho - torus.major_radius()).hypot(along) - torus.minor_radius()).abs();
7956                worst = worst.max(off).max(other(p).abs());
7957            }
7958        }
7959        worst
7960    }
7961
7962    #[test]
7963    fn exact_sphere_torus_meets_a_ball_on_the_axis_in_circles() {
7964        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7965        for height in [0.0, 1.0] {
7966            let centre = Point3::new(0.0, 0.0, height);
7967            let sphere = SphericalSurface::new(centre, 3.0).unwrap();
7968            let curves = exact_sphere_torus(&sphere, &torus).unwrap().unwrap();
7969            let circles = circles_of(&curves);
7970            assert_eq!((curves.len(), circles.len()), (2, 2), "height {height}");
7971            let worst = worst_off(&circles, &torus, |p| (p - centre).length() - 3.0);
7972            assert!(worst < 1e-9, "height {height}: {worst}");
7973        }
7974    }
7975
7976    /// Balls off a ring torus's axis, one poking out of the tube's top, one
7977    /// wider than the tube on its core circle, one anywhere, and one just past
7978    /// the tube's outside, in a loop narrower than the scan's step, meet the
7979    /// torus in curves whose points lie on both surfaces, given either way
7980    /// round, where the marcher found nothing with the torus first.
7981    #[test]
7982    fn a_ball_off_a_torus_axis_meets_it_in_its_closed_form_loops() {
7983        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
7984        let on_torus = |p: Point3| (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
7985        for (centre, radius, loops) in [
7986            (Point3::new(4.0, 0.0, 1.0), 1.0, 1),
7987            (Point3::new(4.0, 0.0, 0.0), 2.0, 2),
7988            (Point3::new(2.0, 1.0, 0.5), 1.2, 1),
7989            (Point3::new(6.4999, 0.0, 0.0), 1.0, 1),
7990        ] {
7991            let ball = SphericalSurface::new(centre, radius).unwrap();
7992            let on_ball = |p: Point3| (p - centre).length() - radius;
7993            for ball_first in [true, false] {
7994                let (a, b) = if ball_first {
7995                    (
7996                        AnalyticSurface::Sphere(&ball),
7997                        AnalyticSurface::Torus(&torus),
7998                    )
7999                } else {
8000                    (
8001                        AnalyticSurface::Torus(&torus),
8002                        AnalyticSurface::Sphere(&ball),
8003                    )
8004                };
8005                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8006                let case = format!("ball {radius} at {centre:?}, ball first {ball_first}");
8007                assert_eq!(curves.len(), loops, "{case}");
8008                for ic in &curves {
8009                    for q in &ic.points {
8010                        let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
8011                        assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
8012                        let (on_ball_at, on_torus_at) = if ball_first {
8013                            (q.param1, q.param2)
8014                        } else {
8015                            (q.param2, q.param1)
8016                        };
8017                        let (pb, pt) = (
8018                            ball.evaluate(on_ball_at.0, on_ball_at.1),
8019                            torus.evaluate(on_torus_at.0, on_torus_at.1),
8020                        );
8021                        assert!(
8022                            (pb - q.point).length() < 1e-9 && (pt - q.point).length() < 1e-9,
8023                            "{case}: a point's parameters miss it"
8024                        );
8025                    }
8026                    let (t0, t1) = ic.curve.domain();
8027                    for k in 0..=400 {
8028                        let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
8029                        let off = on_ball(p).abs().max(on_torus(p).abs());
8030                        assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
8031                    }
8032                }
8033            }
8034        }
8035    }
8036
8037    /// Balls whose loops a fixed scan of the tube misses or blurs: one far
8038    /// smaller than its torus, one near the axis whose two loops share a
8039    /// scan step, one a hair larger than the tube it sits in, whose two
8040    /// loops lie close together all the way round, and one whose winding
8041    /// loops swing round the axis within a few scan steps. Each loop is met
8042    /// either way round, and its curve holds to both surfaces.
8043    #[test]
8044    fn balls_meet_tori_in_loops_a_scan_would_miss() {
8045        for (big, small, centre, radius, loops) in [
8046            (4000.0, 1500.0, Point3::new(5500.0, 0.0, 0.0), 0.001, 1),
8047            (4.0, 1.5, Point3::new(1e-6, 0.0, 0.0), 2.500_002, 2),
8048            (1000.0, 1.0, Point3::new(1000.0, 0.0, 0.0), 1.000_000_5, 2),
8049            (4.0, 1.5, Point3::new(1.500_001, 0.0, 0.0), 4.0, 2),
8050        ] {
8051            let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), big, small).unwrap();
8052            let ball = SphericalSurface::new(centre, radius).unwrap();
8053            let on_torus = |p: Point3| (p.x().hypot(p.y()) - big).hypot(p.z()) - small;
8054            let on_ball = |p: Point3| (p - centre).length() - radius;
8055            for ball_first in [true, false] {
8056                let (a, b) = if ball_first {
8057                    (
8058                        AnalyticSurface::Sphere(&ball),
8059                        AnalyticSurface::Torus(&torus),
8060                    )
8061                } else {
8062                    (
8063                        AnalyticSurface::Torus(&torus),
8064                        AnalyticSurface::Sphere(&ball),
8065                    )
8066                };
8067                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8068                let case = format!("ball {radius} at {centre:?} on torus ({big}, {small})");
8069                assert_eq!(curves.len(), loops, "{case}");
8070                for ic in &curves {
8071                    for q in &ic.points {
8072                        let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
8073                        assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
8074                    }
8075                    let (t0, t1) = ic.curve.domain();
8076                    for k in 0..=2000 {
8077                        let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
8078                        let off = on_ball(p).abs().max(on_torus(p).abs());
8079                        assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
8080                    }
8081                }
8082            }
8083        }
8084    }
8085
8086    /// Sections a closed form can lose to scale or rounding: a plane whose
8087    /// equation is scaled by 1e14 keeps the loop of the plane it describes; a
8088    /// ball 1e-5 across poking out of a large torus, and a ball a micron wider
8089    /// than the tube of a ring 1e8 across, defer to the marcher instead of
8090    /// reading as apart, and the last is not taken for the meridian circle.
8091    #[test]
8092    fn scaled_and_ill_conditioned_sections_are_kept_or_deferred() {
8093        let origin = Point3::new(0.0, 0.0, 0.0);
8094        let torus = ToroidalSurface::new(origin, 4.0, 1.5).unwrap();
8095        let unit = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), 4.0, 128).len();
8096        let scaled = plane_torus_loops(&torus, Vec3::new(1e14, 0.0, 0.0), 4e14, 128).len();
8097        assert_eq!((unit, scaled), (1, 1));
8098
8099        let large = ToroidalSurface::new(origin, 4000.0, 1500.0).unwrap();
8100        let speck = SphericalSurface::new(Point3::new(5_500.000_001, 0.0, 0.0), 1e-5).unwrap();
8101        assert!(sphere_torus_curves(&speck, &large, true).is_none());
8102
8103        let ring = ToroidalSurface::new(origin, 1e8, 1.0).unwrap();
8104        let ball = SphericalSurface::new(Point3::new(1e8, 0.0, 0.0), 1.000_001).unwrap();
8105        assert!(exact_sphere_torus(&ball, &ring).unwrap().is_none());
8106        assert!(sphere_torus_curves(&ball, &ring, true).is_none());
8107    }
8108
8109    /// A ball centred on a ring torus's core circle with the tube's own
8110    /// radius meets it along the meridian circle through its centre: one
8111    /// circle, given either way round.
8112    #[test]
8113    fn a_ball_filling_a_torus_tube_meets_it_in_one_meridian_circle() {
8114        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8115        let centre = Point3::new(4.0, 0.0, 0.0);
8116        let ball = SphericalSurface::new(centre, 1.5).unwrap();
8117        for (a, b) in [
8118            (
8119                AnalyticSurface::Sphere(&ball),
8120                AnalyticSurface::Torus(&torus),
8121            ),
8122            (
8123                AnalyticSurface::Torus(&torus),
8124                AnalyticSurface::Sphere(&ball),
8125            ),
8126        ] {
8127            let curves = intersect_analytic_analytic(a, b, 32).unwrap();
8128            assert_eq!(curves.len(), 1);
8129            let (t0, t1) = curves[0].curve.domain();
8130            for k in 0..=100 {
8131                let p = curves[0]
8132                    .curve
8133                    .evaluate(t0 + (t1 - t0) * f64::from(k) / 100.0);
8134                let off = ((p - centre).length() - 1.5).abs().max(p.y().abs());
8135                assert!(off < 1e-9, "the circle strays {off:.2e}");
8136            }
8137        }
8138    }
8139
8140    #[test]
8141    fn exact_sphere_torus_misses_touches_and_defers() {
8142        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8143        let ball = |x: f64, r: f64| SphericalSurface::new(Point3::new(x, 0.0, 0.0), r).unwrap();
8144        assert!(
8145            exact_sphere_torus(&ball(0.0, 1.0), &torus)
8146                .unwrap()
8147                .unwrap()
8148                .is_empty(),
8149            "a small ball in the hole misses"
8150        );
8151        let touching = exact_sphere_torus(&ball(0.0, 2.5), &torus)
8152            .unwrap()
8153            .unwrap();
8154        let circles = circles_of(&touching);
8155        assert_eq!(
8156            circles.len(),
8157            1,
8158            "a ball in the hole touches the inner equator"
8159        );
8160        assert!((circles[0].radius() - 2.5).abs() < 1e-12);
8161        assert!(circles[0].center().z().abs() < 1e-12);
8162        assert!(
8163            exact_sphere_torus(&ball(1.0, 3.0), &torus)
8164                .unwrap()
8165                .is_none(),
8166            "a ball off the axis defers"
8167        );
8168        let spindle = ToroidalSurface::with_axis_and_ref_dir(
8169            Point3::new(0.0, 0.0, 0.0),
8170            1.0,
8171            2.0,
8172            Vec3::new(0.0, 0.0, 1.0),
8173            Vec3::new(1.0, 0.0, 0.0),
8174        )
8175        .unwrap();
8176        assert!(
8177            exact_sphere_torus(&ball(0.0, 2.5), &spindle)
8178                .unwrap()
8179                .is_none()
8180        );
8181    }
8182
8183    /// A rod of radius 0.6 along `y` through the ring (4, 1.5) at `x = 0.5`,
8184    /// `z = 1` leaves the tube through its top, and meets it in one loop on
8185    /// each side of the ring. The march back to a loop's seed can be several
8186    /// steps long; each loop's curve lies on both surfaces all along it.
8187    #[test]
8188    fn a_marched_loop_closes_on_both_surfaces() {
8189        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8190        let rod =
8191            CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
8192                .unwrap();
8193        let region = Aabb3 {
8194            min: Point3::new(-0.1, -5.5, 0.4),
8195            max: Point3::new(1.1, 5.5, 1.5),
8196        };
8197        let curves = intersect_analytic_analytic_in_region(
8198            AnalyticSurface::Cylinder(&rod),
8199            AnalyticSurface::Torus(&torus),
8200            32,
8201            Some((-10.0, 10.0)),
8202            None,
8203            region,
8204        )
8205        .unwrap();
8206        assert_eq!(curves.len(), 2);
8207        for c in &curves {
8208            let (t0, t1) = c.curve.domain();
8209            let worst = (0..=4000)
8210                .map(|k| {
8211                    let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 4000.0, t0));
8212                    let on_torus = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
8213                    let on_rod = ((p.x() - 0.5).hypot(p.z() - 1.0) - 0.6).abs();
8214                    on_torus.max(on_rod)
8215                })
8216                .fold(0.0, f64::max);
8217            assert!(worst <= 1e-7, "off the surfaces by {worst}");
8218        }
8219    }
8220
8221    /// A funnel's outer wall, a 45 degree cone, crosses the tube of a lip
8222    /// that leans a thousandth of a radian off the cone's axis in one loop
8223    /// round the axis. The marcher closes the loop on its seed, and the loop
8224    /// runs round the axis once.
8225    #[test]
8226    fn a_marched_loop_round_an_axis_runs_round_it_once() {
8227        let skin = 1.6 * std::f64::consts::SQRT_2;
8228        let tilt = 0.001_f64;
8229        let torus = ToroidalSurface::with_axis(
8230            Point3::new(0.0, 0.0, 70.5),
8231            80.8 + skin / 2.0,
8232            2.0,
8233            Vec3::new(0.0, -tilt.sin(), tilt.cos()),
8234        )
8235        .unwrap();
8236        let cone = ConicalSurface::new(
8237            Point3::new(0.0, 0.0, -9.5 - skin),
8238            Vec3::new(0.0, 0.0, 1.0),
8239            std::f64::consts::FRAC_PI_4,
8240        )
8241        .unwrap();
8242        let region = Aabb3 {
8243            min: Point3::new(-84.0, -84.0, 68.0),
8244            max: Point3::new(84.0, 84.0, 73.0),
8245        };
8246        let curves = intersect_analytic_analytic_in_region(
8247            AnalyticSurface::Cone(&cone),
8248            AnalyticSurface::Torus(&torus),
8249            32,
8250            Some((16.6, 116.3)),
8251            None,
8252            region,
8253        )
8254        .unwrap();
8255        assert_eq!(curves.len(), 1);
8256        let (t0, t1) = curves[0].curve.domain();
8257        let (start, end) = (curves[0].curve.evaluate(t0), curves[0].curve.evaluate(t1));
8258        assert!((start - end).length() < 1e-9, "{start:?} to {end:?}");
8259        let n = 4000;
8260        let mut turn = 0.0;
8261        let mut last = start.y().atan2(start.x());
8262        for k in 1..=n {
8263            let p = curves[0]
8264                .curve
8265                .evaluate((t1 - t0).madd(f64::from(k) / f64::from(n), t0));
8266            let at = p.y().atan2(p.x());
8267            turn += (at - last + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
8268            last = at;
8269        }
8270        assert!((turn.abs() - TAU).abs() < 1e-6, "turns {}", turn / TAU);
8271    }
8272
8273    /// A 45 degree cone about the axis of the ring (4, 1.5), its apex at
8274    /// `z = apex` below the ring: its generator `ρ = z − apex` stands
8275    /// `|4 + apex| / √2` from the tube's centre in the half-plane.
8276    #[test]
8277    fn exact_cone_torus_meets_a_coaxial_cone_in_circles() {
8278        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8279        let z = Vec3::new(0.0, 0.0, 1.0);
8280        let quarter = std::f64::consts::FRAC_PI_4;
8281        let cone = |apex: f64, axis: Vec3| {
8282            ConicalSurface::new(Point3::new(0.0, 0.0, apex), axis, quarter).unwrap()
8283        };
8284        let on_cone = |apex: f64| move |p: Point3| p.x().hypot(p.y()) - (p.z() - apex);
8285        let curves = exact_cone_torus(&cone(-5.0, z), &torus).unwrap().unwrap();
8286        let circles = circles_of(&curves);
8287        assert_eq!(
8288            (curves.len(), circles.len()),
8289            (2, 2),
8290            "a wall through the tube"
8291        );
8292        let worst = worst_off(&circles, &torus, on_cone(-5.0));
8293        assert!(worst < 1e-12, "{worst}");
8294        assert!(
8295            exact_cone_torus(&cone(-8.0, z), &torus)
8296                .unwrap()
8297                .unwrap()
8298                .is_empty(),
8299            "a wall clear of the tube misses it"
8300        );
8301        let touch = -4.0 - 1.5 * std::f64::consts::SQRT_2;
8302        let curves = exact_cone_torus(&cone(touch, z), &torus).unwrap().unwrap();
8303        let circles = circles_of(&curves);
8304        assert_eq!(circles.len(), 1, "a wall touching the tube");
8305        let worst = worst_off(&circles, &torus, on_cone(touch));
8306        assert!(worst < 1e-12, "{worst}");
8307        assert_eq!(
8308            exact_cone_torus(&cone(touch + 1e-6, z), &torus)
8309                .unwrap()
8310                .unwrap()
8311                .len(),
8312            2,
8313            "a wall into the tube by more than the tolerance crosses it twice"
8314        );
8315        // The cone's axis may run either way along the torus's.
8316        let below = ConicalSurface::new(Point3::new(0.0, 0.0, 5.0), -z, quarter).unwrap();
8317        let curves = exact_cone_torus(&below, &torus).unwrap().unwrap();
8318        let circles = circles_of(&curves);
8319        assert_eq!(circles.len(), 2);
8320        let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - (5.0 - p.z()));
8321        assert!(worst < 1e-12, "{worst}");
8322        let tilted = cone(-5.0, Vec3::new(0.0, 0.1, 1.0));
8323        let offset = ConicalSurface::new(Point3::new(0.5, 0.0, -5.0), z, quarter).unwrap();
8324        assert!(exact_cone_torus(&tilted, &torus).unwrap().is_none());
8325        assert!(exact_cone_torus(&offset, &torus).unwrap().is_none());
8326        // A near cylinder whose apex lies a million below, its axis 0.0005
8327        // beside the torus's: radius 4.75 at the torus, off its axis.
8328        let far = ConicalSurface::new(Point3::new(0.0005, 0.0, -1e6), z, (1e6_f64 / 4.75).atan())
8329            .unwrap();
8330        assert!(
8331            exact_cone_torus(&far, &torus).unwrap().is_none(),
8332            "a cone off the torus's axis by 0.0005 is not coaxial, however far its apex"
8333        );
8334        let spindle = ToroidalSurface::with_axis_and_ref_dir(
8335            Point3::new(0.0, 0.0, 0.0),
8336            1.0,
8337            2.0,
8338            z,
8339            Vec3::new(1.0, 0.0, 0.0),
8340        )
8341        .unwrap();
8342        assert!(
8343            exact_cone_torus(&cone(-5.0, z), &spindle)
8344                .unwrap()
8345                .is_none(),
8346            "a spindle torus's tube reaches the axis"
8347        );
8348    }
8349
8350    #[test]
8351    fn exact_cylinder_torus_meets_a_coaxial_rod_in_circles() {
8352        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
8353        let z = Vec3::new(0.0, 0.0, 1.0);
8354        let rod = |r: f64| CylindricalSurface::new(Point3::new(0.0, 0.0, -5.0), z, r).unwrap();
8355        let curves = exact_cylinder_torus(&rod(4.2), &torus).unwrap().unwrap();
8356        let circles = circles_of(&curves);
8357        assert_eq!((curves.len(), circles.len()), (2, 2));
8358        let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - 4.2);
8359        assert!(worst < 1e-9, "{worst}");
8360        assert!(
8361            exact_cylinder_torus(&rod(2.0), &torus)
8362                .unwrap()
8363                .unwrap()
8364                .is_empty(),
8365            "a rod clear in the hole misses"
8366        );
8367        for (wall, label) in [(5.5, "outer"), (2.5, "inner")] {
8368            let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
8369            let circles = circles_of(&curves);
8370            assert_eq!(circles.len(), 1, "a wall touching the {label} equator");
8371            assert!(circles[0].center().z().abs() < 1e-12, "{label}");
8372            let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - wall);
8373            assert!(worst < 1e-9, "{label}: {worst}");
8374        }
8375        assert!(
8376            exact_cylinder_torus(&rod(5.5 + 1e-6), &torus)
8377                .unwrap()
8378                .unwrap()
8379                .is_empty(),
8380            "a wall clear of the tube by more than the tolerance misses it"
8381        );
8382        assert_eq!(
8383            exact_cylinder_torus(&rod(5.5 - 1e-6), &torus)
8384                .unwrap()
8385                .unwrap()
8386                .len(),
8387            2,
8388            "a wall into the tube by more than the tolerance crosses it twice"
8389        );
8390        // Within the linear tolerance of the tube the wall reads as touching
8391        // it: the two crossings lie under 1e-3 apart on a band the wall
8392        // never leaves by more than that tolerance.
8393        for wall in [5.5 - 5e-8, 5.5 + 5e-8] {
8394            let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
8395            assert_eq!(circles_of(&curves).len(), 1, "a wall at {wall}");
8396        }
8397        let tilted =
8398            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 1.0), 4.2)
8399                .unwrap();
8400        let offset = CylindricalSurface::new(Point3::new(0.5, 0.0, 0.0), z, 4.2).unwrap();
8401        assert!(exact_cylinder_torus(&tilted, &torus).unwrap().is_none());
8402        assert!(exact_cylinder_torus(&offset, &torus).unwrap().is_none());
8403        let spindle = ToroidalSurface::with_axis_and_ref_dir(
8404            Point3::new(0.0, 0.0, 0.0),
8405            1.0,
8406            2.0,
8407            z,
8408            Vec3::new(1.0, 0.0, 0.0),
8409        )
8410        .unwrap();
8411        assert!(
8412            exact_cylinder_torus(&rod(0.5), &spindle).unwrap().is_none(),
8413            "a spindle torus's inner lemon also meets the rod"
8414        );
8415        // The rounded air wall of a fillet whose radius nearly fills its
8416        // corner: the spindle's outer equator rests on the wall.
8417        let spindle = ToroidalSurface::with_axis_and_ref_dir(
8418            Point3::new(0.0, 0.0, 4.7),
8419            0.1,
8420            2.45,
8421            z,
8422            Vec3::new(1.0, 0.0, 0.0),
8423        )
8424        .unwrap();
8425        let curves = exact_cylinder_torus(&rod(2.55), &spindle).unwrap().unwrap();
8426        let circles = circles_of(&curves);
8427        assert_eq!(circles.len(), 1);
8428        assert!((circles[0].center().z() - 4.7).abs() < 1e-12);
8429        let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.55);
8430        assert!(worst < 1e-9, "{worst}");
8431        let curves = exact_cylinder_torus(&rod(2.4), &spindle).unwrap().unwrap();
8432        let circles = circles_of(&curves);
8433        assert_eq!(circles.len(), 2, "a wall into the spindle's outer tube");
8434        let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.4);
8435        assert!(worst < 1e-9, "{worst}");
8436    }
8437
8438    /// Loops of an off-axis sphere-cylinder pair: `(count, worst distance
8439    /// from either surface)`.
8440    fn off_axis_loops(cylinder_origin: Point3, cylinder_radius: f64) -> (usize, f64) {
8441        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
8442        let cyl =
8443            CylindricalSurface::new(cylinder_origin, Vec3::new(0.0, 0.0, 1.0), cylinder_radius)
8444                .unwrap();
8445        let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
8446            .unwrap()
8447            .unwrap();
8448        let mut worst: f64 = 0.0;
8449        for c in &curves {
8450            for ip in &c.points {
8451                let on_sphere = sphere.evaluate(ip.param1.0, ip.param1.1);
8452                let on_cylinder = cyl.evaluate(ip.param2.0, ip.param2.1);
8453                worst = worst
8454                    .max((on_sphere - ip.point).length())
8455                    .max((on_cylinder - ip.point).length());
8456            }
8457            let (t0, t1) = c.curve.domain();
8458            assert!((c.curve.evaluate(t0) - c.curve.evaluate(t1)).length() < 1e-9);
8459            for k in 0..=400 {
8460                let p = c.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
8461                let on_sphere = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 2.0).abs();
8462                let on_cylinder = ((p.x() - cylinder_origin.x())
8463                    .hypot(p.y() - cylinder_origin.y())
8464                    - cylinder_radius)
8465                    .abs();
8466                worst = worst.max(on_sphere).max(on_cylinder);
8467            }
8468        }
8469        (curves.len(), worst)
8470    }
8471
8472    /// A drill off the ball's axis passes through it: an entry and an exit
8473    /// loop.
8474    #[test]
8475    fn off_axis_drill_through_a_sphere_meets_it_in_two_loops() {
8476        let (count, worst) = off_axis_loops(Point3::new(0.5, 0.0, 0.0), 0.2);
8477        assert_eq!(count, 2);
8478        assert!(worst < 1e-5, "loops leave the surfaces by {worst}");
8479    }
8480
8481    /// A cylinder over the ball's side: one loop joined at its branch points.
8482    #[test]
8483    fn cylinder_over_a_spheres_side_meets_it_in_one_loop() {
8484        let (count, worst) = off_axis_loops(Point3::new(1.8, 0.0, 0.0), 0.5);
8485        assert_eq!(count, 1);
8486        assert!(worst < 5e-4, "loop leaves the surfaces by {worst}");
8487    }
8488
8489    /// A ball through the wall of a ring far wider than it: the rulings that
8490    /// meet the ball span a twelfth of the turn, and the loop through them
8491    /// stays on both surfaces.
8492    #[test]
8493    fn a_ball_through_a_wide_wall_meets_it_in_one_close_loop() {
8494        let centre = Point3::new(7.35, 0.0, 0.0);
8495        let sphere = SphericalSurface::new(centre, 2.4145).unwrap();
8496        let cyl =
8497            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 9.15)
8498                .unwrap();
8499        let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
8500            .unwrap()
8501            .unwrap();
8502        assert_eq!(curves.len(), 1);
8503        let (t0, t1) = curves[0].curve.domain();
8504        let mut worst: f64 = 0.0;
8505        for k in 0..=2000 {
8506            let p = curves[0]
8507                .curve
8508                .evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
8509            let on_sphere = ((p - centre).length() - 2.4145).abs();
8510            let on_cylinder = (p.x().hypot(p.y()) - 9.15).abs();
8511            worst = worst.max(on_sphere).max(on_cylinder);
8512        }
8513        assert!(worst < 1e-6, "the loop leaves the surfaces by {worst}");
8514    }
8515
8516    /// A whole torus ends where it starts both ways round; its size is read
8517    /// from its first corner to its middle, across the ring.
8518    #[test]
8519    fn a_whole_torus_patch_spans_its_ring() {
8520        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 50.0, 10.0).unwrap();
8521        let size = patch_diagonal(&|u, v| torus.evaluate(u, v), (0.0, TAU), (0.0, TAU));
8522        assert!((size - 100.0).abs() < 1e-9, "size {size}");
8523    }
8524
8525    /// A cone's face, between two of its circles, and a cylinder's face
8526    /// across it: each marched curve ends on the edge of one face's band,
8527    /// where the other faces' sections meet it, not a march step short.
8528    #[test]
8529    fn marched_cone_cylinder_curves_end_on_the_band_edges() {
8530        let half_angle = 14.0_f64.atan2(10.0);
8531        let cone = ConicalSurface::new(
8532            Point3::new(0.0, 0.0, 273.2),
8533            Vec3::new(0.0, 0.0, -1.0),
8534            half_angle,
8535        )
8536        .unwrap();
8537        let cyl = CylindricalSurface::new(
8538            Point3::new(0.0, -50.0, 215.0),
8539            Vec3::new(0.0, 1.0, 0.0),
8540            60.0,
8541        )
8542        .unwrap();
8543        // The cone from z = 192 down to z = 178, the cylinder from y = -40
8544        // to y = 40.
8545        let v_cone = (81.2 / half_angle.sin(), 95.2 / half_angle.sin());
8546        let region = Aabb3 {
8547            min: Point3::new(-59.98, -40.0, 178.0),
8548            max: Point3::new(-47.23, 40.0, 192.0),
8549        };
8550        let curves = intersect_analytic_analytic_in_region(
8551            AnalyticSurface::Cone(&cone),
8552            AnalyticSurface::Cylinder(&cyl),
8553            32,
8554            Some(v_cone),
8555            Some((10.0, 90.0)),
8556            region,
8557        )
8558        .unwrap();
8559        assert_eq!(curves.len(), 2);
8560        for c in &curves {
8561            let (t0, t1) = c.curve.domain();
8562            for p in [c.curve.evaluate(t0), c.curve.evaluate(t1)] {
8563                let on_edge = (p.z() - 192.0).abs() < 1e-6 || (p.y().abs() - 40.0).abs() < 1e-6;
8564                assert!(on_edge, "a curve ends at {p:?}");
8565            }
8566        }
8567    }
8568
8569    /// Long steps along the same cone and cylinder: a step whose predictor
8570    /// leaves a band while the curve stays on it carries the march on, and
8571    /// each end still lies on a band's edge.
8572    #[test]
8573    fn long_march_steps_end_on_the_band_edges() {
8574        let half_angle = 14.0_f64.atan2(10.0);
8575        let cone = ConicalSurface::new(
8576            Point3::new(0.0, 0.0, 273.2),
8577            Vec3::new(0.0, 0.0, -1.0),
8578            half_angle,
8579        )
8580        .unwrap();
8581        let cyl = CylindricalSurface::new(
8582            Point3::new(0.0, -50.0, 215.0),
8583            Vec3::new(0.0, 1.0, 0.0),
8584            60.0,
8585        )
8586        .unwrap();
8587        let (a, b) = (
8588            AnalyticSurface::Cone(&cone),
8589            AnalyticSurface::Cylinder(&cyl),
8590        );
8591        let (surf_a, norm_a, u_a, _) = surface_closures(&a);
8592        let (surf_b, norm_b, u_b, _) = surface_closures(&b);
8593        let v_a = (81.2 / half_angle.sin(), 95.2 / half_angle.sin());
8594        let v_b = (10.0, 90.0);
8595        let seed = correct_to_intersection(
8596            &a,
8597            &b,
8598            surf_a.as_ref(),
8599            norm_a.as_ref(),
8600            surf_b.as_ref(),
8601            norm_b.as_ref(),
8602            Point3::new(-53.0, -30.0, 187.0),
8603            u_a,
8604            v_a,
8605            u_b,
8606            v_b,
8607            20,
8608        );
8609        for step in [0.5, 1.0, 2.0, 3.0] {
8610            let points = march_analytic_intersection(
8611                &a,
8612                &b,
8613                surf_a.as_ref(),
8614                norm_a.as_ref(),
8615                surf_b.as_ref(),
8616                norm_b.as_ref(),
8617                seed,
8618                u_a,
8619                v_a,
8620                u_b,
8621                v_b,
8622                step,
8623                true,
8624                true,
8625                None,
8626            )
8627            .unwrap();
8628            for p in [points[0], points[points.len() - 1]] {
8629                let on_edge = (p.z() - 192.0).abs() < 1e-6 || (p.y().abs() - 40.0).abs() < 1e-6;
8630                assert!(on_edge, "step {step}: the march ends at {p:?}");
8631            }
8632        }
8633    }
8634
8635    #[test]
8636    fn disjoint_cylinders_no_intersection() {
8637        let cyl_a =
8638            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
8639                .unwrap();
8640        let cyl_b =
8641            CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
8642                .unwrap();
8643
8644        let curves = intersect_analytic_analytic(
8645            AnalyticSurface::Cylinder(&cyl_a),
8646            AnalyticSurface::Cylinder(&cyl_b),
8647            16,
8648        )
8649        .unwrap();
8650
8651        assert!(curves.is_empty(), "disjoint cylinders should not intersect");
8652    }
8653
8654    // ── Oblique plane × cone conic (ellipse / parabola / hyperbola) ──────
8655
8656    /// Collect 3D points from a returned exact curve, sampling analytic forms.
8657    fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
8658        use crate::traits::ParametricCurve;
8659        match curve {
8660            ExactIntersectionCurve::Circle(c) => (0..=64)
8661                .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
8662                .collect(),
8663            ExactIntersectionCurve::Ellipse(e) => (0..=64)
8664                .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
8665                .collect(),
8666            ExactIntersectionCurve::Points(pts) => pts.clone(),
8667        }
8668    }
8669
8670    /// Assert every returned point lies on the plane and the cone surface, on
8671    /// the real (`v >= 0`) nappe, and within a sane axial bound.
8672    fn assert_on_plane_and_cone(
8673        curves: &[ExactIntersectionCurve],
8674        cone: &ConicalSurface,
8675        n: Vec3,
8676        d: f64,
8677        z_bound: (f64, f64),
8678    ) {
8679        assert!(!curves.is_empty(), "expected at least one section curve");
8680        let mut total = 0;
8681        for curve in curves {
8682            for p in collect_points(curve) {
8683                total += 1;
8684                let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
8685                assert!(
8686                    plane_err < 1e-9,
8687                    "point off plane by {plane_err:.2e}: {p:?}"
8688                );
8689                let (u, v) = cone.project_point(p);
8690                let q = cone.evaluate(u, v);
8691                let cone_err =
8692                    ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
8693                        .sqrt();
8694                assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
8695                assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
8696                assert!(
8697                    p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
8698                    "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
8699                    p.z()
8700                );
8701            }
8702        }
8703        assert!(total >= 8, "too few section points ({total})");
8704    }
8705
8706    #[test]
8707    fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
8708        // 45°-half-angle cone (axis +z). A plane tilted only ~16.7° off horizontal
8709        // has plane-axis angle ≈ 73° > 45° (the cone's half-opening from axis) →
8710        // ellipse. Must come back as an exact Ellipse, fully on both surfaces.
8711        let cone = ConicalSurface::new(
8712            Point3::new(0.0, 0.0, 0.0),
8713            Vec3::new(0.0, 0.0, 1.0),
8714            std::f64::consts::FRAC_PI_4,
8715        )
8716        .unwrap();
8717        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
8718        // Plane through (0,0,5): d = n·(0,0,5).
8719        let d = n.z() * 5.0;
8720        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8721        assert!(
8722            curves
8723                .iter()
8724                .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
8725            "oblique steep plane × cone must yield an exact Ellipse"
8726        );
8727        // The ellipse straddles z=5; with the 0.3 tilt the z-extent stays modest.
8728        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
8729    }
8730
8731    #[test]
8732    fn oblique_plane_cone_wrong_nappe_is_empty() {
8733        // Same ellipse-regime plane as above, but offset to the FAR side of the
8734        // apex (z=-5). The +z cone's real (v≥0) nappe is not met — only the
8735        // phantom v<0 nappe — so the result must be EMPTY, not a phantom ellipse.
8736        let cone = ConicalSurface::new(
8737            Point3::new(0.0, 0.0, 0.0),
8738            Vec3::new(0.0, 0.0, 1.0),
8739            std::f64::consts::FRAC_PI_4,
8740        )
8741        .unwrap();
8742        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
8743        let d = n.z() * -5.0;
8744        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8745        assert!(
8746            curves.is_empty(),
8747            "plane on the phantom-nappe side must yield no real curve, got {}",
8748            curves.len()
8749        );
8750    }
8751
8752    #[test]
8753    fn oblique_plane_cone_parabola_on_both_single_branch() {
8754        // Plane normal at exactly 45° to the axis (= the cone half-opening) → the
8755        // plane is parallel to a generator → parabola. One unbounded branch.
8756        let cone = ConicalSurface::new(
8757            Point3::new(0.0, 0.0, 0.0),
8758            Vec3::new(0.0, 0.0, 1.0),
8759            std::f64::consts::FRAC_PI_4,
8760        )
8761        .unwrap();
8762        let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
8763        let d = n.x() * 3.0 + n.z() * 3.0; // through (3,0,3)
8764        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8765        assert_eq!(
8766            curves.len(),
8767            1,
8768            "a parabola is a single branch, got {}",
8769            curves.len()
8770        );
8771        // Bounded by r_max = 32·|e|; |e| here is O(few), so allow a wide z window.
8772        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
8773    }
8774
8775    #[test]
8776    fn oblique_plane_cone_hyperbola_real_nappe_only() {
8777        // Faithful scooplabel lip-foot geometry: a 45° cone with axis −z and
8778        // apex at (−59,−59,15.85) (a bin corner), cut by the upper ramp tread
8779        // plane n=(0,0.99518,0.09802), d=−58.36056. The plane is nearly parallel
8780        // to the axis (cos≈0.098) → plane-axis angle ≈ 5.6° < 45° → hyperbola.
8781        // The downward real nappe is hit by exactly one branch; the phantom
8782        // upward nappe (and the asymptote runaway) must NOT appear, and the arc
8783        // must stay near the apex (the plane is ~1.2 mm from it).
8784        let cone = ConicalSurface::new(
8785            Point3::new(-59.0, -59.0, 15.85),
8786            Vec3::new(0.0, 0.0, -1.0),
8787            std::f64::consts::FRAC_PI_4,
8788        )
8789        .unwrap();
8790        let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
8791        let d = -58.360_56;
8792        let cos_theta = n.dot(cone.axis()).abs();
8793        assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
8794        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
8795        // Real downward nappe only: never above the apex (z=15.85). The vertex is
8796        // ~1.2 mm from the apex, so the bounded arc stays within a few mm of it.
8797        assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
8798        // Every returned curve is sampled Points (no false Circle/Ellipse).
8799        for c in &curves {
8800            assert!(
8801                matches!(c, ExactIntersectionCurve::Points(_)),
8802                "hyperbola must be sampled Points, not a closed conic"
8803            );
8804        }
8805    }
8806
8807    /// Two spheres meet in one circle on both of them; spheres apart, one
8808    /// inside the other, or concentric of different radii meet in nothing,
8809    /// and one sphere twice has no curve.
8810    #[test]
8811    fn sphere_sphere_meets_in_a_circle_on_both() {
8812        let ball = |x: f64, y: f64, z: f64, r: f64| {
8813            SphericalSurface::new(Point3::new(x, y, z), r).unwrap()
8814        };
8815        let (a, b) = (ball(0.0, 0.0, 0.0, 2.0), ball(1.6, 0.3, 0.2, 1.5));
8816        let curves = exact_sphere_sphere(&a, &b).unwrap().unwrap();
8817        assert_eq!(curves.len(), 1);
8818        let circle = match &curves[0] {
8819            ExactIntersectionCurve::Circle(circle) => circle,
8820            other => unreachable!("expected a circle, got {other:?}"),
8821        };
8822        for k in 0..16 {
8823            let p = circle.evaluate(std::f64::consts::TAU * f64::from(k) / 16.0);
8824            assert!(((p - a.center()).length() - 2.0).abs() < 1e-12);
8825            assert!(((p - b.center()).length() - 1.5).abs() < 1e-12);
8826        }
8827        assert!(
8828            exact_sphere_sphere(&a, &ball(4.0, 0.0, 0.0, 1.5))
8829                .unwrap()
8830                .unwrap()
8831                .is_empty()
8832        );
8833        assert!(
8834            exact_sphere_sphere(&a, &ball(0.2, 0.0, 0.0, 1.0))
8835                .unwrap()
8836                .unwrap()
8837                .is_empty()
8838        );
8839        assert!(
8840            exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 1.0))
8841                .unwrap()
8842                .unwrap()
8843                .is_empty()
8844        );
8845        assert!(
8846            exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 2.0))
8847                .unwrap()
8848                .is_none()
8849        );
8850
8851        // A tiny sphere nearly bisected by a large one, in either order, and a
8852        // pair far from the origin: each meets in its small circle.
8853        let radius = |p: &SphericalSurface, q: &SphericalSurface| -> f64 {
8854            match exact_sphere_sphere(p, q).unwrap().unwrap().as_slice() {
8855                [ExactIntersectionCurve::Circle(c)] => c.radius(),
8856                other => unreachable!("expected one circle, got {other:?}"),
8857            }
8858        };
8859        let tiny = ball(2.0, 0.0, 0.0, 1e-5);
8860        assert!((radius(&a, &tiny) - 1e-5).abs() < 1e-9);
8861        assert!((radius(&tiny, &a) - 1e-5).abs() < 1e-9);
8862        let near = radius(&ball(0.0, 0.0, 0.0, 2.0), &ball(3.5, 0.0, 0.0, 1.500_001));
8863        let far = radius(
8864            &ball(1e10, 0.0, 0.0, 2.0),
8865            &ball(1e10 + 3.5, 0.0, 0.0, 1.500_001),
8866        );
8867        assert!(near > 1e-3);
8868        assert!((far - near).abs() < 1e-9 * near.max(1.0));
8869    }
8870
8871    /// Each line among `sections`, and whether it is a ray; any other
8872    /// section fails the test.
8873    #[allow(clippy::panic)]
8874    fn lines_of(sections: &[PlaneSection]) -> Vec<(Line3D, bool)> {
8875        sections
8876            .iter()
8877            .map(|s| match s {
8878                PlaneSection::Line { line, ray } => (line.clone(), *ray),
8879                other => panic!("expected a line, got {other:?}"),
8880            })
8881            .collect()
8882    }
8883
8884    /// A plane along a cylinder's axis cuts its rulings: two through the
8885    /// axis, two 2e-6 apart where it sinks a hair into the cylinder, the one
8886    /// it touches along, and none past it. `exact_plane_analytic` gives no
8887    /// curve for any of them.
8888    #[test]
8889    fn a_plane_along_a_cylinder_cuts_its_rulings() {
8890        let cyl =
8891            CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
8892                .unwrap();
8893        let y = Vec3::new(0.0, 1.0, 0.0);
8894        let surface = AnalyticSurface::Cylinder(&cyl);
8895        let on_both = |p: Point3, d: f64| {
8896            assert!((p.y() - d).abs() < 1e-12, "{p:?} off the plane y = {d}");
8897            assert!(
8898                (p.x().hypot(p.y()) - 1.0).abs() < 1e-12,
8899                "{p:?} off the cylinder"
8900            );
8901        };
8902        for (d, count) in [(0.0, 2), (1e-6_f64.cos(), 2), (1.0, 1), (1.5, 0)] {
8903            assert!(exact_plane_analytic(surface, y, d).unwrap().is_empty());
8904            let lines = lines_of(&exact_plane_section(surface, y, d).unwrap());
8905            assert_eq!(lines.len(), count, "plane y = {d}");
8906            let mut xs = Vec::new();
8907            for (line, ray) in lines {
8908                assert!(!ray);
8909                assert!(line.direction().cross(cyl.axis()).length() < 1e-12);
8910                for t in [-3.0, 0.0, 3.0] {
8911                    on_both(line.evaluate(t), d);
8912                }
8913                xs.push(line.evaluate(0.0).x());
8914            }
8915            if count == 2 {
8916                let apart = (xs[0] - xs[1]).abs();
8917                let want = 2.0 * (1.0 - d * d).sqrt();
8918                assert!(
8919                    (apart - want).abs() < 1e-9 * want.max(1e-6),
8920                    "{apart} apart"
8921                );
8922            }
8923        }
8924    }
8925
8926    /// A plane through a cone's apex cuts rays from it: two for a plane
8927    /// through the axis, one for a plane touching the cone along a ruling,
8928    /// and the apex alone for a plane missing the nappe. A plane 5e-8 off the
8929    /// apex still cuts its conic.
8930    #[test]
8931    #[allow(clippy::panic)]
8932    fn a_plane_through_a_cone_apex_cuts_its_rulings() {
8933        use std::f64::consts::FRAC_PI_4;
8934
8935        let cone = ConicalSurface::new(
8936            Point3::new(1.0, 2.0, 3.0),
8937            Vec3::new(0.0, 0.0, 1.0),
8938            FRAC_PI_4,
8939        )
8940        .unwrap();
8941        let surface = AnalyticSurface::Cone(&cone);
8942        let apex = cone.apex();
8943        let through = |n: Vec3| {
8944            let n = n.normalize().unwrap();
8945            let d = n.dot(apex - Point3::new(0.0, 0.0, 0.0));
8946            assert!(exact_plane_analytic(surface, n, d).unwrap().is_empty());
8947            (n, d, exact_plane_section(surface, n, d).unwrap())
8948        };
8949        for (n, count) in [
8950            (Vec3::new(1.0, 0.0, 0.0), 2),
8951            (Vec3::new(1.0, 0.0, -1.0), 1),
8952        ] {
8953            let (n, d, sections) = through(n);
8954            let rays = lines_of(&sections);
8955            assert_eq!(rays.len(), count, "plane normal {n:?}");
8956            for (line, ray) in rays {
8957                assert!(ray);
8958                assert!((line.evaluate(0.0) - apex).length() < 1e-12);
8959                let p = line.evaluate(2.0);
8960                assert!((n.dot(p - Point3::new(0.0, 0.0, 0.0)) - d).abs() < 1e-12);
8961                let rel = p - apex;
8962                assert!(rel.z() > 0.0, "{p:?} on the phantom nappe");
8963                assert!(
8964                    (rel.x().hypot(rel.y()) - rel.z()).abs() < 1e-12,
8965                    "{p:?} off the cone"
8966                );
8967            }
8968        }
8969        for n in [Vec3::new(0.1, 0.0, 1.0), Vec3::new(0.0, 0.0, 1.0)] {
8970            let (_, _, sections) = through(n);
8971            assert!(
8972                matches!(sections[..], [PlaneSection::Point(p)] if (p - apex).length() < 1e-12),
8973                "{sections:?}"
8974            );
8975        }
8976
8977        let upright = ConicalSurface::new(
8978            Point3::new(0.0, 0.0, 0.0),
8979            Vec3::new(0.0, 0.0, 1.0),
8980            FRAC_PI_4,
8981        )
8982        .unwrap();
8983        let n = Vec3::new((0.5 - 1e-8_f64).sqrt(), 0.0, (0.5 + 1e-8_f64).sqrt());
8984        let sections = exact_plane_section(AnalyticSurface::Cone(&upright), n, 5e-8).unwrap();
8985        let [PlaneSection::Ellipse(ellipse)] = &sections[..] else {
8986            panic!("{sections:?}");
8987        };
8988        assert!(
8989            ellipse.semi_major() > 1.0,
8990            "semi-major {}",
8991            ellipse.semi_major()
8992        );
8993    }
8994
8995    /// A plane touching a sphere meets it at the point of contact, and one a
8996    /// hair inside cuts the small circle there, however small.
8997    #[test]
8998    #[allow(clippy::panic)]
8999    fn a_plane_touching_a_sphere_meets_it_at_a_point() {
9000        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 1.0), 1.0).unwrap();
9001        let surface = AnalyticSurface::Sphere(&sphere);
9002        let z = Vec3::new(0.0, 0.0, 1.0);
9003        assert!(exact_plane_analytic(surface, z, 0.0).unwrap().is_empty());
9004        let sections = exact_plane_section(surface, z, 0.0).unwrap();
9005        assert!(
9006            matches!(sections[..], [PlaneSection::Point(p)] if p.z().abs() < 1e-15 && p.x() == 0.0),
9007            "{sections:?}"
9008        );
9009        assert!(exact_plane_section(surface, z, -1e-9).unwrap().is_empty());
9010        for height in [5e-15, 1e-12, 1e-8] {
9011            let sections = exact_plane_section(surface, z, height).unwrap();
9012            let [PlaneSection::Circle(circle)] = &sections[..] else {
9013                panic!("{sections:?}");
9014            };
9015            let want = (height * (2.0 - height)).sqrt();
9016            assert!(
9017                (circle.radius() - want).abs() < 1e-3 * want,
9018                "circle at z = {height}: radius {}, want {want}",
9019                circle.radius()
9020            );
9021            assert!((circle.center().z() - height).abs() < 1e-15);
9022        }
9023    }
9024
9025    /// The farthest any of `curves` strays from `off`, sampled densely.
9026    fn farthest(curves: &[IntersectionCurve], off: impl Fn(Point3) -> f64) -> f64 {
9027        let mut far = 0.0_f64;
9028        for ic in curves {
9029            let (t0, t1) = ic.curve.domain();
9030            for i in 0..=2000 {
9031                let t = t0 + (t1 - t0) * f64::from(i) / 2000.0;
9032                far = far.max(off(ic.curve.evaluate(t)));
9033            }
9034        }
9035        far
9036    }
9037
9038    /// A ball sitting in a bore of its own radius touches it along its
9039    /// equator, which comes back as the exact circle.
9040    #[test]
9041    fn a_ball_in_its_bore_meets_it_on_an_exact_circle() {
9042        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
9043        let bore =
9044            CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9045                .unwrap();
9046        let curves = intersect_analytic_analytic_bounded(
9047            AnalyticSurface::Sphere(&ball),
9048            AnalyticSurface::Cylinder(&bore),
9049            64,
9050            None,
9051            Some((0.0, 4.0)),
9052        )
9053        .unwrap();
9054        assert_eq!(curves.len(), 1);
9055        let far = farthest(&curves, |p| {
9056            let on_ball = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
9057            on_ball
9058                .max((p.x().hypot(p.y()) - 1.0).abs())
9059                .max(p.z().abs())
9060        });
9061        assert!(far < 1e-14, "circle strays {far:.2e}");
9062    }
9063
9064    /// Two unit balls a unit apart meet in a circle of radius √3/2, which
9065    /// comes back exact.
9066    #[test]
9067    fn overlapping_balls_meet_on_an_exact_circle() {
9068        let a = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
9069        let b = SphericalSurface::new(Point3::new(1.0, 0.0, 0.0), 1.0).unwrap();
9070        let curves = intersect_analytic_analytic_bounded(
9071            AnalyticSurface::Sphere(&a),
9072            AnalyticSurface::Sphere(&b),
9073            64,
9074            None,
9075            None,
9076        )
9077        .unwrap();
9078        assert_eq!(curves.len(), 1);
9079        let far = farthest(&curves, |p| {
9080            let on_a = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
9081            on_a.max(((p - Point3::new(1.0, 0.0, 0.0)).length() - 1.0).abs())
9082        });
9083        assert!(far < 1e-14, "circle strays {far:.2e}");
9084    }
9085
9086    /// A loop with semi-axes 3 and 1.5 in a tilted frame lies on its ellipse
9087    /// all the way round and starts at the end of its major axis.
9088    #[test]
9089    fn a_conic_loop_is_its_ellipse() {
9090        let centre = Point3::new(1.0, -2.0, 0.5);
9091        let frame = Frame3::from_normal(centre, Vec3::new(0.3, -0.4, 1.0)).unwrap();
9092        let curve = conic_loop(centre, frame.x, frame.y, 3.0, 1.5).unwrap();
9093        let (t0, t1) = curve.domain();
9094        assert!((curve.evaluate(t0) - (centre + frame.x * 3.0)).length() < 1e-15);
9095        for i in 0..=2000 {
9096            let p = curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 2000.0) - centre;
9097            let (x, y) = (p.dot(frame.x) / 3.0, p.dot(frame.y) / 1.5);
9098            assert!(
9099                (x.hypot(y) - 1.0).abs() < 1e-14,
9100                "off its ellipse by {}",
9101                x.hypot(y) - 1.0
9102            );
9103            assert!(p.dot(frame.z).abs() < 1e-14);
9104        }
9105    }
9106
9107    /// A ball sitting in a ring's hole, and a ring resting on a wider one,
9108    /// meet them along the one circle where they touch, and the bounded
9109    /// call returns it exactly.
9110    #[test]
9111    fn touching_coaxial_rings_meet_along_one_circle() {
9112        let z = Vec3::new(0.0, 0.0, 1.0);
9113        let x = Vec3::new(1.0, 0.0, 0.0);
9114        let ring =
9115            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), 3.0, 1.0, z, x)
9116                .unwrap();
9117        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
9118        let curves = intersect_analytic_analytic_bounded(
9119            AnalyticSurface::Sphere(&ball),
9120            AnalyticSurface::Torus(&ring),
9121            64,
9122            None,
9123            None,
9124        )
9125        .unwrap();
9126        assert_eq!(curves.len(), 1);
9127        let far = farthest(&curves, |p| {
9128            let q = p - Point3::new(0.0, 0.0, 0.0);
9129            let rho = q.x().hypot(q.y());
9130            let on_ring = ((rho - 3.0).hypot(q.z()) - 1.0).abs();
9131            on_ring.max((q.length() - 2.0).abs())
9132        });
9133        assert!(far < 1e-14, "circle strays {far:.2e}");
9134
9135        // Tubes of radius 1 and 0.5 on rings of radius 3 and 3.9, the second
9136        // raised 1.2: their centres lie 1.5 apart, so they touch a third of
9137        // the way along, at height 0.8 on a circle of radius 3.6.
9138        let wider =
9139            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 1.2), 3.9, 0.5, z, x)
9140                .unwrap();
9141        let touching = exact_torus_torus(&ring, &wider).unwrap().unwrap();
9142        let circles = circles_of(&touching);
9143        assert_eq!(circles.len(), 1);
9144        assert!(
9145            (circles[0].radius() - 3.6).abs() < 1e-12,
9146            "{}",
9147            circles[0].radius()
9148        );
9149        assert!((circles[0].center().z() - 0.8).abs() < 1e-12);
9150    }
9151
9152    /// Unit tubes on rings of radius 1e6 and 1e6 + 1.999 overlap by 0.001
9153    /// and cross in two circles 0.063 apart; on rings 2.001 apart they miss.
9154    /// Neither is read as a touch, at a scale where a millionth of it is
9155    /// two thousandths.
9156    #[test]
9157    fn huge_coaxial_rings_cross_or_miss_rather_than_touch() {
9158        let z = Vec3::new(0.0, 0.0, 1.0);
9159        let x = Vec3::new(1.0, 0.0, 0.0);
9160        let ring = |big: f64| {
9161            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), big, 1.0, z, x)
9162                .unwrap()
9163        };
9164        let crossing = exact_torus_torus(&ring(1e6), &ring(1_000_001.999))
9165            .unwrap()
9166            .unwrap();
9167        let circles = circles_of(&crossing);
9168        assert_eq!(circles.len(), 2);
9169        for circle in circles {
9170            let height = (1.0 - 0.9995_f64 * 0.9995).sqrt();
9171            assert!(
9172                (circle.center().z().abs() - height).abs() < 1e-9,
9173                "{}",
9174                circle.center().z()
9175            );
9176        }
9177        let apart = exact_torus_torus(&ring(1e6), &ring(1_000_002.001))
9178            .unwrap()
9179            .unwrap();
9180        assert!(apart.is_empty());
9181    }
9182
9183    /// A plane parallel to a cone's axis cuts the branch of a hyperbola on
9184    /// the cone's one nappe; planes parallel to a generator cut a parabola
9185    /// on one side of the apex and miss the cone on the other.
9186    #[test]
9187    fn a_plane_cuts_a_cones_open_conics() {
9188        let up = Vec3::new(0.0, 0.0, 1.0);
9189        let on_cone = |p: Point3, slope: f64| (p.z() - slope * p.x().hypot(p.y())).abs();
9190        let steep =
9191            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 60_f64.to_radians()).unwrap();
9192        let slope = 60_f64.to_radians().tan();
9193        let along =
9194            exact_plane_section(AnalyticSurface::Cone(&steep), Vec3::new(1.0, 0.0, 0.0), 1.0)
9195                .unwrap();
9196        let [PlaneSection::Hyperbola(h)] = along.as_slice() else {
9197            unreachable!("{along:?}")
9198        };
9199        for i in -20..=20 {
9200            let p = h.evaluate(f64::from(i) / 5.0);
9201            assert!((p.x() - 1.0).abs() < 1e-12 && p.z() > 0.0, "{p:?}");
9202            assert!(on_cone(p, slope) < 1e-12 * p.z().max(1.0), "{p:?}");
9203        }
9204        let even =
9205            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 45_f64.to_radians()).unwrap();
9206        let tilt = Vec3::new(-1.0, 0.0, 1.0) * std::f64::consts::FRAC_1_SQRT_2;
9207        let above = exact_plane_section(AnalyticSurface::Cone(&even), tilt, 1.0).unwrap();
9208        let [PlaneSection::Parabola(parabola)] = above.as_slice() else {
9209            unreachable!("{above:?}")
9210        };
9211        for i in -20..=20 {
9212            let p = parabola.evaluate(f64::from(i) / 2.0);
9213            assert!(
9214                (tilt.dot(p - Point3::new(0.0, 0.0, 0.0)) - 1.0).abs() < 1e-12,
9215                "{p:?}"
9216            );
9217            assert!(
9218                p.z() > 0.0 && on_cone(p, 1.0) < 1e-12 * p.z().max(1.0),
9219                "{p:?}"
9220            );
9221        }
9222        let below = exact_plane_section(AnalyticSurface::Cone(&even), tilt, -1.0).unwrap();
9223        assert!(below.is_empty(), "{below:?}");
9224    }
9225
9226    /// A cone so flat it rises 1e-7 from its radial plane, cut by a plane
9227    /// tilted 7e-7 off it, and a cone so narrow it opens 5e-7 off its axis,
9228    /// cut by a plane parallel to the axis, give sections that lie on the
9229    /// cone: a hyperbola for the flat one, read from its eccentricity, and
9230    /// sampled points where the formulas lose their digits.
9231    #[test]
9232    fn extreme_cones_give_sections_on_the_cone() {
9233        let up = Vec3::new(0.0, 0.0, 1.0);
9234        let apex = Point3::new(0.0, 0.0, 0.0);
9235        let holds = |cone: &ConicalSurface, q: Point3| {
9236            let w = q - apex;
9237            (w.dot(up) - cone.half_angle().sin() * w.length()).abs() <= 1e-6 * (1.0 + w.length())
9238        };
9239        let flat = ConicalSurface::new(apex, up, 1e-7).unwrap();
9240        let tilt = Vec3::new(5e-13_f64.sqrt(), 0.0, (1.0 - 5e-13_f64).sqrt());
9241        let needle = ConicalSurface::new(apex, up, FRAC_PI_2 - 5e-7).unwrap();
9242        for (cone, normal, d) in [(&flat, tilt, 1.0), (&needle, Vec3::new(1.0, 0.0, 0.0), 1.0)] {
9243            let sections = exact_plane_section(AnalyticSurface::Cone(cone), normal, d).unwrap();
9244            assert!(!sections.is_empty());
9245            for section in &sections {
9246                let points: Vec<Point3> = match section {
9247                    PlaneSection::Hyperbola(h) => {
9248                        (-4..=4).map(|i| h.evaluate(f64::from(i) / 4.0)).collect()
9249                    }
9250                    PlaneSection::Parabola(q) => {
9251                        (-4..=4).map(|i| q.evaluate(f64::from(i))).collect()
9252                    }
9253                    PlaneSection::Points(points) => points.clone(),
9254                    other => unreachable!("{other:?}"),
9255                };
9256                for q in points {
9257                    assert!(holds(cone, q), "{q:?} off the cone");
9258                }
9259            }
9260        }
9261        let flat_section = exact_plane_section(AnalyticSurface::Cone(&flat), tilt, 1.0).unwrap();
9262        assert!(matches!(
9263            flat_section.as_slice(),
9264            [PlaneSection::Hyperbola(_)]
9265        ));
9266    }
9267
9268    /// The rulings two parallel cylinders meet along, from the bounded call
9269    /// with each face's `v` range: each ruling's ends, sorted by height.
9270    fn parallel_rulings(
9271        (c1, r1, v1): (Point3, f64, (f64, f64)),
9272        (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
9273    ) -> Vec<(Point3, Point3)> {
9274        rulings_within((c1, r1, v1), (c2, r2, axis2, v2), 1e-12)
9275    }
9276
9277    /// [`parallel_rulings`] with each curve held to `tolerance` of both
9278    /// cylinders.
9279    fn rulings_within(
9280        (c1, r1, v1): (Point3, f64, (f64, f64)),
9281        (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
9282        tolerance: f64,
9283    ) -> Vec<(Point3, Point3)> {
9284        let a = CylindricalSurface::new(c1, Vec3::new(0.0, 0.0, 1.0), r1).unwrap();
9285        let b = CylindricalSurface::new(c2, axis2, r2).unwrap();
9286        let curves = intersect_analytic_analytic_bounded(
9287            AnalyticSurface::Cylinder(&a),
9288            AnalyticSurface::Cylinder(&b),
9289            32,
9290            Some(v1),
9291            Some(v2),
9292        )
9293        .unwrap();
9294        curves
9295            .iter()
9296            .map(|ic| {
9297                let (t0, t1) = ic.curve.domain();
9298                let (p, q) = (ic.curve.evaluate(t0), ic.curve.evaluate(t1));
9299                for i in 0..=100 {
9300                    let x = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 100.0);
9301                    let on_a = ((x - c1) - Vec3::new(0.0, 0.0, (x - c1).z())).length() - r1;
9302                    let w = x - c2;
9303                    let on_b = (w - axis2 * w.dot(axis2)).length() - r2;
9304                    assert!(
9305                        on_a.abs() < tolerance && on_b.abs() < tolerance,
9306                        "{x:?} off a cylinder by {on_a:.1e}, {on_b:.1e}"
9307                    );
9308                }
9309                if p.z() <= q.z() { (p, q) } else { (q, p) }
9310            })
9311            .collect()
9312    }
9313
9314    /// Rods of radius 1 with axes 1.2 apart overlap along two rulings, at
9315    /// x 0.6 and y ±0.8, over the height both faces share; the second rod's
9316    /// axis runs down, so its range counts down from its origin.
9317    #[test]
9318    fn overlapping_parallel_rods_meet_along_two_rulings() {
9319        let mut rulings = parallel_rulings(
9320            (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 4.0)),
9321            (
9322                Point3::new(1.2, 0.0, 3.0),
9323                1.0,
9324                Vec3::new(0.0, 0.0, -1.0),
9325                (0.0, 2.0),
9326            ),
9327        );
9328        rulings.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
9329        assert_eq!(rulings.len(), 2);
9330        for ((lo, hi), y) in rulings.into_iter().zip([-0.8, 0.8]) {
9331            assert!((lo - Point3::new(0.6, y, 1.0)).length() < 1e-12, "{lo:?}");
9332            assert!((hi - Point3::new(0.6, y, 3.0)).length() < 1e-12, "{hi:?}");
9333        }
9334    }
9335
9336    /// Rods touching side by side, or one inside another against its wall,
9337    /// meet along the one ruling where they touch; rods apart do not meet.
9338    #[test]
9339    fn touching_parallel_rods_meet_along_one_ruling() {
9340        let up = Vec3::new(0.0, 0.0, 1.0);
9341        let beside = parallel_rulings(
9342            (Point3::new(0.0, 0.0, 0.0), 1.0, (-2.0, 2.0)),
9343            (Point3::new(2.0, 0.0, -2.0), 1.0, up, (0.0, 4.0)),
9344        );
9345        assert_eq!(beside.len(), 1);
9346        assert!((beside[0].0 - Point3::new(1.0, 0.0, -2.0)).length() < 1e-12);
9347        assert!((beside[0].1 - Point3::new(1.0, 0.0, 2.0)).length() < 1e-12);
9348        let inside = parallel_rulings(
9349            (Point3::new(0.0, 0.0, 0.0), 2.0, (0.0, 1.0)),
9350            (Point3::new(-1.0, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
9351        );
9352        assert_eq!(inside.len(), 1);
9353        assert!((inside[0].0 - Point3::new(-2.0, 0.0, 0.0)).length() < 1e-12);
9354        let apart = parallel_rulings(
9355            (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 1.0)),
9356            (Point3::new(2.5, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
9357        );
9358        assert!(apart.is_empty());
9359    }
9360
9361    /// Rods whose axes lean 1e-5 apart drift 1e-3 over a span of 100, so
9362    /// the rulings defer to the next solver there; over a span of 0.001
9363    /// they drift 1e-8 and keep their two rulings.
9364    #[test]
9365    fn rods_leaning_apart_keep_rulings_only_over_a_short_span() {
9366        let up = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9367            .unwrap();
9368        let lean = Vec3::new(1e-5_f64.sin(), 0.0, 1e-5_f64.cos());
9369        let leaning = CylindricalSurface::new(Point3::new(1.2, 0.0, 0.0), lean, 1.0).unwrap();
9370        let span = |h: f64| parallel_cylinders(&up, &leaning, Some((0.0, h)), Some((0.0, h)));
9371        assert!(span(100.0).unwrap().is_none());
9372        assert_eq!(span(0.001).unwrap().map(|r| r.len()), Some(2));
9373    }
9374
9375    /// Huge rods a short stretch long still meet along both rulings, and
9376    /// rods of radius 100 whose axes lie 3e-7 short of touching meet along
9377    /// two rulings 0.011 apart, not the one where they would touch.
9378    #[test]
9379    fn parallel_rods_keep_short_and_close_rulings() {
9380        let up = Vec3::new(0.0, 0.0, 1.0);
9381        let huge = rulings_within(
9382            (Point3::new(0.0, 0.0, 0.0), 1e6, (0.0, 0.001)),
9383            (Point3::new(1.2e6, 0.0, 0.0), 1e6, up, (0.0, 0.001)),
9384            1e-9,
9385        );
9386        assert_eq!(huge.len(), 2);
9387        assert!(
9388            huge.iter()
9389                .all(|(lo, hi)| ((*hi - *lo).length() - 0.001).abs() < 1e-12)
9390        );
9391        let mut close = rulings_within(
9392            (Point3::new(0.0, 0.0, 0.0), 100.0, (0.0, 1.0)),
9393            (Point3::new(199.999_999_7, 0.0, 0.0), 100.0, up, (0.0, 1.0)),
9394            1e-9,
9395        );
9396        assert_eq!(close.len(), 2);
9397        close.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
9398        let apart = close[1].0.y() - close[0].0.y();
9399        assert!((apart - 0.010_954).abs() < 1e-5, "{apart}");
9400    }
9401
9402    /// How far `p` lies off `cone` (either nappe), and its `v` there.
9403    fn off_cone(cone: &ConicalSurface, p: Point3) -> (f64, f64) {
9404        let q = p - cone.apex();
9405        let (along, s) = (q.dot(cone.axis()), cone.half_angle().sin());
9406        ((along.abs() - s * q.length()).abs(), along / s)
9407    }
9408
9409    /// Cones sharing an apex, their axes 40° apart and each opening 20°
9410    /// from its axis, touch along the one ruling between the axes, which
9411    /// runs where both faces hold it.
9412    #[test]
9413    fn cones_sharing_an_apex_touch_along_one_ruling() {
9414        let apex = Point3::new(1.0, 2.0, 3.0);
9415        let a = 20.0_f64.to_radians();
9416        let half = std::f64::consts::FRAC_PI_2 - a;
9417        let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
9418        let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
9419        let curves = intersect_analytic_analytic_bounded(
9420            AnalyticSurface::Cone(&c1),
9421            AnalyticSurface::Cone(&c2),
9422            64,
9423            Some((0.2, 3.0)),
9424            Some((0.5, 4.0)),
9425        )
9426        .unwrap();
9427        assert_eq!(curves.len(), 1);
9428        let curve = &curves[0].curve;
9429        let (t0, t1) = curve.domain();
9430        let x = Vec3::new(1.0, 0.0, 0.0);
9431        assert!((curve.evaluate(t0) - (apex + x * 0.5)).length() < 1e-12);
9432        assert!((curve.evaluate(t1) - (apex + x * 3.0)).length() < 1e-12);
9433    }
9434
9435    /// Cones sharing an apex, their axes 20° apart and each opening 30°,
9436    /// cross along two rulings; faces reaching past the apex hold each on
9437    /// both sides of it, in two segments that end there.
9438    #[test]
9439    fn cones_sharing_an_apex_cross_along_two_rulings() {
9440        let apex = Point3::new(-1.0, 0.5, 2.0);
9441        let b = 20.0_f64.to_radians();
9442        let half = 60.0_f64.to_radians();
9443        let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9444        let c2 = ConicalSurface::new(apex, Vec3::new(b.sin(), 0.0, b.cos()), half).unwrap();
9445        for (range, pieces) in [((0.5, 2.0), 2), ((-2.0, 2.0), 4)] {
9446            let curves = intersect_analytic_analytic_bounded(
9447                AnalyticSurface::Cone(&c1),
9448                AnalyticSurface::Cone(&c2),
9449                64,
9450                Some(range),
9451                Some(range),
9452            )
9453            .unwrap();
9454            assert_eq!(curves.len(), pieces, "{range:?}");
9455            for ic in &curves {
9456                let (t0, t1) = ic.curve.domain();
9457                for k in 0..=20 {
9458                    let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 20.0);
9459                    for cone in [&c1, &c2] {
9460                        let (off, v) = off_cone(cone, p);
9461                        assert!(off < 1e-12, "{range:?}: off a cone by {off:.2e}");
9462                        assert!(v > range.0 - 1e-12 && v < range.1 + 1e-12);
9463                    }
9464                }
9465                if pieces == 4 {
9466                    let ends = [ic.curve.evaluate(t0), ic.curve.evaluate(t1)];
9467                    assert!(ends.iter().any(|&e| (e - apex).length() < 1e-12));
9468                }
9469                for point in &ic.points {
9470                    let (on1, on2) = (point.param1, point.param2);
9471                    assert!((c1.evaluate(on1.0, on1.1) - point.point).length() < 1e-9);
9472                    assert!((c2.evaluate(on2.0, on2.1) - point.point).length() < 1e-9);
9473                }
9474            }
9475        }
9476    }
9477
9478    /// Axes 1e-8 apart in angle leave a ruling's part across them to
9479    /// rounding, and cones touching within rounding along a ruling leave
9480    /// how far apart their rulings may be 1e6 out to it: neither is solved
9481    /// here.
9482    #[test]
9483    fn cones_sharing_an_apex_defer_what_rounding_cannot_settle() {
9484        let apex = Point3::new(0.0, 0.0, 0.0);
9485        let half = 60.0_f64.to_radians();
9486        let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9487        let c2 = ConicalSurface::new(apex, Vec3::new(1e-8_f64.sin(), 0.0, 1e-8_f64.cos()), half)
9488            .unwrap();
9489        let near = Some((0.5, 2.0));
9490        assert!(shared_apex_cones(&c1, &c2, near, near).unwrap().is_none());
9491        let a = 20.0_f64.to_radians();
9492        let half = std::f64::consts::FRAC_PI_2 - a;
9493        let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
9494        let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
9495        let far = Some((0.5, 1e6));
9496        assert!(shared_apex_cones(&c1, &c2, far, far).unwrap().is_none());
9497    }
9498
9499    /// Perpendicular cones opening 1e-15 short of touching cross along two
9500    /// rulings, which part by about 0.09 a million out: two segments.
9501    #[test]
9502    fn cones_sharing_an_apex_just_short_of_touching_cross_in_two_rulings() {
9503        let apex = Point3::new(0.0, 0.0, 0.0);
9504        let half = std::f64::consts::FRAC_PI_4 - 1e-15;
9505        let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
9506        let c2 = ConicalSurface::new(apex, Vec3::new(1.0, 0.0, 0.0), half).unwrap();
9507        let range = Some((0.5, 1e6));
9508        let curves = shared_apex_cones(&c1, &c2, range, range).unwrap().unwrap();
9509        assert_eq!(curves.len(), 2);
9510        let ends: Vec<Point3> = curves
9511            .iter()
9512            .map(|ic| ic.curve.evaluate(ic.curve.domain().1))
9513            .collect();
9514        assert!((ends[0] - ends[1]).length() > 0.05);
9515    }
9516
9517    /// A ball off a ring's axis touches it at one point from outside the
9518    /// tube, from inside it, or holding the whole ring, and that point is
9519    /// all they share. A ball reaching 1e-6 further cuts the tube in a small
9520    /// loop, which is left to the section's closed form, and one centred on
9521    /// the core circle with the tube's radius meets it along the meridian
9522    /// circle through its centre.
9523    #[test]
9524    fn a_ball_off_a_rings_axis_touches_it_at_one_point() {
9525        let o = Point3::new(1.0, 2.0, 3.0);
9526        let ring = ToroidalSurface::new(o, 3.0, 1.0).unwrap();
9527        let (s, c) = 30.0_f64.to_radians().sin_cos();
9528        let (out, up) = (Vec3::new(c, s, 0.0), Vec3::new(0.0, 0.0, 1.0));
9529        let on_ring = |p: Point3| {
9530            let q = p - o;
9531            ((q.x().hypot(q.y()) - 3.0).hypot(q.z()) - 1.0).abs()
9532        };
9533        let balls = [
9534            (o + out * 5.0, 1.0),
9535            (o + out * 3.2 + up * 0.1, 1.0 - 0.05_f64.sqrt()),
9536            (o + out + up * 0.5, 1.0 + 16.25_f64.sqrt()),
9537        ];
9538        let mut touches = Vec::new();
9539        for (centre, radius) in balls {
9540            let ball = SphericalSurface::new(centre, radius).unwrap();
9541            let exacts = exact_sphere_torus(&ball, &ring).unwrap().unwrap();
9542            let p = match exacts.as_slice() {
9543                [ExactIntersectionCurve::Points(points)] => points[0],
9544                _ => unreachable!("one touching point"),
9545            };
9546            assert!(on_ring(p) < 1e-12 && ((p - centre).length() - radius).abs() < 1e-12);
9547            let curves = intersect_analytic_analytic(
9548                AnalyticSurface::Sphere(&ball),
9549                AnalyticSurface::Torus(&ring),
9550                16,
9551            )
9552            .unwrap();
9553            assert_eq!(curves.len(), 1);
9554            let (t0, t1) = curves[0].curve.domain();
9555            assert!((curves[0].curve.evaluate(t0) - p).length() < 1e-15);
9556            assert!((curves[0].curve.evaluate(t1) - p).length() < 1e-15);
9557            touches.push(p);
9558        }
9559        assert!((touches[0] - (o + out * 4.0)).length() < 1e-12);
9560        let past = SphericalSurface::new(o + out * 5.0, 1.0 + 1e-6).unwrap();
9561        assert!(exact_sphere_torus(&past, &ring).unwrap().is_none());
9562        let on_core = SphericalSurface::new(o + out * 3.0, 1.0).unwrap();
9563        let meridian = exact_sphere_torus(&on_core, &ring).unwrap().unwrap();
9564        let [ExactIntersectionCurve::Circle(circle)] = meridian.as_slice() else {
9565            unreachable!("one meridian circle");
9566        };
9567        assert!((circle.center() - (o + out * 3.0)).length() < 1e-12);
9568        assert!((circle.radius() - 1.0).abs() < 1e-12);
9569    }
9570
9571    /// A taper pin through a rod turned `spin` about its axis, as
9572    /// `a_taper_pin_through_a_turned_rod_traces_both_loops` builds it: the pin,
9573    /// its faces' `v` range, and its apex's `y`.
9574    fn taper_pin_and_rod(
9575        flip: bool,
9576        spin: f64,
9577    ) -> (ConicalSurface, (f64, f64), f64, CylindricalSurface) {
9578        let slope = 0.7_f64 / 16.0;
9579        let half = (1.0 / slope).atan();
9580        let (apex_y, axis_y) = if flip {
9581            (-8.0 - 0.8 / slope, 1.0)
9582        } else {
9583            (-8.0 + 1.5 / slope, -1.0)
9584        };
9585        let pin = ConicalSurface::new(
9586            Point3::new(0.0, apex_y, 10.0),
9587            Vec3::new(0.0, axis_y, 0.0),
9588            half,
9589        )
9590        .unwrap();
9591        let (h0, h1) = ((-8.0 - apex_y).abs(), (8.0 - apex_y).abs());
9592        let v_pin = (h0.min(h1) / half.sin(), h0.max(h1) / half.sin());
9593        let rod = CylindricalSurface::with_ref_dir(
9594            Point3::new(0.0, 0.0, 0.0),
9595            Vec3::new(0.0, 0.0, 1.0),
9596            5.0,
9597            Vec3::new(spin.cos(), spin.sin(), 0.0),
9598        )
9599        .unwrap();
9600        (pin, v_pin, apex_y, rod)
9601    }
9602
9603    /// The overlap of the taper pin's and the rod's faces, a little wide.
9604    const TAPER_PIN_REGION: Aabb3 = Aabb3 {
9605        min: Point3::new(-1.6, -5.1, 8.4),
9606        max: Point3::new(1.6, 5.1, 11.6),
9607    };
9608
9609    /// The farthest that `n` points of `curve` lie off a surface, by `off`.
9610    fn farthest_along(curve: &NurbsCurve, n: u32, off: impl Fn(Point3) -> f64) -> f64 {
9611        let (t0, t1) = curve.domain();
9612        (0..=n)
9613            .map(|k| off(curve.evaluate((t1 - t0).madd(f64::from(k) / f64::from(n), t0))))
9614            .fold(0.0, f64::max)
9615    }
9616
9617    /// The general marcher traces a taper pin's two loops on a rod (which the
9618    /// rulings trace, so the marcher is called on its own here), a cone and a
9619    /// tilted tube, and a cone's band across a wide cylinder. Its cubic fits
9620    /// stay within the linear tolerance of both surfaces between their
9621    /// points, not only at them: fits through the marched points alone lay
9622    /// 2e-5 to 1.1e-4 off both, with the points 0.08 to 0.31 apart.
9623    #[test]
9624    fn marched_cone_cylinder_sections_stay_on_both_between_their_points() {
9625        let lin = Tolerance::new().linear;
9626        for flip in [false, true] {
9627            for spin in [0.0_f64, 0.3, 0.9, 1.4, 2.0, 2.6, 3.0, 3.6] {
9628                let (pin, v_pin, apex_y, rod) = taper_pin_and_rod(flip, spin);
9629                let half = pin.half_angle();
9630                let off_pin = |p: Point3| {
9631                    let rho = p.x().hypot(p.z() - 10.0);
9632                    let h = (p.y() - apex_y).abs();
9633                    rho.madd(half.sin(), -h * half.cos()).abs()
9634                };
9635                let off_rod = |p: Point3| (p.x().hypot(p.y()) - 5.0).abs();
9636                for rod_first in [true, false] {
9637                    let (a, b, va, vb) = if rod_first {
9638                        (
9639                            AnalyticSurface::Cylinder(&rod),
9640                            AnalyticSurface::Cone(&pin),
9641                            Some((0.0, 20.0)),
9642                            Some(v_pin),
9643                        )
9644                    } else {
9645                        (
9646                            AnalyticSurface::Cone(&pin),
9647                            AnalyticSurface::Cylinder(&rod),
9648                            Some(v_pin),
9649                            Some((0.0, 20.0)),
9650                        )
9651                    };
9652                    let curves =
9653                        marched_sections(a, b, 32, va, vb, Some(TAPER_PIN_REGION)).unwrap();
9654                    assert_eq!(curves.len(), 2, "spin {spin} flip {flip}: loops");
9655                    for c in &curves {
9656                        let worst = farthest_along(&c.curve, 4000, |p| off_pin(p).max(off_rod(p)));
9657                        assert!(worst <= lin, "spin {spin} flip {flip}: off by {worst:.2e}");
9658                    }
9659                }
9660            }
9661        }
9662
9663        let (cone, tube) = cone_and_tilted_tube();
9664        let curves = intersect_analytic_analytic_bounded(
9665            AnalyticSurface::Cone(&cone),
9666            AnalyticSurface::Cylinder(&tube),
9667            32,
9668            Some((0.5, 4.0)),
9669            Some((-5.0, 5.0)),
9670        )
9671        .unwrap();
9672        assert!(!curves.is_empty());
9673        let (sin, cos) = cone.half_angle().sin_cos();
9674        let axis = tube.axis();
9675        for c in &curves {
9676            let worst = farthest_along(&c.curve, 4000, |p| {
9677                let on_cone = p.x().hypot(p.y()).madd(sin, -p.z().abs() * cos).abs();
9678                let w = p - tube.origin();
9679                let on_tube = ((w - axis * axis.dot(w)).length() - 0.1).abs();
9680                on_cone.max(on_tube)
9681            });
9682            assert!(worst <= lin, "tilted tube: off by {worst:.2e}");
9683        }
9684
9685        let half_angle = 14.0_f64.atan2(10.0);
9686        let cone = ConicalSurface::new(
9687            Point3::new(0.0, 0.0, 273.2),
9688            Vec3::new(0.0, 0.0, -1.0),
9689            half_angle,
9690        )
9691        .unwrap();
9692        let cyl = CylindricalSurface::new(
9693            Point3::new(0.0, -50.0, 215.0),
9694            Vec3::new(0.0, 1.0, 0.0),
9695            60.0,
9696        )
9697        .unwrap();
9698        let curves = intersect_analytic_analytic_in_region(
9699            AnalyticSurface::Cone(&cone),
9700            AnalyticSurface::Cylinder(&cyl),
9701            32,
9702            Some((81.2 / half_angle.sin(), 95.2 / half_angle.sin())),
9703            Some((10.0, 90.0)),
9704            Aabb3 {
9705                min: Point3::new(-59.98, -40.0, 178.0),
9706                max: Point3::new(-47.23, 40.0, 192.0),
9707            },
9708        )
9709        .unwrap();
9710        assert_eq!(curves.len(), 2);
9711        let (sin, cos) = half_angle.sin_cos();
9712        for c in &curves {
9713            let worst = farthest_along(&c.curve, 4000, |p| {
9714                let on_cone = p.x().hypot(p.y()).madd(sin, -(273.2 - p.z()) * cos).abs();
9715                let on_cyl = (p.x().hypot(p.z() - 215.0) - 60.0).abs();
9716                on_cone.max(on_cyl)
9717            });
9718            assert!(worst <= lin, "band: off by {worst:.2e}");
9719        }
9720    }
9721
9722    /// Between the taper pin's two holes, the pin's side and the rod's wall
9723    /// pass closest without meeting. Projections from one to the other
9724    /// settle there, both normals along the gap: with the rod turned 0.9, at
9725    /// (-2.50, -3.35, 9.88), 0.82 off the rod. The march from that seed never
9726    /// came back to it: it ran 1001 points and ended 2.6 from where it began.
9727    /// The seed now moves onto both surfaces by Newton steps before the march,
9728    /// or is dropped where they cannot take it there, and every loop closes
9729    /// on itself.
9730    #[test]
9731    fn a_seed_where_two_walls_pass_closest_starts_no_march() {
9732        let (pin, v_pin, _, rod) = taper_pin_and_rod(false, 0.9);
9733        let (a, b) = (AnalyticSurface::Cylinder(&rod), AnalyticSurface::Cone(&pin));
9734        let stalled = Point3::new(
9735            -2.503_835_657_485_280_5,
9736            -3.349_109_255_073_426,
9737            9.881_016_348_226_973,
9738        );
9739        let off_rod = |p: Point3| section_fit::Carrier::distance(&a, p).unwrap().0;
9740        let off_pin = |p: Point3| section_fit::Carrier::distance(&b, p).unwrap().0;
9741        assert!(off_rod(stalled).abs() > 0.8);
9742        let on = settle_on_section(&a, &b, stalled).unwrap();
9743        let (d_rod, d_pin) = (off_rod(on), off_pin(on));
9744        assert!(
9745            d_rod.abs() < 1e-12 && d_pin.abs() < 1e-12,
9746            "{d_rod:.1e}, {d_pin:.1e}"
9747        );
9748
9749        let curves = marched_sections(
9750            a,
9751            b,
9752            32,
9753            Some((0.0, 20.0)),
9754            Some(v_pin),
9755            Some(TAPER_PIN_REGION),
9756        )
9757        .unwrap();
9758        assert_eq!(curves.len(), 2);
9759        for c in &curves {
9760            let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
9761            assert!((first - last).length() < 1e-9, "{first:?} to {last:?}");
9762            assert!(c.points.len() < 400, "{} points", c.points.len());
9763        }
9764
9765        // Where both normals lie along the gap, no Newton step crosses it.
9766        let ball = SphericalSurface::new(Point3::new(3.0, 0.0, 0.0), 1.0).unwrap();
9767        let post =
9768            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
9769                .unwrap();
9770        let gap = Point3::new(1.5, 0.0, 0.0);
9771        assert!(
9772            settle_on_section(
9773                &AnalyticSurface::Sphere(&ball),
9774                &AnalyticSurface::Cylinder(&post),
9775                gap
9776            )
9777            .is_none()
9778        );
9779    }
9780
9781    /// Two rods whose axes cross square, as far apart as their radii add up
9782    /// to, touch at one point and cross nowhere. A seed settles onto that
9783    /// point, where no direction along a section is defined: the march from
9784    /// it wandered up to 1.3e-5 off both rods, and its fit was refused. The
9785    /// seed is now dropped, and no section is traced.
9786    #[test]
9787    fn rods_that_only_touch_trace_no_section() {
9788        let wall =
9789            CylindricalSurface::new(Point3::new(1.1, 1.1, 1.2), Vec3::new(0.0, 0.0, 1.0), 2.55)
9790                .unwrap();
9791        let air =
9792            CylindricalSurface::new(Point3::new(-3.9, 1.1, 4.7), Vec3::new(0.0, 1.0, 0.0), 2.45)
9793                .unwrap();
9794        let (a, b) = (
9795            AnalyticSurface::Cylinder(&wall),
9796            AnalyticSurface::Cylinder(&air),
9797        );
9798        let touch = Point3::new(-1.45, 1.1, 4.7);
9799        assert!(!crosses_at(&a, &b, touch));
9800        let region = Aabb3 {
9801            min: Point3::new(-2.1625, 0.3875, 1.5375),
9802            max: Point3::new(-0.7375, 1.8125, 5.4125),
9803        };
9804        let curves = marched_sections(
9805            a,
9806            b,
9807            32,
9808            Some((1.05, 12.45)),
9809            Some((0.0, 30.9)),
9810            Some(region),
9811        )
9812        .unwrap();
9813        assert!(curves.is_empty(), "{} sections", curves.len());
9814    }
9815
9816    /// The distance from the double cone `cone`, by the ruling on `p`'s side
9817    /// of the axis on `p`'s nappe.
9818    fn off_double_cone(cone: &ConicalSurface, p: Point3) -> f64 {
9819        let w = p - cone.apex();
9820        let h = cone.axis().dot(w);
9821        let rho = (w - cone.axis() * h).length();
9822        let (sin, cos) = cone.half_angle().sin_cos();
9823        rho.madd(sin, -h.abs() * cos).abs()
9824    }
9825
9826    /// Two cones of one axis direction, a unit apart, bounded on their
9827    /// negative nappes between `z = -1` and `z = -1/3`, meet in one loop
9828    /// there (through `(0.125, sqrt(15)/8, -0.5)`). The marcher traces it
9829    /// either way round, and the fit stays on both nappes between its
9830    /// points. Read by the ruling of the positive nappe, the shared point lay
9831    /// 0.707 off the first cone, and no seed settled on the loop.
9832    #[test]
9833    fn negative_nappe_sections_are_marched_on_both_cones() {
9834        let up = Vec3::new(0.0, 0.0, 1.0);
9835        let wide = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, std::f64::consts::FRAC_PI_4)
9836            .unwrap();
9837        let narrow = ConicalSurface::new(Point3::new(1.0, 0.0, 0.0), up, 0.5_f64.atan()).unwrap();
9838        let shared = Point3::new(0.125, 15.0_f64.sqrt() / 8.0, -0.5);
9839        for cone in [&wide, &narrow] {
9840            let (off, _) =
9841                section_fit::Carrier::distance(&AnalyticSurface::Cone(cone), shared).unwrap();
9842            assert!(off.abs() < 1e-12, "{off}");
9843        }
9844        let (r1, r2) = (std::f64::consts::SQRT_2, 5.0_f64.sqrt());
9845        let (v_wide, v_narrow) = ((-r1, -r1 / 3.0), (-r2, -r2 / 3.0));
9846        for wide_first in [true, false] {
9847            let (a, b, va, vb) = if wide_first {
9848                (
9849                    AnalyticSurface::Cone(&wide),
9850                    AnalyticSurface::Cone(&narrow),
9851                    v_wide,
9852                    v_narrow,
9853                )
9854            } else {
9855                (
9856                    AnalyticSurface::Cone(&narrow),
9857                    AnalyticSurface::Cone(&wide),
9858                    v_narrow,
9859                    v_wide,
9860                )
9861            };
9862            let curves = marched_sections(a, b, 32, Some(va), Some(vb), None).unwrap();
9863            assert!(!curves.is_empty(), "wide first {wide_first}: no section");
9864            for c in &curves {
9865                let worst = farthest_along(&c.curve, 4000, |p| {
9866                    off_double_cone(&wide, p).max(off_double_cone(&narrow, p))
9867                });
9868                assert!(worst <= 1e-7, "wide first {wide_first}: off by {worst:.2e}");
9869                let below = farthest_along(&c.curve, 4000, |p| (p.z() + 1.0 / 3.0).max(0.0));
9870                assert!(
9871                    below < 1e-9,
9872                    "wide first {wide_first}: above z = -1/3 by {below:.2e}"
9873                );
9874            }
9875        }
9876    }
9877
9878    /// A 45-degree cone holds its negative ruling from (1, 0, -1) to
9879    /// (4, 0, -4), and so does a rod of radius 1 along it. The bound on the
9880    /// cone reads that ruling as on it, and the fit through its points is
9881    /// the ruling; read by the positive nappe, its factor was negative and
9882    /// no span could be bounded. A span through the apex, where the factor
9883    /// vanishes, has no bound.
9884    #[test]
9885    fn a_fit_along_a_negative_ruling_is_bounded() {
9886        let cone = ConicalSurface::new(
9887            Point3::new(0.0, 0.0, 0.0),
9888            Vec3::new(0.0, 0.0, 1.0),
9889            std::f64::consts::FRAC_PI_4,
9890        )
9891        .unwrap();
9892        let along = Vec3::new(1.0, 0.0, -1.0) * std::f64::consts::FRAC_1_SQRT_2;
9893        let rod = CylindricalSurface::new(Point3::new(0.0, 1.0, 0.0), along, 1.0).unwrap();
9894        let (a, b) = (
9895            AnalyticSurface::Cone(&cone),
9896            AnalyticSurface::Cylinder(&rod),
9897        );
9898        let ruling: Vec<Point3> = (1..=4)
9899            .map(|k| Point3::new(f64::from(k), 0.0, -f64::from(k)))
9900            .collect();
9901        let ctrl = [ruling[0], ruling[1], ruling[2], ruling[3]];
9902        let bound = section_fit::Carrier::bound(&a, &ctrl).unwrap();
9903        assert!(bound < 1e-12, "{bound:.2e}");
9904        let (curve, points) = fit_section(&a, &b, &ruling, 1e-7).unwrap();
9905        assert_eq!(points.len(), 4);
9906        let worst = farthest_along(&curve, 1000, |p| p.y().abs().max((p.x() + p.z()).abs()));
9907        assert!(worst < 1e-12, "{worst:.2e}");
9908        let through_apex = [
9909            Point3::new(-1.0, 0.0, 1.0),
9910            Point3::new(-1.0 / 3.0, 0.0, 1.0 / 3.0),
9911            Point3::new(1.0 / 3.0, 0.0, -1.0 / 3.0),
9912            Point3::new(1.0, 0.0, -1.0),
9913        ];
9914        assert!(section_fit::Carrier::bound(&a, &through_apex).is_none());
9915    }
9916
9917    /// Two rods, `x^2 + y^2 = 1` and `(x - 3)^2 + z^2 = 4`, touch at
9918    /// (1, 0, 0) alone, where a seed near it settles on no crossing. Moved
9919    /// 1e6 along x, a seed settled 3.1e-4 from the touch, where both
9920    /// distances lay below the rounding of the coordinates and the normals
9921    /// 1.5e-4 from parallel, and a march started there; moved 1e12, the
9922    /// spacing of one coordinate let a point one float step from the touch
9923    /// read as a crossing. The marcher now works near the origin, so the
9924    /// rods moved along each axis trace no section, as they do unmoved.
9925    #[test]
9926    fn a_touch_far_from_the_origin_settles_as_one_near_it_does() {
9927        for o in [
9928            Vec3::new(0.0, 0.0, 0.0),
9929            Vec3::new(1e6, 0.0, 0.0),
9930            Vec3::new(1e12, 0.0, 0.0),
9931            Vec3::new(0.0, 1e12, 0.0),
9932            Vec3::new(0.0, 0.0, 1e12),
9933        ] {
9934            let post = CylindricalSurface::new(
9935                Point3::new(0.0, 0.0, 0.0) + o,
9936                Vec3::new(0.0, 0.0, 1.0),
9937                1.0,
9938            )
9939            .unwrap();
9940            let beam = CylindricalSurface::new(
9941                Point3::new(3.0, 0.0, 0.0) + o,
9942                Vec3::new(0.0, 1.0, 0.0),
9943                2.0,
9944            )
9945            .unwrap();
9946            let (a, b) = (
9947                AnalyticSurface::Cylinder(&post),
9948                AnalyticSurface::Cylinder(&beam),
9949            );
9950            if o.length() == 0.0 {
9951                let settled = settle_on_section(&a, &b, Point3::new(1.0, 0.01, 0.01));
9952                assert!(
9953                    settled.is_none_or(|p| !crosses_at(&a, &b, p)),
9954                    "settles on a crossing at {settled:?}"
9955                );
9956            }
9957            let region = Aabb3 {
9958                min: Point3::new(0.5, -0.5, -0.5) + o,
9959                max: Point3::new(1.5, 0.5, 0.5) + o,
9960            };
9961            let curves =
9962                marched_sections(a, b, 32, Some((-1.0, 1.0)), Some((-1.0, 1.0)), Some(region))
9963                    .unwrap();
9964            assert!(curves.is_empty(), "moved {o:?}: {} sections", curves.len());
9965        }
9966    }
9967
9968    /// A cone opening 0.01 or 0.001 either side of its axis, or lying that
9969    /// far off its radial plane, meets a rod on its axis in one circle. The
9970    /// fit through points of that circle is bounded on both surfaces within
9971    /// the linear tolerance: the cone's factor, `|h| cos + rho sin`, keeps a
9972    /// lower bound however slender or flat the cone.
9973    #[test]
9974    fn fits_on_slender_and_flat_cones_are_bounded() {
9975        use std::f64::consts::FRAC_PI_2;
9976        for half in [FRAC_PI_2 - 0.01, FRAC_PI_2 - 0.001, 0.01, 0.001] {
9977            let cone =
9978                ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), half)
9979                    .unwrap();
9980            let v = 10.0;
9981            let (rho, h) = (v * half.cos(), v * half.sin());
9982            let rod =
9983                CylindricalSurface::new(Point3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 1.0), rho)
9984                    .unwrap();
9985            let (a, b) = (
9986                AnalyticSurface::Cone(&cone),
9987                AnalyticSurface::Cylinder(&rod),
9988            );
9989            let circle: Vec<Point3> = (0..=12)
9990                .map(|k| {
9991                    let t = TAU * f64::from(k) / 12.0;
9992                    Point3::new(rho * t.cos(), rho * t.sin(), h)
9993                })
9994                .collect();
9995            let (curve, points) = fit_section(&a, &b, &circle, 1e-7).unwrap();
9996            let worst = farthest_along(&curve, 4000, |p| {
9997                off_double_cone(&cone, p).max((p.x().hypot(p.y()) - rho).abs())
9998            });
9999            assert!(worst <= 1e-7, "half {half}: off by {worst:.2e}");
10000            assert!(points.len() < 2000, "half {half}: {} points", points.len());
10001        }
10002    }
10003
10004    /// The ring of radii 4 and 1.5 and a rod of radius 0.6 along y through
10005    /// (0.5, y, 1), moved 1e6 along each axis, meet in the two loops they
10006    /// meet in unmoved, each within the linear tolerance of both surfaces.
10007    /// Moved 1e9, where the floats' spacing (1.2e-7) leaves no room for the
10008    /// tolerance once a curve is moved back, the traced section is refused
10009    /// before any fit, not dropped; its fit ran 7 passes over 1.4 s first.
10010    #[test]
10011    fn a_section_far_from_the_origin_is_traced_as_near_it() {
10012        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10013        let run = |o: Vec3| {
10014            let torus = ring.translated(o);
10015            let rod = CylindricalSurface::new(
10016                Point3::new(0.5, 0.0, 1.0) + o,
10017                Vec3::new(0.0, 1.0, 0.0),
10018                0.6,
10019            )
10020            .unwrap();
10021            let region = Aabb3 {
10022                min: Point3::new(-0.1, -5.5, 0.4) + o,
10023                max: Point3::new(1.1, 5.5, 1.5) + o,
10024            };
10025            intersect_analytic_analytic_in_region(
10026                AnalyticSurface::Cylinder(&rod),
10027                AnalyticSurface::Torus(&torus),
10028                32,
10029                Some((-10.0, 10.0)),
10030                None,
10031                region,
10032            )
10033        };
10034        for o in [
10035            Vec3::new(0.0, 0.0, 0.0),
10036            Vec3::new(1e6, 0.0, 0.0),
10037            Vec3::new(0.0, 1e6, 0.0),
10038            Vec3::new(0.0, 0.0, 1e6),
10039        ] {
10040            let curves = run(o).unwrap();
10041            assert_eq!(curves.len(), 2, "moved {o:?}");
10042            for c in &curves {
10043                let worst = farthest_along(&c.curve, 4000, |p| {
10044                    let q = p - o;
10045                    let on_torus = ((q.x().hypot(q.y()) - 4.0).hypot(q.z()) - 1.5).abs();
10046                    let on_rod = ((q.x() - 0.5).hypot(q.z() - 1.0) - 0.6).abs();
10047                    on_torus.max(on_rod)
10048                });
10049                assert!(worst <= 1e-7, "moved {o:?}: off by {worst:.2e}");
10050            }
10051        }
10052        for o in [
10053            Vec3::new(1e9, 0.0, 0.0),
10054            Vec3::new(0.0, 1e9, 0.0),
10055            Vec3::new(0.0, 0.0, 1e9),
10056        ] {
10057            assert!(
10058                matches!(run(o), Err(MathError::ConvergenceFailure { iterations: 0 })),
10059                "moved {o:?}: not refused before its fit"
10060            );
10061        }
10062    }
10063
10064    /// A cylinder's frame can sit anywhere along its axis. The rods
10065    /// `x^2 + y^2 = 1` and `(x - 3)^2 + z^2 = 4`, with their frames 1e6 along
10066    /// their axes, touch at (1, 0, 0) alone, as with their frames beside it:
10067    /// a seed near the touch settled 1.55e-4 from it and read as a crossing,
10068    /// and the marcher refused the pair. Now the seed settles on no crossing
10069    /// and no section is traced. The ring and rod of the truth audit, the
10070    /// rod's frame 1e6 along its axis, meet in the loops they meet in with
10071    /// the frame beside them.
10072    #[test]
10073    fn frames_far_along_a_rods_axis_read_as_near_ones() {
10074        let post =
10075            CylindricalSurface::new(Point3::new(0.0, 0.0, -1e6), Vec3::new(0.0, 0.0, 1.0), 1.0)
10076                .unwrap();
10077        let beam =
10078            CylindricalSurface::new(Point3::new(3.0, -1e6, 0.0), Vec3::new(0.0, 1.0, 0.0), 2.0)
10079                .unwrap();
10080        let (a, b) = (
10081            AnalyticSurface::Cylinder(&post),
10082            AnalyticSurface::Cylinder(&beam),
10083        );
10084        let settled = settle_on_section(&a, &b, Point3::new(1.0, 0.01, 0.01));
10085        assert!(
10086            settled.is_none_or(|p| !crosses_at(&a, &b, p)),
10087            "settles on a crossing at {settled:?}"
10088        );
10089        let region = Aabb3 {
10090            min: Point3::new(0.5, -0.5, -0.5),
10091            max: Point3::new(1.5, 0.5, 0.5),
10092        };
10093        let far = Some((1e6 - 1.0, 1e6 + 1.0));
10094        let curves = marched_sections(a, b, 32, far, far, Some(region)).unwrap();
10095        assert!(curves.is_empty(), "{} sections", curves.len());
10096
10097        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10098        let boxes = |frame: f64| {
10099            let rod = CylindricalSurface::new(
10100                Point3::new(0.5, -frame, 1.0),
10101                Vec3::new(0.0, 1.0, 0.0),
10102                0.6,
10103            )
10104            .unwrap();
10105            let region = Aabb3 {
10106                min: Point3::new(-0.1, -5.5, 0.4),
10107                max: Point3::new(1.1, 5.5, 1.5),
10108            };
10109            let curves = intersect_analytic_analytic_in_region(
10110                AnalyticSurface::Cylinder(&rod),
10111                AnalyticSurface::Torus(&ring),
10112                32,
10113                Some((frame - 10.0, frame + 10.0)),
10114                None,
10115                region,
10116            )
10117            .unwrap();
10118            let mut boxes: Vec<Aabb3> = curves
10119                .iter()
10120                .map(|c| {
10121                    let worst = farthest_along(&c.curve, 4000, |p| {
10122                        let on_torus = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
10123                        let on_rod = ((p.x() - 0.5).hypot(p.z() - 1.0) - 0.6).abs();
10124                        on_torus.max(on_rod)
10125                    });
10126                    assert!(worst <= 1e-7, "frame {frame}: off by {worst:.2e}");
10127                    Aabb3::try_from_points(c.points.iter().map(|ip| ip.point)).unwrap()
10128                })
10129                .collect();
10130            boxes.sort_by(|p, q| p.min.y().total_cmp(&q.min.y()));
10131            boxes
10132        };
10133        let (near, far) = (boxes(0.0), boxes(1e6));
10134        assert_eq!(near.len(), 2);
10135        assert_eq!(far.len(), near.len());
10136        for (n, f) in near.iter().zip(&far) {
10137            assert!((n.min - f.min).length() < 1e-6 && (n.max - f.max).length() < 1e-6);
10138        }
10139    }
10140
10141    /// `a + b` as a float and its rounding error.
10142    fn two_sum(a: f64, b: f64) -> (f64, f64) {
10143        let s = a + b;
10144        let back = s - a;
10145        (s, (a - (s - back)) + (b - back))
10146    }
10147
10148    /// `a b` as a float and its rounding error, by Dekker's split.
10149    fn two_prod(a: f64, b: f64) -> (f64, f64) {
10150        let split = |v: f64| {
10151            let c = 134_217_729.0 * v;
10152            let hi = c - (c - v);
10153            (hi, v - hi)
10154        };
10155        let p = a * b;
10156        let ((ah, al), (bh, bl)) = (split(a), split(b));
10157        (p, ((ah * bh - p) + ah * bl + al * bh) + al * bl)
10158    }
10159
10160    /// How far `p` lies from the line through `o` along `a`, in
10161    /// double-length arithmetic, so a far `o` costs no digits of the answer
10162    /// (nor does `a` being a float step from unit length).
10163    fn off_line(o: Point3, a: Vec3, p: Point3) -> f64 {
10164        let w = [
10165            two_sum(p.x(), -o.x()),
10166            two_sum(p.y(), -o.y()),
10167            two_sum(p.z(), -o.z()),
10168        ];
10169        let a = [a.x(), a.y(), a.z()];
10170        // A sum of products `a_i y_i` with each `y_i` double-length.
10171        let dot = |y: &[(f64, f64); 3]| {
10172            let (mut hi, mut lo) = (0.0, 0.0);
10173            for (ai, (yh, yl)) in a.iter().zip(y) {
10174                let (prod, prod_err) = two_prod(*ai, *yh);
10175                let (sum, sum_err) = two_sum(hi, prod);
10176                hi = sum;
10177                lo += sum_err + prod_err + ai * yl;
10178            }
10179            two_sum(hi, lo)
10180        };
10181        let (aw, aw_err) = dot(&w);
10182        let (aa, aa_err) = dot(&a.map(|x| (x, 0.0)));
10183        // `s = aw / aa` to double length: its float, then the remainder
10184        // over `aa`.
10185        let s = aw / aa;
10186        let (sa, sa_err) = two_prod(s, aa);
10187        let rest = ((aw - sa) - sa_err) + aw_err - s * aa_err;
10188        let s_err = rest / aa;
10189        let across = a.iter().zip(w).map(|(ai, (hi, lo))| {
10190            let (prod, prod_err) = two_prod(*ai, s);
10191            let (diff, diff_err) = two_sum(hi, -prod);
10192            diff + (diff_err + lo - prod_err - ai * s_err)
10193        });
10194        across.map(|c| c * c).sum::<f64>().sqrt()
10195    }
10196
10197    /// A rod of radius 0.6 on an axis along (0.3, 0.4, 0.5) through the
10198    /// centre circle of the ring of radii 4 and 1.5 at (4, 0, 0), its frame
10199    /// 1e12 along the axis. Moved to the region by plain sums, such a frame
10200    /// landed 2.1e-5 off the axis, and a fit certified against the moved rod
10201    /// need not lie within 1e-7 of the input one. The frame now lands within
10202    /// 4e-15 of the axis, and both loops lie within 1e-7 of the input rod
10203    /// (measured in double-length arithmetic) and of the ring.
10204    #[test]
10205    fn a_tilted_rod_framed_far_along_its_axis_is_traced_on_it() {
10206        let along = Vec3::new(0.3, 0.4, 0.5);
10207        let through = Point3::new(4.0, 0.0, 0.0);
10208        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
10209        let near_rod = CylindricalSurface::new(through, along, 0.6).unwrap();
10210        let axis = near_rod.axis();
10211        let far = through + axis * 1e12;
10212        let rod = CylindricalSurface::new(far, along, 0.6).unwrap();
10213        let anchor = Point3::new(4.0, 0.0, 0.0);
10214        let (moved, dv, error) = Moved::new(&AnalyticSurface::Cylinder(&rod), anchor);
10215        let AnalyticSurface::Cylinder(moved) = moved.surface() else {
10216            unreachable!("a rod moves to a rod");
10217        };
10218        let foot = moved.origin() + (anchor - Point3::new(0.0, 0.0, 0.0));
10219        let off = off_line(rod.origin(), rod.axis(), foot);
10220        assert!(
10221            off <= error && error < 1e-14,
10222            "the frame lies {off:.2e} off the axis"
10223        );
10224        assert!((dv + 1e12).abs() < 1.0, "v moved by {dv}");
10225
10226        let region = Aabb3 {
10227            min: Point3::new(2.0, -2.0, -2.0),
10228            max: Point3::new(6.0, 2.0, 2.0),
10229        };
10230        let sweep = (1e12 - 10.0, 1e12 + 10.0);
10231        let result = marched_sections(
10232            AnalyticSurface::Cylinder(&rod),
10233            AnalyticSurface::Torus(&ring),
10234            32,
10235            Some((-sweep.1, -sweep.0)),
10236            None,
10237            Some(region),
10238        );
10239        let curves = result.unwrap();
10240        assert_eq!(curves.len(), 2);
10241        {
10242            for c in &curves {
10243                let worst = farthest_along(&c.curve, 4000, |p| {
10244                    let on_rod = (off_line(rod.origin(), rod.axis(), p) - 0.6).abs();
10245                    let on_ring = ((p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5).abs();
10246                    on_rod.max(on_ring)
10247                });
10248                assert!(worst <= 1e-7, "off by {worst:.2e}");
10249            }
10250        }
10251    }
10252
10253    /// Each surface's closed-form second derivative of its distance along a
10254    /// direction matches the distance's central second difference, at points
10255    /// on and near the surface, along and across it.
10256    #[test]
10257    fn each_surface_bends_as_its_distance_does() {
10258        use section_fit::Carrier;
10259        let cyl =
10260            CylindricalSurface::new(Point3::new(0.3, -0.2, 0.5), Vec3::new(0.2, 0.3, 1.0), 0.7)
10261                .unwrap();
10262        let ball = SphericalSurface::new(Point3::new(-0.4, 0.1, 0.2), 1.3).unwrap();
10263        let cone = ConicalSurface::new(Point3::new(0.1, 0.2, -0.3), Vec3::new(-0.3, 0.1, 1.0), 0.6)
10264            .unwrap();
10265        let ring = ToroidalSurface::new(Point3::new(0.2, -0.1, 0.1), 2.0, 0.6).unwrap();
10266        let surfaces = [
10267            AnalyticSurface::Cylinder(&cyl),
10268            AnalyticSurface::Sphere(&ball),
10269            AnalyticSurface::Cone(&cone),
10270            AnalyticSurface::Torus(&ring),
10271        ];
10272        let directions = [
10273            Vec3::new(1.0, 0.0, 0.0),
10274            Vec3::new(0.0, 1.0, 0.0),
10275            Vec3::new(0.0, 0.0, 1.0),
10276            Vec3::new(0.6, -0.48, 0.64),
10277        ];
10278        let (_, _, _, cone_v) = surface_closures(&AnalyticSurface::Cone(&cone));
10279        for (k, s) in surfaces.iter().enumerate() {
10280            let (surf, norm, _, (v0, v1)) = surface_closures(s);
10281            let (v0, v1) = if matches!(s, AnalyticSurface::Cone(_)) {
10282                (cone_v.0.max(0.5), cone_v.1)
10283            } else {
10284                (v0, v1)
10285            };
10286            for (u, v) in [(0.3, 0.25), (1.9, 0.5), (4.4, 0.75)] {
10287                let v = (v1 - v0).madd(v, v0);
10288                for off in [0.0, 0.05, -0.05] {
10289                    let p = surf(u, v) + norm(u, v) * off;
10290                    let f = |q: Point3| s.distance(q).unwrap().0;
10291                    for d in directions {
10292                        let d = d * (1.0 / d.length());
10293                        let h = 1e-4;
10294                        let second = (f(p + d * h) - 2.0 * f(p) + f(p - d * h)) / (h * h);
10295                        let exact = s.bend(p, d).unwrap();
10296                        assert!(
10297                            (second - exact).abs() <= 1e-5 * (1.0 + exact.abs()),
10298                            "surface {k} at {p:?} along {d:?}: {exact} against {second}"
10299                        );
10300                    }
10301                }
10302            }
10303        }
10304    }
10305
10306    /// A cone's distance holds `-|h| cos`, which has no second derivative
10307    /// across the apex's plane. Off the axis on that plane, within the
10308    /// rounding of `h`, no curvature is read, along the axis or across it,
10309    /// so neither a march station nor a search for a touch is built there:
10310    /// both find nothing, and no touch is read. Just off the plane each
10311    /// curvature reads again.
10312    #[test]
10313    fn a_cone_reads_no_curvature_on_its_apex_plane() {
10314        use section_fit::Carrier;
10315        let axis = Vec3::new(0.0, 0.0, 1.0);
10316        let cone = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), axis, 0.7).unwrap();
10317        let rod =
10318            CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
10319                .unwrap();
10320        let (a, b) = (
10321            AnalyticSurface::Cone(&cone),
10322            AnalyticSurface::Cylinder(&rod),
10323        );
10324        let across = Vec3::new(1.0, 0.0, 0.0);
10325        for on in [
10326            Point3::new(2.0, 0.0, 0.0),
10327            Point3::new(2.0, 0.0, 1e-17),
10328            Point3::new(2.0, 0.0, -1e-17),
10329        ] {
10330            assert!(a.distance(on).is_some());
10331            assert!(a.bend(on, axis).is_none(), "{on:?} along the axis");
10332            assert!(a.bend(on, across).is_none(), "{on:?} across");
10333            assert!(station(&a, &b, on, axis).is_none(), "{on:?} station");
10334            assert!(singular_point(&a, &b, on, 1.0).is_none(), "{on:?} touch");
10335        }
10336        for off in [Point3::new(2.0, 0.0, 1e-3), Point3::new(2.0, 0.0, -1e-3)] {
10337            assert!(a.bend(off, axis).is_some(), "{off:?} along the axis");
10338            assert!(a.bend(off, across).is_some(), "{off:?} across");
10339        }
10340    }
10341
10342    /// Upright, turned and moved, and mirrored through a slanted plane.
10343    fn three_poses() -> [crate::mat::Mat4; 3] {
10344        use crate::mat::Mat4;
10345        [
10346            Mat4::identity(),
10347            Mat4::translation(-3.7, 5.5, 14.0) * Mat4::rotation_z(0.7) * Mat4::rotation_x(-0.9),
10348            Mat4::scale(-1.0, 1.0, 1.0) * Mat4::rotation_y(0.4),
10349        ]
10350    }
10351
10352    /// A cone with its apex at the origin and its axis along z, and a rod of
10353    /// radius `r` along x through `(0, 0, z0)`, both moved by `pose`; and
10354    /// the points of their section where the rod's angle about its axis is
10355    /// `k / n` of a turn, for `k` below `n`, each moved by `pose`.
10356    fn posed_cone_and_rod(
10357        pose: &crate::mat::Mat4,
10358        half: f64,
10359        z0: f64,
10360        r: f64,
10361        n: u32,
10362    ) -> (ConicalSurface, CylindricalSurface, Vec<Point3>) {
10363        let o = Point3::new(0.0, 0.0, 0.0);
10364        let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10365        let cone =
10366            ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half).unwrap();
10367        let rod = CylindricalSurface::new(
10368            pose.mul_point(Point3::new(0.0, 0.0, z0)),
10369            along(Vec3::new(1.0, 0.0, 0.0)),
10370            r,
10371        )
10372        .unwrap();
10373        let mut truth = Vec::new();
10374        for k in 0..n {
10375            let phi = TAU * f64::from(k) / f64::from(n);
10376            let (y, z) = (r * phi.sin(), r.madd(-phi.cos(), z0));
10377            let rho = z.abs() / half.tan();
10378            let x2 = rho.madd(rho, -y * y);
10379            if x2 >= 0.0 {
10380                for x in [x2.sqrt(), -x2.sqrt()] {
10381                    truth.push(pose.mul_point(Point3::new(x, y, z)));
10382                }
10383            }
10384        }
10385        (cone, rod, truth)
10386    }
10387
10388    /// A cone lying 0.01 off its radial plane meets a rod of radius 0.05 at
10389    /// height 0.1 in two loops 10 long and 0.1 across, which turn at radius
10390    /// 5e-4 at their ends. A cone opening 0.01 about its axis meets rods
10391    /// across it in loops 0.2 to 0.6 long. The march's steps of up to 1.5
10392    /// passed the turns and left points 2.4e-2 off the rod, and its closure,
10393    /// five steps from the seed, joined a loop's far side: each fit was
10394    /// refused, but for the rod of radius 0.2, whose second loop was lost
10395    /// with no error. The march now follows each loop round once, in every
10396    /// pose and either way round: each fit lies within the linear tolerance
10397    /// of both surfaces, closes, and passes within 1e-5 of every point of
10398    /// the section.
10399    #[test]
10400    fn thin_loops_on_flat_and_slender_cones_are_marched_round() {
10401        use std::f64::consts::FRAC_PI_2;
10402        let lin = Tolerance::new().linear;
10403        let cases = [
10404            (0.01, 0.1, 0.05),
10405            (FRAC_PI_2 - 0.01, 3.0, 0.05),
10406            (FRAC_PI_2 - 0.01, 10.0, 0.05),
10407            (FRAC_PI_2 - 0.01, 10.0, 0.2),
10408        ];
10409        for (half, z0, r) in cases {
10410            for (p, pose) in three_poses().iter().enumerate() {
10411                let (cone, rod, truth) = posed_cone_and_rod(pose, half, z0, r, 360);
10412                for cone_first in [true, false] {
10413                    let label =
10414                        format!("half {half} z0 {z0} r {r} pose {p} cone first {cone_first}");
10415                    let (a, b, va, vb) = if cone_first {
10416                        (
10417                            AnalyticSurface::Cone(&cone),
10418                            AnalyticSurface::Cylinder(&rod),
10419                            (1.0, 20.0),
10420                            (-20.0, 20.0),
10421                        )
10422                    } else {
10423                        (
10424                            AnalyticSurface::Cylinder(&rod),
10425                            AnalyticSurface::Cone(&cone),
10426                            (-20.0, 20.0),
10427                            (1.0, 20.0),
10428                        )
10429                    };
10430                    let result = marched_sections(a, b, 32, Some(va), Some(vb), None);
10431                    assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10432                    let curves = result.unwrap();
10433                    assert_eq!(curves.len(), 2, "{label}: loops");
10434                    let off_rod = |p: Point3| {
10435                        let (w, ax) = (p - rod.origin(), rod.axis());
10436                        ((w - ax * ax.dot(w)).length() - r).abs()
10437                    };
10438                    for c in &curves {
10439                        let worst = farthest_along(&c.curve, 4000, |p| {
10440                            off_double_cone(&cone, p).max(off_rod(p))
10441                        });
10442                        assert!(worst <= lin, "{label}: off by {worst:.2e}");
10443                        let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
10444                        assert!((first - last).length() < 1e-9, "{label}: open");
10445                    }
10446                    for &t in &truth {
10447                        let near = curves
10448                            .iter()
10449                            .map(|c| {
10450                                crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10451                                    .unwrap()
10452                                    .distance
10453                            })
10454                            .fold(f64::INFINITY, f64::min);
10455                        assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10456                    }
10457                }
10458            }
10459        }
10460    }
10461
10462    /// A cone lying 0.001 off its radial plane, its apex at the origin, and
10463    /// a rod of radius 0.05 along x through the apex meet in four curves
10464    /// along the rod, two on each nappe, a nappe's 1e-4 from the other's.
10465    /// With both nappes in the cone's patch, a march step hopped to the other
10466    /// nappe and the fit was refused; with each step kept on its nappe, a
10467    /// seed on one nappe still lay within the estimated gap of a curve
10468    /// marched on the other and started no march, and two of the four curves
10469    /// were lost with no error. A seed now joins a marched curve only on its
10470    /// nappe and where Newton steps from the curve's chord reach it within
10471    /// the linear tolerance.
10472    #[test]
10473    fn sections_on_both_nappes_of_a_flat_cone_are_each_marched() {
10474        let (half, r) = (0.001_f64, 0.05_f64);
10475        let lin = Tolerance::new().linear;
10476        let t2 = half.tan() * half.tan();
10477        for (k, pose) in three_poses().iter().enumerate() {
10478            let o = Point3::new(0.0, 0.0, 0.0);
10479            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10480            let cone =
10481                ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half)
10482                    .unwrap();
10483            let rod =
10484                CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(1.0, 0.0, 0.0)), r)
10485                    .unwrap();
10486            let mut truth = Vec::new();
10487            for j in 0..=90 {
10488                let x = 0.9 * (f64::from(j) / 45.0 - 1.0);
10489                let z = (t2 * x.madd(x, r * r) / (1.0 + t2)).sqrt();
10490                let y = z.madd(-z, r * r).sqrt();
10491                for (sy, sz) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] {
10492                    truth.push(pose.mul_point(Point3::new(x, sy * y, sz * z)));
10493                }
10494            }
10495            let off_rod = |p: Point3| {
10496                let (w, ax) = (p - rod.origin(), rod.axis());
10497                ((w - ax * ax.dot(w)).length() - r).abs()
10498            };
10499            for cone_first in [true, false] {
10500                let label = format!("pose {k} cone first {cone_first}");
10501                let (a, b) = if cone_first {
10502                    (
10503                        AnalyticSurface::Cone(&cone),
10504                        AnalyticSurface::Cylinder(&rod),
10505                    )
10506                } else {
10507                    (
10508                        AnalyticSurface::Cylinder(&rod),
10509                        AnalyticSurface::Cone(&cone),
10510                    )
10511                };
10512                let result = marched_sections(a, b, 32, Some((-1.0, 1.0)), Some((-1.0, 1.0)), None);
10513                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10514                let curves = result.unwrap();
10515                assert_eq!(curves.len(), 4, "{label}: curves");
10516                for c in &curves {
10517                    let worst = farthest_along(&c.curve, 4000, |p| {
10518                        off_double_cone(&cone, p).max(off_rod(p))
10519                    });
10520                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
10521                }
10522                for &t in &truth {
10523                    let near = curves
10524                        .iter()
10525                        .map(|c| {
10526                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10527                                .unwrap()
10528                                .distance
10529                        })
10530                        .fold(f64::INFINITY, f64::min);
10531                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10532                }
10533            }
10534        }
10535    }
10536
10537    /// A cone lying 2e-6 off its radial plane, its apex at the origin, and a
10538    /// rod of radius 0.1 along x through the apex cross at a shallow angle,
10539    /// 2e-6, in a curve whose two sides along the rod meet near
10540    /// (50000, 0, 0.1), where it turns at a radius of about 2e-7. The march
10541    /// cannot step round that turn and stops there, the normals 2e-6 from
10542    /// parallel but no point near where they are parallel: each march ended
10543    /// there with a lone point, which was dropped, and the section was lost
10544    /// with no error. The march now refuses it, or traces all of it.
10545    #[test]
10546    fn a_shallow_crossing_too_tight_to_march_is_refused_not_dropped() {
10547        let (half, r) = (2e-6_f64, 0.1_f64);
10548        let t2 = half.tan() * half.tan();
10549        for (k, pose) in three_poses().iter().enumerate() {
10550            let o = Point3::new(0.0, 0.0, 0.0);
10551            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10552            let cone =
10553                ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), half)
10554                    .unwrap();
10555            let rod =
10556                CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(1.0, 0.0, 0.0)), r)
10557                    .unwrap();
10558            let mut truth = Vec::new();
10559            for j in 0..=100 {
10560                let x = 40_000.0 + 99.9 * f64::from(j);
10561                let z = (t2 * x.madd(x, r * r) / (1.0 + t2)).sqrt();
10562                if z < r {
10563                    let y = z.madd(-z, r * r).sqrt();
10564                    for sy in [1.0, -1.0] {
10565                        truth.push(pose.mul_point(Point3::new(x, sy * y, z)));
10566                    }
10567                }
10568            }
10569            for cone_first in [true, false] {
10570                let label = format!("pose {k} cone first {cone_first}");
10571                let (a, b) = if cone_first {
10572                    (
10573                        AnalyticSurface::Cone(&cone),
10574                        AnalyticSurface::Cylinder(&rod),
10575                    )
10576                } else {
10577                    (
10578                        AnalyticSurface::Cylinder(&rod),
10579                        AnalyticSurface::Cone(&cone),
10580                    )
10581                };
10582                let range = Some((40_000.0, 60_000.0));
10583                let Ok(curves) = marched_sections(a, b, 32, range, range, None) else {
10584                    continue;
10585                };
10586                for &t in &truth {
10587                    let near = curves
10588                        .iter()
10589                        .map(|c| {
10590                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10591                                .unwrap()
10592                                .distance
10593                        })
10594                        .fold(f64::INFINITY, f64::min);
10595                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10596                }
10597            }
10598        }
10599    }
10600
10601    /// A ball of radius 2 at the origin and a rod of radius 1 along z
10602    /// through (1, 0, 0) touch at (2, 0, 0), where their section, two lobes,
10603    /// crosses itself. The march steps through that node, where its steps
10604    /// grow faster than the gap to the other lobe shrinks; a curve that
10605    /// stops instead stops on the node. Either way the curves cover both
10606    /// lobes, in every pose and either way round.
10607    #[test]
10608    fn a_section_that_crosses_itself_is_traced_through_the_node() {
10609        let lin = Tolerance::new().linear;
10610        for (k, pose) in three_poses().iter().enumerate() {
10611            let o = Point3::new(0.0, 0.0, 0.0);
10612            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10613            let ball = SphericalSurface::new(pose.mul_point(o), 2.0).unwrap();
10614            let rod = CylindricalSurface::new(
10615                pose.mul_point(Point3::new(1.0, 0.0, 0.0)),
10616                along(Vec3::new(0.0, 0.0, 1.0)),
10617                1.0,
10618            )
10619            .unwrap();
10620            let node = pose.mul_point(Point3::new(2.0, 0.0, 0.0));
10621            let mut truth = Vec::new();
10622            for j in 1..360 {
10623                let t = TAU * f64::from(j) / 360.0;
10624                let z = 2.0 * (0.5 * t).sin().abs();
10625                for sz in [1.0, -1.0] {
10626                    truth.push(pose.mul_point(Point3::new(1.0 + t.cos(), t.sin(), sz * z)));
10627                }
10628            }
10629            let off_ball = |p: Point3| ((p - pose.mul_point(o)).length() - 2.0).abs();
10630            let off_rod = |p: Point3| {
10631                let (w, ax) = (p - rod.origin(), rod.axis());
10632                ((w - ax * ax.dot(w)).length() - 1.0).abs()
10633            };
10634            for ball_first in [true, false] {
10635                let label = format!("pose {k} ball first {ball_first}");
10636                let (a, b, va, vb) = if ball_first {
10637                    (
10638                        AnalyticSurface::Sphere(&ball),
10639                        AnalyticSurface::Cylinder(&rod),
10640                        None,
10641                        Some((-3.0, 3.0)),
10642                    )
10643                } else {
10644                    (
10645                        AnalyticSurface::Cylinder(&rod),
10646                        AnalyticSurface::Sphere(&ball),
10647                        Some((-3.0, 3.0)),
10648                        None,
10649                    )
10650                };
10651                let result = marched_sections(a, b, 32, va, vb, None);
10652                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10653                let curves = result.unwrap();
10654                assert!(!curves.is_empty(), "{label}: no section");
10655                for c in &curves {
10656                    let worst = farthest_along(&c.curve, 4000, |p| off_ball(p).max(off_rod(p)));
10657                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
10658                    let (t0, t1) = c.curve.domain();
10659                    let (first, last) = (c.curve.evaluate(t0), c.curve.evaluate(t1));
10660                    if (first - last).length() > lin {
10661                        for end in [first, last] {
10662                            let miss = (end - node).length();
10663                            assert!(miss <= lin, "{label}: an end lies {miss:.1e} from the node");
10664                        }
10665                    }
10666                }
10667                for &t in &truth {
10668                    let near = curves
10669                        .iter()
10670                        .map(|c| {
10671                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10672                                .unwrap()
10673                                .distance
10674                        })
10675                        .fold(f64::INFINITY, f64::min);
10676                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10677                }
10678            }
10679        }
10680    }
10681
10682    /// A rod of radius 3 along z up to z = 30 and the ring of radii 20 and 3
10683    /// about the y axis through (20, 0, 30), a leg and the bend on its top,
10684    /// touch along the circle z = 30 of the rod, and cross below it in a
10685    /// curve that runs from (0, 3, 30) round through (3, 0, 14.5) to
10686    /// (0, -3, 30): there the touch is of higher order, and the march stops
10687    /// short of it. The curve ends where Gauss-Newton steps find both
10688    /// surfaces passing with their normals parallel to rounding, within
10689    /// 1e-5 of the touch, which rounding leaves no closer to fix, in every
10690    /// pose and either way round.
10691    #[test]
10692    fn a_marched_branch_that_runs_into_a_touch_ends_on_it() {
10693        let lin = Tolerance::new().linear;
10694        for (k, pose) in three_poses().iter().enumerate() {
10695            let o = Point3::new(0.0, 0.0, 0.0);
10696            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10697            let leg =
10698                CylindricalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), 3.0)
10699                    .unwrap();
10700            let bend = ToroidalSurface::with_axis(
10701                pose.mul_point(Point3::new(20.0, 0.0, 30.0)),
10702                20.0,
10703                3.0,
10704                along(Vec3::new(0.0, 1.0, 0.0)),
10705            )
10706            .unwrap();
10707            let touches = [
10708                pose.mul_point(Point3::new(0.0, 3.0, 30.0)),
10709                pose.mul_point(Point3::new(0.0, -3.0, 30.0)),
10710            ];
10711            let mut truth = Vec::new();
10712            for j in 1..=120 {
10713                let x = 3.0 * f64::from(j) / 120.0;
10714                let z = 30.0 - (80.0 * x).sqrt();
10715                let y = x.madd(-x, 9.0).max(0.0).sqrt();
10716                for sy in [1.0, -1.0] {
10717                    truth.push(pose.mul_point(Point3::new(x, sy * y, z)));
10718                }
10719            }
10720            let back = pose.inverse().unwrap();
10721            let off_leg = |p: Point3| {
10722                let (w, ax) = (p - leg.origin(), leg.axis());
10723                ((w - ax * ax.dot(w)).length() - 3.0).abs()
10724            };
10725            let off_bend = |p: Point3| {
10726                let q = back.mul_point(p);
10727                (((q.x() - 20.0).hypot(q.z() - 30.0) - 20.0).hypot(q.y()) - 3.0).abs()
10728            };
10729            for leg_first in [true, false] {
10730                let label = format!("pose {k} leg first {leg_first}");
10731                let (a, b, va, vb) = if leg_first {
10732                    (
10733                        AnalyticSurface::Cylinder(&leg),
10734                        AnalyticSurface::Torus(&bend),
10735                        Some((0.0, 30.0)),
10736                        None,
10737                    )
10738                } else {
10739                    (
10740                        AnalyticSurface::Torus(&bend),
10741                        AnalyticSurface::Cylinder(&leg),
10742                        None,
10743                        Some((0.0, 30.0)),
10744                    )
10745                };
10746                let result = marched_sections(a, b, 32, va, vb, None);
10747                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10748                let curves = result.unwrap();
10749                assert_eq!(curves.len(), 1, "{label}: curves");
10750                let c = &curves[0];
10751                let worst = farthest_along(&c.curve, 4000, |p| off_leg(p).max(off_bend(p)));
10752                assert!(worst <= lin, "{label}: off by {worst:.2e}");
10753                let (t0, t1) = c.curve.domain();
10754                for end in [c.curve.evaluate(t0), c.curve.evaluate(t1)] {
10755                    let miss = touches
10756                        .iter()
10757                        .map(|&t| (end - t).length())
10758                        .fold(f64::INFINITY, f64::min);
10759                    assert!(
10760                        miss <= 1e-5,
10761                        "{label}: an end lies {miss:.1e} from the touch"
10762                    );
10763                }
10764                for &t in &truth {
10765                    let near = crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10766                        .unwrap()
10767                        .distance;
10768                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10769                }
10770            }
10771        }
10772    }
10773
10774    /// A cone opening a quarter turn about z, its apex at the origin, and a
10775    /// ball of radius 0.1 about the apex meet in two circles, one on each
10776    /// nappe. With the cone's patch from v = -0.5 to 31.5 in a grid of 32,
10777    /// the only cells near the ball have their middles on the apex, the
10778    /// ball's centre, where the ball's distance has no gradient: they were
10779    /// dropped as holding no section, no cell of the cone was kept, and the
10780    /// pair traced nothing. A cell whose distance cannot be read may hold the
10781    /// section and is kept, so the ball's cells near it are read too.
10782    #[test]
10783    fn cells_centred_on_a_balls_centre_are_kept() {
10784        use std::f64::consts::FRAC_PI_4;
10785        let lin = Tolerance::new().linear;
10786        let (radius, h) = (0.1_f64, 0.1 * FRAC_PI_4.sin());
10787        let rho = 0.1 * FRAC_PI_4.cos();
10788        for (k, pose) in three_poses().iter().enumerate() {
10789            let o = Point3::new(0.0, 0.0, 0.0);
10790            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10791            let cone = ConicalSurface::new(
10792                pose.mul_point(o),
10793                along(Vec3::new(0.0, 0.0, 1.0)),
10794                FRAC_PI_4,
10795            )
10796            .unwrap();
10797            let ball = SphericalSurface::new(pose.mul_point(o), radius).unwrap();
10798            let mut truth = Vec::new();
10799            for j in 0..72 {
10800                let t = TAU * f64::from(j) / 72.0;
10801                for z in [h, -h] {
10802                    truth.push(pose.mul_point(Point3::new(rho * t.cos(), rho * t.sin(), z)));
10803                }
10804            }
10805            let off_ball = |p: Point3| ((p - pose.mul_point(o)).length() - radius).abs();
10806            for cone_first in [true, false] {
10807                let label = format!("pose {k} cone first {cone_first}");
10808                let (a, b, va, vb) = if cone_first {
10809                    (
10810                        AnalyticSurface::Cone(&cone),
10811                        AnalyticSurface::Sphere(&ball),
10812                        Some((-0.5, 31.5)),
10813                        None,
10814                    )
10815                } else {
10816                    (
10817                        AnalyticSurface::Sphere(&ball),
10818                        AnalyticSurface::Cone(&cone),
10819                        None,
10820                        Some((-0.5, 31.5)),
10821                    )
10822                };
10823                let result = marched_sections(a, b, 32, va, vb, None);
10824                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
10825                let curves = result.unwrap();
10826                assert_eq!(curves.len(), 2, "{label}: circles");
10827                for c in &curves {
10828                    let worst = farthest_along(&c.curve, 4000, |p| {
10829                        off_double_cone(&cone, p).max(off_ball(p))
10830                    });
10831                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
10832                    let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
10833                    assert!((first - last).length() < 1e-9, "{label}: open");
10834                }
10835                for &t in &truth {
10836                    let near = curves
10837                        .iter()
10838                        .map(|c| {
10839                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10840                                .unwrap()
10841                                .distance
10842                        })
10843                        .fold(f64::INFINITY, f64::min);
10844                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10845                }
10846            }
10847        }
10848    }
10849
10850    /// A cone lying 1e-14 off its radial plane, its apex at the origin, and a
10851    /// rod of radius 1 along z through (3, 0, 0) cross square to each other
10852    /// in a circle. Every point of the cone lies within 64 float steps of its
10853    /// apex's plane, where its curvature was not read: each seed on the
10854    /// crossing found no station and was dropped, and the pair traced
10855    /// nothing with no error. A seed on a crossing whose curvature cannot be
10856    /// read now refuses the section. The pair refuses or traces the circle,
10857    /// in three poses and either way round, and never returns empty.
10858    #[test]
10859    fn a_crossing_on_a_nearly_flat_cone_is_traced_or_refused() {
10860        let lin = Tolerance::new().linear;
10861        for (k, pose) in three_poses().iter().enumerate() {
10862            let o = Point3::new(0.0, 0.0, 0.0);
10863            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10864            let cone =
10865                ConicalSurface::new(pose.mul_point(o), along(Vec3::new(0.0, 0.0, 1.0)), 1e-14)
10866                    .unwrap();
10867            let rod = CylindricalSurface::new(
10868                pose.mul_point(Point3::new(3.0, 0.0, 0.0)),
10869                along(Vec3::new(0.0, 0.0, 1.0)),
10870                1.0,
10871            )
10872            .unwrap();
10873            let truth: Vec<Point3> = (0..72)
10874                .map(|j| {
10875                    let t = TAU * f64::from(j) / 72.0;
10876                    let (x, y) = (3.0 + t.cos(), t.sin());
10877                    pose.mul_point(Point3::new(x, y, 1e-14_f64.tan() * x.hypot(y)))
10878                })
10879                .collect();
10880            let off_rod = |p: Point3| {
10881                let (w, ax) = (p - rod.origin(), rod.axis());
10882                ((w - ax * ax.dot(w)).length() - 1.0).abs()
10883            };
10884            for cone_first in [true, false] {
10885                let label = format!("pose {k} cone first {cone_first}");
10886                let (a, b, va, vb) = if cone_first {
10887                    (
10888                        AnalyticSurface::Cone(&cone),
10889                        AnalyticSurface::Cylinder(&rod),
10890                        Some((1.0, 5.0)),
10891                        Some((-1.0, 1.0)),
10892                    )
10893                } else {
10894                    (
10895                        AnalyticSurface::Cylinder(&rod),
10896                        AnalyticSurface::Cone(&cone),
10897                        Some((-1.0, 1.0)),
10898                        Some((1.0, 5.0)),
10899                    )
10900                };
10901                let Ok(curves) = marched_sections(a, b, 32, va, vb, None) else {
10902                    continue;
10903                };
10904                assert!(!curves.is_empty(), "{label}: no section and no refusal");
10905                for c in &curves {
10906                    let worst = farthest_along(&c.curve, 4000, |p| {
10907                        off_double_cone(&cone, p).max(off_rod(p))
10908                    });
10909                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
10910                }
10911                for &t in &truth {
10912                    let near = curves
10913                        .iter()
10914                        .map(|c| {
10915                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
10916                                .unwrap()
10917                                .distance
10918                        })
10919                        .fold(f64::INFINITY, f64::min);
10920                    assert!(near < 1e-5, "{label}: {t:?} lies {near:.1e} off");
10921                }
10922            }
10923        }
10924    }
10925
10926    /// A rod of radius 0.6 runs along x over the top of the ring of radii 4
10927    /// and 1.5, its axis 0.007 inside the tube's top circle, its underside
10928    /// 8e-6 below the tube's top. Along the rod the tube's top rises to two
10929    /// crests 0.47 apart, where the rod dips into it in two loops about 0.17
10930    /// long and 0.005 wide. Each loop is smaller than a cell of either patch,
10931    /// and both lie in about one cell of the rod's. A cell's seed settles on
10932    /// one loop: one loop was lost with no error. The cells are now cut until
10933    /// each part of the section is proved to run through cells that a marched
10934    /// point or a seed reaches. Both loops are traced, in three poses and
10935    /// either way round, within the linear tolerance of both surfaces. Where
10936    /// the two cross at an angle whose sine is `s`, a fit within the
10937    /// tolerance of both can lie twice the tolerance over `s` off the
10938    /// section, up to 3e-3 at the loops' ends, where `s` is 7e-5: every point
10939    /// of the section lies within twice that, or 1e-5, of a curve.
10940    #[test]
10941    fn two_loops_in_one_cell_of_each_patch_are_both_traced() {
10942        let lin = Tolerance::new().linear;
10943        let turn = crate::mat::Mat4::rotation_z(0.75 * TAU / 32.0);
10944        let (delta, depth) = (0.007_f64, 8e-6_f64);
10945        let (y0, z0) = (4.0 - delta, 2.1 - depth);
10946        for (k, pose) in three_poses().iter().enumerate() {
10947            let pose = *pose * turn;
10948            let o = Point3::new(0.0, 0.0, 0.0);
10949            let along = |v: Vec3| pose.mul_point(o + v) - pose.mul_point(o);
10950            let centre = pose.mul_point(o);
10951            let up = along(Vec3::new(0.0, 0.0, 1.0));
10952            let ring = ToroidalSurface::with_axis(centre, 4.0, 1.5, up).unwrap();
10953            let start = pose.mul_point(Point3::new(0.0, y0, z0));
10954            let dir = along(Vec3::new(1.0, 0.0, 0.0));
10955            let rod = CylindricalSurface::new(start, dir, 0.6).unwrap();
10956            let ring_normal = |p: Point3| {
10957                let w = p - centre;
10958                let across = w - up * up.dot(w);
10959                let tube = centre + across * (4.0 / across.length());
10960                (p - tube) * (1.0 / (p - tube).length())
10961            };
10962            let rod_normal = |p: Point3| {
10963                let w = p - start;
10964                let across = w - dir * dir.dot(w);
10965                across * (1.0 / across.length())
10966            };
10967            let off_ring = |p: Point3| {
10968                let w = p - centre;
10969                let h = up.dot(w);
10970                ((w - up * h).length() - 4.0).hypot(h) - 1.5
10971            };
10972            let off_rod = |p: Point3| {
10973                let w = p - start;
10974                ((w - dir * dir.dot(w)).length() - 0.6).abs()
10975            };
10976            // Each ruling of the rod meets the ring where a quartic along it
10977            // vanishes.
10978            let mut truth = Vec::new();
10979            for j in -300..=300 {
10980                let phi = f64::from(j) * 1e-4;
10981                let from =
10982                    pose.mul_point(Point3::new(0.0, y0 + 0.6 * phi.sin(), z0 - 0.6 * phi.cos()));
10983                for t in intersect_line_torus(&ring, from, dir) {
10984                    if t.abs() < 2.0 {
10985                        truth.push(from + dir * t);
10986                    }
10987                }
10988            }
10989            assert!(truth.len() > 100, "pose {k}: {} points", truth.len());
10990            for rod_first in [true, false] {
10991                let label = format!("pose {k} rod first {rod_first}");
10992                let along_rod = Some((-9.6875, 10.3125));
10993                let result = if rod_first {
10994                    marched_sections(
10995                        AnalyticSurface::Cylinder(&rod),
10996                        AnalyticSurface::Torus(&ring),
10997                        32,
10998                        along_rod,
10999                        None,
11000                        None,
11001                    )
11002                } else {
11003                    marched_sections(
11004                        AnalyticSurface::Torus(&ring),
11005                        AnalyticSurface::Cylinder(&rod),
11006                        32,
11007                        None,
11008                        along_rod,
11009                        None,
11010                    )
11011                };
11012                assert!(result.is_ok(), "{label}: {:?}", result.as_ref().err());
11013                let curves = result.unwrap();
11014                assert_eq!(curves.len(), 2, "{label}: loops");
11015                for c in &curves {
11016                    let worst =
11017                        farthest_along(&c.curve, 4000, |p| off_ring(p).abs().max(off_rod(p)));
11018                    assert!(worst <= lin, "{label}: off by {worst:.2e}");
11019                }
11020                for &t in &truth {
11021                    let sin = ring_normal(t).cross(rod_normal(t)).length();
11022                    let bound = (4.0 * lin / sin).max(1e-5);
11023                    let near = curves
11024                        .iter()
11025                        .map(|c| {
11026                            crate::nurbs::projection::project_point_to_curve(&c.curve, t, 1e-12)
11027                                .unwrap()
11028                                .distance
11029                        })
11030                        .fold(f64::INFINITY, f64::min);
11031                    assert!(
11032                        near <= bound,
11033                        "{label}: {t:?} lies {near:.1e} off, past {bound:.1e}"
11034                    );
11035                }
11036            }
11037        }
11038    }
11039}