Skip to main content

ogeom_intersect/
section.rs

1//! Where two surfaces meet: the one call.
2//!
3//! Everything else in this crate is a stage: closed forms, seeding, tracing,
4//! fitting. This is the function an application calls, and the one `ogeom-bool`
5//! will build on: give it two surfaces, get back what they do to each other,
6//! with the analytic path taken where it exists and the marched-and-fitted
7//! path where it does not. The caller does not choose; the pair does.
8//!
9//! *Elsewhere* this is `GeomAPI_IntSS` over `IntPatch`/`GeomInt`: one entry
10//! point hiding an analytic dispatch and a walking intersector.
11//!
12//! # What a section curve carries
13//!
14//! Three descriptions, because three consumers: the curve in space for the
15//! edge, and a pcurve per surface for the faces; face splitting happens in
16//! parameter space, and a curve a face cannot express is one it cannot be
17//! split along. Analytic results carry exact pcurves where the projection has
18//! a closed form and `None` where it does not; fitted results always carry
19//! fitted pcurves, because the tracer recorded the parameters as it walked.
20//!
21//! A pcurve here is **same-parameter** with its 3D curve: evaluating either at
22//! the same `t` lands on the same point of the intersection. That is the claim
23//! `docs/DATA_MODEL.md` ยง6 makes edges carry, and it is arranged here by
24//! construction (the 2D curves inherit the 3D curve's own parameterization)
25//! rather than asserted and repaired later.
26
27use ogeom_core::{OgeomResult, Tolerances, ogeom_bail};
28use ogeom_geom::{
29    Circle2d, Curve, Curve2d as _, Curve3d, Ellipse2d, Line2d, PlanarCurve, Surface,
30    SurfaceGeometry,
31};
32use ogeom_math::{Circle2, Ellipse2, Frame2, Point, Point2};
33
34use crate::approx::approximate_branch;
35use crate::march::{Marching, branches, trace_tangential};
36use crate::surface::{Meeting, surface_surface};
37
38/// How to intersect, when the general path runs.
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct IntersectOptions {
41    /// The tolerance the fitted curves are held to.
42    pub tolerance: f64,
43    /// The marching settings, for pairs with no closed form.
44    pub marching: Marching,
45}
46
47impl Default for IntersectOptions {
48    fn default() -> Self {
49        Self {
50            tolerance: 1e-6,
51            marching: Marching::default(),
52        }
53    }
54}
55
56/// One curve of a section, with its parameter-space descriptions.
57#[derive(Debug, Clone, PartialEq)]
58pub struct SectionCurve {
59    /// The curve in space.
60    pub curve: Curve,
61    /// The curve in the first surface's parameter space, where it has one.
62    ///
63    /// Always present for a fitted curve. For an exact curve, present when the
64    /// projection has a closed form (a line on a plane, a circle on the
65    /// cylinder it wraps) and `None` where it does not, which is a statement
66    /// about the projection rather than about the curve.
67    pub on_a: Option<PlanarCurve>,
68    /// The same, on the second surface.
69    pub on_b: Option<PlanarCurve>,
70    /// How far this curve may sit from the true intersection.
71    ///
72    /// Zero for an exact curve. For a fitted one, the trace's chord tolerance
73    /// plus the fit's reported error: the sum of the stated parts.
74    pub tolerance: f64,
75    /// Whether the curve came from a closed form.
76    pub exact: bool,
77    /// Whether it is a closed loop.
78    pub closed: bool,
79    /// Whether the surfaces *touch* along this curve rather than crossing
80    /// it.
81    ///
82    /// A tangential contact is a real curve (the two surfaces meet there,
83    /// and a drawing has to show it), but it carries no boundary parity:
84    /// neither surface passes through the other, so nothing is inside on
85    /// one side and outside on the other. Consumers that classify by
86    /// crossing must leave these out of that arithmetic; consumers that
87    /// draw or measure contact want them.
88    pub tangential: bool,
89}
90
91/// What two surfaces do to each other.
92#[derive(Debug, Clone, PartialEq)]
93pub enum SurfaceIntersection {
94    /// They do not meet.
95    ///
96    /// From the general path this means *no crossing was found at the seeding
97    /// resolution*: a branch thinner than the sampling grid is invisible to
98    /// it, and the completeness instrument in `tests/support/coverage.rs` is
99    /// what checks.
100    Apart,
101    /// They touch at isolated points without crossing.
102    Touching(Vec<Point>),
103    /// They meet along these curves.
104    Along(Vec<SectionCurve>),
105    /// They are the same surface wherever they overlap.
106    Same,
107}
108
109/// Where two surfaces meet.
110///
111/// The analytic path answers the pairs with closed forms, exactly, with
112/// tolerance zero. Every other pair is seeded, traced and fitted to
113/// `options.tolerance`. One call, and the pair decides the path.
114///
115/// # Errors
116///
117/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if the options
118/// are unusable. A pair the marcher finds nothing for is [`Apart`], not an
119/// error; see that variant for what it can and cannot claim.
120///
121/// [`Apart`]: SurfaceIntersection::Apart
122pub fn intersect_surfaces(
123    a: &SurfaceGeometry,
124    b: &SurfaceGeometry,
125    options: IntersectOptions,
126    tol: Tolerances,
127) -> OgeomResult<SurfaceIntersection> {
128    if !options.tolerance.is_finite() || options.tolerance <= 0.0 {
129        ogeom_bail!(
130            Construction,
131            "a tolerance of {} is not a distance",
132            options.tolerance
133        );
134    }
135
136    // A plane all but along a drum's axis meets it in an ellipse
137    // kilometres long, whose parameter is too coarse a ruler for the few
138    // millimetres of it the drum's height holds: a crossing solved on it
139    // lands tens of microns off. Over that height it is two lines.
140    if let Some(sections) = near_parallel_plane_drum(a, b, tol) {
141        return Ok(if sections.is_empty() {
142            SurfaceIntersection::Apart
143        } else {
144            SurfaceIntersection::Along(sections)
145        });
146    }
147    match surface_surface(a, b, tol) {
148        Ok(Meeting::Apart) => Ok(SurfaceIntersection::Apart),
149        Ok(Meeting::Same) => Ok(SurfaceIntersection::Same),
150        Ok(Meeting::Touching(points)) => Ok(SurfaceIntersection::Touching(points)),
151        Ok(Meeting::Along(curves)) => {
152            let sections: Vec<SectionCurve> = curves
153                .into_iter()
154                .filter_map(|curve| exact_section(curve, a, b, tol))
155                .collect();
156            Ok(if sections.is_empty() {
157                // Every curve fell outside the surfaces' stated extents: the
158                // unbounded geometries meet, the surfaces as given do not.
159                SurfaceIntersection::Apart
160            } else {
161                SurfaceIntersection::Along(sections)
162            })
163        }
164        // No closed form for this pair: the statement that sends us marching,
165        // unless the pair is two drums all but parallel.
166        Err(_) => match near_parallel_drums(a, b, tol)
167            .or_else(|| ball_through_drum(a, b, tol))
168            .or_else(|| axial_plane_revolution(a, b, tol))
169            .or_else(|| plane_along_spline_lines(a, b, tol))
170        {
171            Some(sections) if sections.is_empty() => Ok(SurfaceIntersection::Apart),
172            Some(sections) => Ok(SurfaceIntersection::Along(sections)),
173            None => marched(a, b, options, tol),
174        },
175    }
176}
177
178/// A plane through the axis of a surface of revolution whose profile lies
179/// in a plane through that axis: the profile turned to each angle that sets
180/// its plane on the cut, a column of the revolution's chart.
181///
182/// Marched, such a section runs through the pole wherever the profile meets
183/// the axis, where the chart pinches to a point and the march stalls. Here
184/// the profile is cut where it crosses the axis, and each piece is turned to
185/// both angles, the one setting its side of the axis on each half of the
186/// cut: a revolution whose profile crosses the axis covers the section
187/// twice, once from each column, and a face on either column finds its own
188/// piece. `None` for any other plane or profile, and where the turns fall
189/// outside the sweep the answer is empty.
190fn axial_plane_revolution(
191    a: &SurfaceGeometry,
192    b: &SurfaceGeometry,
193    tol: Tolerances,
194) -> Option<Vec<SectionCurve>> {
195    const SAMPLES: u32 = 64;
196    let (plane, revolution, plane_first) = match (a, b) {
197        (SurfaceGeometry::Plane(p), SurfaceGeometry::Revolution(r)) => (p, r, true),
198        (SurfaceGeometry::Revolution(r), SurfaceGeometry::Plane(p)) => (p, r, false),
199        _ => return None,
200    };
201    let cut = plane.plane();
202    let axis = revolution.axis();
203    let normal = cut.normal();
204    if normal.dot(axis.direction).abs() > tol.angular()
205        || cut.signed_distance_to(axis.location).abs() > tol.confusion()
206    {
207        return None;
208    }
209    let profile = revolution.curve();
210    let (v0, v1) = profile.domain();
211    let at = |k: u32| v0 + (v1 - v0) * f64::from(k) / f64::from(SAMPLES);
212    let radial = |v: f64| {
213        let p = profile.point_at(v, tol).ok()?;
214        Some(p - axis.project(p))
215    };
216    // The profile's own side of the axis, from its point furthest off it.
217    let mut widest = ogeom_math::Vector::ZERO;
218    for k in 0..=SAMPLES {
219        let r = radial(at(k))?;
220        if r.magnitude() > widest.magnitude() {
221            widest = r;
222        }
223    }
224    let side = ogeom_math::Direction::new(widest, tol).ok()?;
225    let across = axis.direction.cross_with(side.vector());
226    // Every point of the profile in the plane of the axis and that side.
227    let offset = |v: f64| radial(v).map(|r| (r.dot(side.vector()), r.dot(across)));
228    for k in 0..=SAMPLES {
229        let (_, off) = offset(at(k))?;
230        if off.abs() > tol.confusion() {
231            return None;
232        }
233    }
234    // The pieces between the profile's crossings of the axis, each crossing
235    // narrowed by bisection.
236    let mut cuts = vec![v0];
237    for k in 0..SAMPLES {
238        let (mut lo, mut hi) = (at(k), at(k + 1));
239        let (s_lo, s_hi) = (offset(lo)?.0, offset(hi)?.0);
240        if s_lo.abs() <= tol.confusion() || s_lo * s_hi >= 0.0 {
241            continue;
242        }
243        for _ in 0..80 {
244            let mid = f64::midpoint(lo, hi);
245            if offset(mid)?.0 * s_lo > 0.0 {
246                lo = mid;
247            } else {
248                hi = mid;
249            }
250        }
251        cuts.push(f64::midpoint(lo, hi));
252    }
253    cuts.push(v1);
254    // The turns setting the profile's side on the cut's two halves.
255    let out = axis.direction.cross_with(normal.vector());
256    let first = across.dot(out).atan2(side.vector().dot(out));
257    let (u0, u1) = revolution.domain().0;
258    let turns: Vec<f64> = [first, first + core::f64::consts::PI]
259        .into_iter()
260        .filter_map(|u| {
261            let u = u0 + (u - u0).rem_euclid(core::f64::consts::TAU);
262            let u = if (u - u0 - core::f64::consts::TAU).abs() <= tol.angular() {
263                u0
264            } else {
265                u
266            };
267            (u <= u1 + tol.angular()).then_some(u.min(u1))
268        })
269        .collect();
270    let mut sections = Vec::new();
271    for &u in &turns {
272        let turned = ogeom_geom::Transformable::transformed(
273            profile,
274            &ogeom_math::Transform::rotation(axis, u),
275            tol,
276        )
277        .ok()?;
278        for piece in cuts.windows(2) {
279            let (va, vb) = (piece[0], piece[1]);
280            if vb - va <= tol.parametric() {
281                continue;
282            }
283            let curve: Curve = ogeom_geom::TrimmedCurve::new(turned.clone(), va, vb, tol)
284                .ok()?
285                .into();
286            let column: PlanarCurve = Line2d::over(
287                ogeom_math::Axis2::new(Point2::new(u, 0.0), ogeom_math::Direction2::Y),
288                va,
289                vb,
290            )
291            .ok()?
292            .into();
293            let flat = exact_pcurve(&curve, (va, vb), a_or_b(plane_first, a, b), tol);
294            let (on_a, on_b) = if plane_first {
295                (flat, Some(column))
296            } else {
297                (Some(column), flat)
298            };
299            sections.push(SectionCurve {
300                on_a,
301                on_b,
302                tolerance: 0.0,
303                exact: true,
304                closed: false,
305                tangential: false,
306                curve,
307            });
308        }
309    }
310    Some(sections)
311}
312
313/// A plane holding whole columns or rows of a spline surface, and meeting
314/// it nowhere else: those iso lines, exactly.
315///
316/// A surface of revolution converted to a spline and scaled keeps its
317/// meridians as columns, and a plane through its axis holds two of them,
318/// one often the seam along the chart's border. Marched, such a section
319/// runs along the chart's edge or through its poles and is not found. An
320/// iso line lies in the plane where every control point of it does, which
321/// is a root of each control point's weighted distance to the plane, found
322/// along the chart. The answer stands only where a grid over the chart
323/// finds the surface on one side of the plane between the lines found;
324/// anything else meets the plane elsewhere too and is marched.
325fn plane_along_spline_lines(
326    a: &SurfaceGeometry,
327    b: &SurfaceGeometry,
328    tol: Tolerances,
329) -> Option<Vec<SectionCurve>> {
330    const SAMPLES: u32 = 96;
331    let (plane, spline, plane_first) = match (a, b) {
332        (SurfaceGeometry::Plane(p), SurfaceGeometry::BSpline(s)) => (p.plane(), s, true),
333        (SurfaceGeometry::BSpline(s), SurfaceGeometry::Plane(p)) => (p.plane(), s, false),
334        _ => return None,
335    };
336    let distance = |p: Point| plane.signed_distance_to(p);
337    let ((u0, u1), (v0, v1)) = spline.domain();
338    // An iso line's control points' weighted distances to the plane, and
339    // whether the line has any length.
340    let line_at = |along_u: bool, t: f64| -> Option<ogeom_geom::BSplineCurve> {
341        if along_u {
342            spline.iso_u_curve(t, tol).ok()
343        } else {
344            spline.iso_v_curve(t, tol).ok()
345        }
346    };
347    let weighted = |curve: &ogeom_geom::BSplineCurve| -> Vec<f64> {
348        curve
349            .control_points()
350            .iter()
351            .map(|w| w.weight * distance(w.point()))
352            .collect()
353    };
354    let lies_in = |curve: &ogeom_geom::BSplineCurve| {
355        curve
356            .control_points()
357            .iter()
358            .all(|w| distance(w.point()).abs() <= tol.confusion())
359    };
360    let has_length = |curve: &ogeom_geom::BSplineCurve| {
361        let first = curve.control_points()[0].point();
362        curve
363            .control_points()
364            .iter()
365            .any(|w| w.point().distance(first) > tol.confusion())
366    };
367    // The iso lines of one family lying in the plane: the chart's borders,
368    // and every root of the control point that strays furthest.
369    let found = |along_u: bool| -> Option<Vec<f64>> {
370        let (lo, hi) = if along_u { (u0, u1) } else { (v0, v1) };
371        let at = |k: u32| lo + (hi - lo) * f64::from(k) / f64::from(SAMPLES);
372        let rows: Vec<Vec<f64>> = (0..=SAMPLES)
373            .map(|k| line_at(along_u, at(k)).map(|c| weighted(&c)))
374            .collect::<Option<_>>()?;
375        let count = rows[0].len();
376        if rows.iter().any(|r| r.len() != count) {
377            return None;
378        }
379        let widest = (0..count).max_by(|&i, &j| {
380            let spread = |i: usize| rows.iter().fold(0.0_f64, |m, r| m.max(r[i].abs()));
381            spread(i).total_cmp(&spread(j))
382        })?;
383        let mut roots = vec![lo, hi];
384        for k in 0..SAMPLES {
385            let (mut a, mut b) = (at(k), at(k + 1));
386            let (da, db) = (rows[k as usize][widest], rows[k as usize + 1][widest]);
387            if da == 0.0 {
388                roots.push(a);
389                continue;
390            }
391            if da * db > 0.0 {
392                continue;
393            }
394            let sign = da.signum();
395            for _ in 0..80 {
396                let mid = f64::midpoint(a, b);
397                let d = weighted(&line_at(along_u, mid)?)[widest];
398                if d * sign > 0.0 {
399                    a = mid;
400                } else {
401                    b = mid;
402                }
403            }
404            roots.push(f64::midpoint(a, b));
405        }
406        roots.sort_by(f64::total_cmp);
407        roots.dedup_by(|x, y| (*x - *y).abs() <= tol.parametric());
408        Some(
409            roots
410                .into_iter()
411                .filter(|&t| line_at(along_u, t).is_some_and(|c| lies_in(&c) && has_length(&c)))
412                .collect(),
413        )
414    };
415    let columns = found(true)?;
416    let rows = found(false)?;
417    if columns.is_empty() && rows.is_empty() {
418        return None;
419    }
420    // The chart cut by the lines found into cells: the surface keeps to one
421    // side of the plane within each, or it meets the plane elsewhere too.
422    let strip = |lines: &[f64], t: f64| lines.iter().filter(|&&x| x < t).count();
423    let near_line = |lines: &[f64], t: f64, span: f64| {
424        lines
425            .iter()
426            .any(|&x| (x - t).abs() <= span / f64::from(SAMPLES) * 0.25)
427    };
428    let mut sides: std::collections::HashMap<(usize, usize), f64> =
429        std::collections::HashMap::new();
430    let band = tol.confusion() * 10.0;
431    for i in 0..=SAMPLES {
432        let u = u0 + (u1 - u0) * (f64::from(i) + 0.5) / f64::from(SAMPLES + 1);
433        if near_line(&columns, u, u1 - u0) {
434            continue;
435        }
436        for j in 0..=SAMPLES {
437            let v = v0 + (v1 - v0) * (f64::from(j) + 0.5) / f64::from(SAMPLES + 1);
438            if near_line(&rows, v, v1 - v0) {
439                continue;
440            }
441            let d = distance(spline.point_at(u, v, tol).ok()?);
442            if d.abs() <= band {
443                continue;
444            }
445            let cell = (strip(&columns, u), strip(&rows, v));
446            match sides.get(&cell) {
447                Some(side) if side * d < 0.0 => return None,
448                Some(_) => {}
449                None => {
450                    sides.insert(cell, d.signum());
451                }
452            }
453        }
454    }
455    // Each line must be a crossing, the cells either side of it on
456    // opposite sides of the plane (across the border of a closed chart,
457    // the cells at its two ends). A line the surface only touches, or with
458    // no cell beside it to say, is a tangency the marcher and the contact
459    // handling answer, and so is the whole pair.
460    let closed_u = spline.is_closed_u(tol);
461    let closed_v = spline.is_closed_v(tol);
462    let side_of = |cu: Option<usize>, cv: Option<usize>| -> Option<f64> {
463        let mut found = sides
464            .iter()
465            .filter(|((u, v), _)| cu.is_none_or(|c| c == *u) && cv.is_none_or(|c| c == *v))
466            .map(|(_, s)| *s);
467        let first = found.next()?;
468        found.all(|s| s == first).then_some(first)
469    };
470    let crosses = |k: usize, count: usize, closed: bool, cell: &dyn Fn(usize) -> Option<f64>| {
471        let below = cell(k).or_else(|| closed.then(|| (0..=count).rev().find_map(cell)).flatten());
472        let above = cell(k + 1).or_else(|| closed.then(|| (0..=count).find_map(cell)).flatten());
473        matches!((below, above), (Some(x), Some(y)) if x * y < 0.0)
474    };
475    for k in 0..columns.len() {
476        if !crosses(k, columns.len(), closed_u, &|c| side_of(Some(c), None)) {
477            return None;
478        }
479    }
480    for k in 0..rows.len() {
481        if !crosses(k, rows.len(), closed_v, &|c| side_of(None, Some(c))) {
482            return None;
483        }
484    }
485    let mut sections = Vec::new();
486    let mut emit = |along_u: bool, t: f64| -> Option<()> {
487        let iso = line_at(along_u, t)?;
488        let curve: Curve = iso.into();
489        let range = curve.domain();
490        let chart: PlanarCurve = if along_u {
491            Line2d::over(
492                ogeom_math::Axis2::new(Point2::new(t, 0.0), ogeom_math::Direction2::Y),
493                range.0,
494                range.1,
495            )
496        } else {
497            Line2d::over(
498                ogeom_math::Axis2::new(Point2::new(0.0, t), ogeom_math::Direction2::X),
499                range.0,
500                range.1,
501            )
502        }
503        .ok()?
504        .into();
505        let flat = exact_pcurve(&curve, range, a_or_b(plane_first, a, b), tol)?;
506        let (on_a, on_b) = if plane_first {
507            (Some(flat), Some(chart))
508        } else {
509            (Some(chart), Some(flat))
510        };
511        sections.push(SectionCurve {
512            on_a,
513            on_b,
514            tolerance: 0.0,
515            exact: true,
516            closed: curve.is_closed(tol),
517            tangential: false,
518            curve,
519        });
520        Some(())
521    };
522    // Every line found: the chart's two borders across a closed surface
523    // are one line in space, stated once.
524    for (k, &u) in columns.iter().enumerate() {
525        if closed_u
526            && k + 1 == columns.len()
527            && k > 0
528            && columns[0] == u0
529            && (u - u1).abs() <= tol.parametric()
530        {
531            continue;
532        }
533        emit(true, u)?;
534    }
535    for (k, &v) in rows.iter().enumerate() {
536        if closed_v
537            && k + 1 == rows.len()
538            && k > 0
539            && rows[0] == v0
540            && (v - v1).abs() <= tol.parametric()
541        {
542            continue;
543        }
544        emit(false, v)?;
545    }
546    Some(sections)
547}
548
549/// The first surface where `first` holds, else the second.
550fn a_or_b<'s>(first: bool, a: &'s SurfaceGeometry, b: &'s SurfaceGeometry) -> &'s SurfaceGeometry {
551    if first { a } else { b }
552}
553
554/// Two drums whose axes are all but parallel, over the height they share.
555///
556/// Parallel drums meet in straight lines along their axes, and drums whose
557/// axes lean a ten-thousandth apart (a drilled hole beside a fillet of a
558/// converted mesh, each axis fitted to its own facets) meet in a quartic
559/// that departs from those lines by less than a micron over any height a
560/// part has. Marched, it comes back as fitted curves that cost seconds to
561/// cross and wander where the drums nearly touch. Here each is solved in
562/// the cross-sections along the shared height and kept as the line through
563/// its ends where every station lies near it, that departure stated as the
564/// section's tolerance.
565///
566/// `None` where the axes lean further, where the drums do not cross
567/// cleanly at every station (a crossing starting part way up, or a near
568/// touch), or where a station strays: the marcher answers those. An empty
569/// answer is drums that share no height.
570fn near_parallel_drums(
571    a: &SurfaceGeometry,
572    b: &SurfaceGeometry,
573    tol: Tolerances,
574) -> Option<Vec<SectionCurve>> {
575    const LEAN: f64 = 1e-3;
576    let (SurfaceGeometry::Cylinder(sa), SurfaceGeometry::Cylinder(sb)) = (a, b) else {
577        return None;
578    };
579    let (ca, cb) = (sa.cylinder(), sb.cylinder());
580    let (axis_a, axis_b) = (ca.axis(), cb.axis());
581    let (da, db) = (axis_a.direction.vector(), axis_b.direction.vector());
582    let (ra, rb) = (ca.radius(), cb.radius());
583    let cos = da.dot(db);
584    if da.cross(db).magnitude() > LEAN || cos.abs() < 0.5 {
585        return None;
586    }
587    let (pa, pb) = (axis_a.location, axis_b.location);
588    // The shared height, measured along the first axis.
589    let (_, (a0, a1)) = a.domain();
590    let (_, (b0, b1)) = b.domain();
591    let along = |v: f64| (pb - pa).dot(da) + v * cos;
592    let (lo, hi) = (
593        a0.min(a1).max(along(b0).min(along(b1))),
594        a0.max(a1).min(along(b0).max(along(b1))),
595    );
596    if !(lo.is_finite() && hi.is_finite()) {
597        return None;
598    }
599    if hi - lo <= tol.confusion() {
600        return Some(Vec::new());
601    }
602    // Where the two cross-sections at a station meet, left and right of
603    // the line of centres: the second drum's section is an ellipse only a
604    // square of its lean away from a circle, a stated part of the stray.
605    let meet = |z: f64| -> Option<[Point; 2]> {
606        let centre_a = pa + da * z;
607        let s = (centre_a - pb).dot(da) / cos;
608        let centre_b = pb + db * s;
609        let mut between = centre_b - centre_a;
610        between = between - da * between.dot(da);
611        let d = between.magnitude();
612        let margin = tol.confusion() * 1e3;
613        if d <= margin || d >= ra + rb - margin || d <= (ra - rb).abs() + margin {
614            return None;
615        }
616        let x = (d * d + ra * ra - rb * rb) / (2.0 * d);
617        let h = (ra * ra - x * x).max(0.0).sqrt();
618        let ex = between / d;
619        let ey = da.cross(ex);
620        Some([centre_a + ex * x + ey * h, centre_a + ex * x - ey * h])
621    };
622    lines_through_stations(lo, hi, meet, rb * (1.0 / cos.abs() - 1.0), tol)
623}
624
625/// How far a near-parallel pair's sections may stray from the true
626/// crossing: what a fitted section typically carries.
627const NEAR_PARALLEL_STRAY: f64 = 1e-5;
628
629/// The two curves a near-parallel pair meets in over the height `lo..hi`,
630/// from where `meet` puts the crossing at each height: the line through the
631/// ends where every station lies within a micron of it, else a cubic
632/// through the stations at their heights, checked midway between them.
633/// Either is kept within [`NEAR_PARALLEL_STRAY`], the departure stated as
634/// its tolerance. `None` where a station has no clean crossing or the
635/// curve strays.
636fn lines_through_stations(
637    lo: f64,
638    hi: f64,
639    meet: impl Fn(f64) -> Option<[Point; 2]>,
640    stated: f64,
641    tol: Tolerances,
642) -> Option<Vec<SectionCurve>> {
643    const STATIONS: u32 = 32;
644    const STRAIGHT: f64 = 1e-6;
645    let at = |k: f64| (hi - lo).mul_add(k / f64::from(STATIONS), lo);
646    let heights: Vec<f64> = (0..=STATIONS).map(|k| at(f64::from(k))).collect();
647    let met: Vec<[Point; 2]> = heights.iter().map(|&z| meet(z)).collect::<Option<_>>()?;
648    let between: Vec<[Point; 2]> = (0..STATIONS)
649        .map(|k| meet(at(f64::from(k) + 0.5)))
650        .collect::<Option<_>>()?;
651    let mut out = Vec::with_capacity(2);
652    for side in 0..2 {
653        let (from, to) = (met[0][side], met[met.len() - 1][side]);
654        let span = to - from;
655        let length = span.magnitude();
656        if length <= tol.confusion() {
657            return None;
658        }
659        let off_line = |p: Point| {
660            let t = (p - from).dot(span) / (length * length);
661            p.distance(from + span * t)
662        };
663        let stray = met
664            .iter()
665            .chain(&between)
666            .map(|pair| off_line(pair[side]))
667            .fold(0.0_f64, f64::max);
668        let (curve, stray): (Curve, f64) = if stray <= STRAIGHT {
669            (
670                ogeom_geom::LineCurve::segment(from, to, tol).ok()?.into(),
671                stray,
672            )
673        } else {
674            let points: Vec<Point> = met.iter().map(|pair| pair[side]).collect();
675            let fitted =
676                ogeom_geom::fit::fit_points_at(&heights, &points, 3, tol.confusion(), tol).ok()?;
677            let curve: Curve = fitted.curve.into();
678            let mut worst = fitted.error;
679            for (k, pair) in (0..STATIONS).zip(&between) {
680                let p = curve.point_at(at(f64::from(k) + 0.5), tol).ok()?;
681                worst = worst.max(p.distance(pair[side]));
682            }
683            (curve, worst)
684        };
685        let tolerance = stray + stated + tol.confusion();
686        if tolerance > NEAR_PARALLEL_STRAY {
687            return None;
688        }
689        out.push(SectionCurve {
690            curve,
691            on_a: None,
692            on_b: None,
693            tolerance,
694            exact: false,
695            closed: false,
696            tangential: false,
697        });
698    }
699    Some(out)
700}
701
702/// A drum passing clean through a ball: every line along the drum meets
703/// the ball twice, within the drum's height.
704///
705/// Then each of the two loops the drum and ball meet in is a function of
706/// the angle round the drum: at each angle, where the line along the drum
707/// enters and leaves the ball is a quadratic's two roots. The loops are
708/// sampled so, exactly, and fitted closed, the fit's error stated as the
709/// section's tolerance. Marched instead, a drum that all but grazes the
710/// ball's far side leaves loops long and thin, and the trace wanders along
711/// them past any bound. `None` where some line misses or grazes the ball,
712/// or leaves the drum's height: the marcher answers those.
713fn ball_through_drum(
714    a: &SurfaceGeometry,
715    b: &SurfaceGeometry,
716    tol: Tolerances,
717) -> Option<Vec<SectionCurve>> {
718    const SAMPLES: u32 = 256;
719    const STRAY: f64 = 1e-5;
720    let (ball, drum, ball_first) = match (a, b) {
721        (SurfaceGeometry::Sphere(s), SurfaceGeometry::Cylinder(c)) => (s, c, true),
722        (SurfaceGeometry::Cylinder(c), SurfaceGeometry::Sphere(s)) => (s, c, false),
723        _ => return None,
724    };
725    let (sphere, cylinder) = (ball.sphere(), drum.cylinder());
726    let frame = cylinder.frame();
727    let (x, y, d) = (frame.x().vector(), frame.y().vector(), frame.z().vector());
728    let (origin, r) = (frame.origin(), cylinder.radius());
729    let (centre, big) = (sphere.centre(), sphere.radius());
730    let ball_frame = sphere.frame();
731    let (_, (h0, h1)) = drum.domain();
732    // A line that only just meets the ball leaves the loop turning sharply
733    // there; a tenth of the drum's radius of chord inside the ball keeps
734    // the loops smooth enough to fit.
735    let margin = r * 0.1;
736    // Where the line along the drum at `angle` enters and leaves the ball.
737    let heights = |angle: f64| -> Option<[f64; 2]> {
738        let foot = origin + (x * angle.cos() + y * angle.sin()) * r;
739        let w = foot - centre;
740        let half = d.dot(w);
741        let disc = half.mul_add(half, -(w.dot(w) - big * big));
742        if disc <= margin * margin {
743            return None;
744        }
745        let root = disc.sqrt();
746        let pair = [-half - root, -half + root];
747        pair.iter().all(|v| *v >= h0 && *v <= h1).then_some(pair)
748    };
749    let at = |angle: f64, v: f64| origin + (x * angle.cos() + y * angle.sin()) * r + d * v;
750    // The ball's longitude and latitude of a point, as its chart reads them.
751    let on_ball = |p: Point, before: Option<Point2>| -> Point2 {
752        let local = ball_frame.to_local(p);
753        let lat = local.z.atan2(local.x.hypot(local.y));
754        let mut lon = local.y.atan2(local.x).rem_euclid(core::f64::consts::TAU);
755        if let Some(prev) = before {
756            while lon - prev.x > core::f64::consts::PI {
757                lon -= core::f64::consts::TAU;
758            }
759            while prev.x - lon > core::f64::consts::PI {
760                lon += core::f64::consts::TAU;
761            }
762        }
763        Point2::new(lon, lat)
764    };
765    let angle_of = |k: f64| core::f64::consts::TAU * k / f64::from(SAMPLES);
766    let params: Vec<f64> = (0..=SAMPLES).map(|k| angle_of(f64::from(k))).collect();
767    let mut sampled: Vec<[f64; 2]> = Vec::with_capacity(params.len());
768    for &angle in &params {
769        sampled.push(heights(angle)?);
770    }
771    let mut out = Vec::with_capacity(2);
772    for side in 0..2 {
773        let points: Vec<Point> = params
774            .iter()
775            .zip(&sampled)
776            .map(|(&angle, pair)| at(angle, pair[side]))
777            .collect();
778        let on_drum: Vec<Point2> = params
779            .iter()
780            .zip(&sampled)
781            .map(|(&angle, pair)| Point2::new(angle, pair[side]))
782            .collect();
783        let mut on_sphere: Vec<Point2> = Vec::with_capacity(points.len());
784        for p in &points {
785            let q = on_ball(*p, on_sphere.last().copied());
786            on_sphere.push(q);
787        }
788        let target = tol.confusion() * 10.0;
789        let curve: Curve = ogeom_geom::fit::fit_points_at(&params, &points, 3, target, tol)
790            .ok()?
791            .curve
792            .into();
793        let drum_image: PlanarCurve =
794            ogeom_geom::fit::fit_points_2d_at(&params, &on_drum, 3, target, tol)
795                .ok()?
796                .curve
797                .into();
798        let ball_image: PlanarCurve =
799            ogeom_geom::fit::fit_points_2d_at(&params, &on_sphere, 3, target, tol)
800                .ok()?
801                .curve
802                .into();
803        // Checked at the samples and midway between them: the curve, and
804        // each surface read through its image, against the true meeting.
805        let mut stray = 0.0_f64;
806        for k in 0..(2 * SAMPLES) {
807            let angle = angle_of(f64::from(k) / 2.0);
808            let truth = at(angle, heights(angle)?[side]);
809            let on_curve = curve.point_at(angle, tol).ok()?;
810            let uv = drum_image.point_at(angle, tol).ok()?;
811            let through_drum = drum.point_at(uv.x, uv.y, tol).ok()?;
812            let uv = ball_image.point_at(angle, tol).ok()?;
813            let through_ball = ball.point_at(uv.x, uv.y, tol).ok()?;
814            stray = stray
815                .max(truth.distance(on_curve))
816                .max(truth.distance(through_drum))
817                .max(truth.distance(through_ball));
818        }
819        let tolerance = stray.max(tol.confusion());
820        if tolerance > STRAY {
821            return None;
822        }
823        let (on_a, on_b) = if ball_first {
824            (ball_image, drum_image)
825        } else {
826            (drum_image, ball_image)
827        };
828        out.push(SectionCurve {
829            curve,
830            on_a: Some(on_a),
831            on_b: Some(on_b),
832            tolerance,
833            exact: false,
834            closed: true,
835            tangential: false,
836        });
837    }
838    Some(out)
839}
840
841/// A plane leaning all but along a drum's axis, over the drum's height.
842///
843/// The closed form is an ellipse whose long axis is the drum's radius over
844/// the lean, kilometres for a facet group fitted a hundred-thousandth off
845/// a hole's axis. Its parameter spans the few millimetres the drum holds in
846/// a millionth of a turn, and crossings solved on it are only as good as
847/// that ruler. The crossing is solved instead in the drum's cross-sections
848/// along its height and kept as two lines where they hold, as
849/// [`near_parallel_drums`] does. `None` where the lean is exactly nothing
850/// (the closed form's lines are exact) or more than a thousandth, or where
851/// the plane does not cross the drum cleanly all the way up.
852fn near_parallel_plane_drum(
853    a: &SurfaceGeometry,
854    b: &SurfaceGeometry,
855    tol: Tolerances,
856) -> Option<Vec<SectionCurve>> {
857    const LEAN: f64 = 1e-3;
858    const SPAN: f64 = 3e4;
859    let (plane, drum, surface) = match (a, b) {
860        (SurfaceGeometry::Plane(p), SurfaceGeometry::Cylinder(c)) => (p.plane(), c.cylinder(), b),
861        (SurfaceGeometry::Cylinder(c), SurfaceGeometry::Plane(p)) => (p.plane(), c.cylinder(), a),
862        _ => return None,
863    };
864    let axis = drum.axis();
865    let (d, r) = (axis.direction.vector(), drum.radius());
866    let n = plane.normal().vector();
867    let lean = n.dot(d).abs();
868    // Only where the ellipse is thirty metres or more across: there a
869    // parameter solved to its last billionth lands tens of nanometres off in
870    // space, past the weld of a face with tight edges. A shorter one is
871    // ruler enough, and its closed form crosses faster than a fitted curve.
872    if lean <= tol.angular() || lean > LEAN || r / lean < SPAN {
873        return None;
874    }
875    let across = n - d * n.dot(d);
876    let k = across.magnitude();
877    let e1 = across / k;
878    let e2 = d.cross(e1);
879    let (_, (lo, hi)) = surface.domain();
880    if !(lo.is_finite() && hi.is_finite()) || hi - lo <= tol.confusion() {
881        return None;
882    }
883    let meet = |z: f64| -> Option<[Point; 2]> {
884        let centre = axis.location + d * z;
885        let u = -plane.signed_distance_to(centre) / k;
886        let margin = tol.confusion() * 1e3;
887        if u.abs() >= r - margin {
888            return None;
889        }
890        let w = r.mul_add(r, -(u * u)).sqrt();
891        Some([centre + e1 * u + e2 * w, centre + e1 * u - e2 * w])
892    };
893    lines_through_stations(lo, hi, meet, 0.0, tol)
894}
895
896/// An exact curve dressed as a section, clipped to the surfaces it lies on.
897///
898/// The analytic layer works on the unbounded geometry (a plane and a cylinder
899/// meet in unbounded lines), but the *surfaces* carry finite extents, and a
900/// section running a billion units past both is not something an edge can be
901/// built on. A line is clipped to the parameter interval where it is inside
902/// both extents, through its exact pcurves; a curve wholly outside either
903/// extent is dropped, or the boolean above would see a phantom edge on a
904/// region the face does not have.
905///
906/// A *closed* curve partially outside an extent is kept whole: cutting it into
907/// arcs is the restriction problem, and the restriction that matters is the
908/// face's trim, which is ยง8's job; the extent here is only the surface's
909/// parameterization window.
910fn exact_section(
911    curve: Curve,
912    a: &SurfaceGeometry,
913    b: &SurfaceGeometry,
914    tol: Tolerances,
915) -> Option<SectionCurve> {
916    let closed = match &curve {
917        Curve::Circle(_) | Curve::Ellipse(_) => true,
918        _ => curve.is_closed(tol),
919    };
920    let range = curve.domain();
921    let on_a = exact_pcurve(&curve, range, a, tol);
922    let on_b = exact_pcurve(&curve, range, b, tol);
923
924    if let Curve::Line(_) = &curve {
925        // Clip through whichever pcurves exist; a missing pcurve leaves that
926        // surface's extent unenforced, which errs long rather than wrong.
927        let mut interval = curve.domain();
928        if let Some(p) = &on_a {
929            interval = intersect_intervals(interval, inside_box(p, a))?;
930        }
931        if let Some(p) = &on_b {
932            interval = intersect_intervals(interval, inside_box(p, b))?;
933        }
934        let (lo, hi) = interval;
935        let Curve::Line(line) = &curve else {
936            unreachable!()
937        };
938        let clipped: Curve = ogeom_geom::LineCurve::over(line.axis(), lo, hi)
939            .ok()?
940            .into();
941        let clip2 = |p: &PlanarCurve| -> Option<PlanarCurve> {
942            let PlanarCurve::Line(l) = p else {
943                return Some(p.clone());
944            };
945            Some(Line2d::over(l.axis(), lo, hi).ok()?.into())
946        };
947        let (ca, cb) = (on_a.as_ref().and_then(clip2), on_b.as_ref().and_then(clip2));
948        let tangential = touching_along(&clipped, ca.as_ref(), cb.as_ref(), a, b, tol);
949        return Some(SectionCurve {
950            on_a: ca,
951            on_b: cb,
952            tolerance: 0.0,
953            exact: true,
954            closed: false,
955            tangential,
956            curve: clipped,
957        });
958    }
959
960    // A closed curve: dropped only when wholly outside an extent it has a
961    // pcurve to check against.
962    for (pcurve, surface) in [(&on_a, a), (&on_b, b)] {
963        if let Some(p) = pcurve
964            && !touches_box(p, surface, tol)
965        {
966            return None;
967        }
968    }
969    let tangential = touching_along(&curve, on_a.as_ref(), on_b.as_ref(), a, b, tol);
970    Some(SectionCurve {
971        on_a,
972        on_b,
973        tolerance: 0.0,
974        exact: true,
975        closed,
976        tangential,
977        curve,
978    })
979}
980
981/// Whether the surfaces touch along an exact curve rather than crossing it:
982/// their normals parallel at stations along its length.
983///
984/// Decided through the curve's own pcurves, which is where the normals can
985/// be read without inverting anything. A curve missing a pcurve on either
986/// surface is reported as a crossing, the honest default, since a section
987/// nobody can place in a chart is one nothing can classify as contact
988/// either.
989fn touching_along(
990    curve: &Curve,
991    on_a: Option<&PlanarCurve>,
992    on_b: Option<&PlanarCurve>,
993    a: &SurfaceGeometry,
994    b: &SurfaceGeometry,
995    tol: Tolerances,
996) -> bool {
997    // The chart position of a sample: through the pcurve where one exists,
998    // through the surface's own closed-form inversion where not. A meridian
999    // through a sphere's poles has no pcurve (its longitude jumps half a
1000    // turn at each pole), but every *point* of it inverts fine, and a
1001    // tangency that would be missed for want of a pcurve becomes a crossing
1002    // section lying along a face's own boundary, which is the worst thing a
1003    // section can be.
1004    let sample_uv = |pc: Option<&PlanarCurve>,
1005                     surface: &SurfaceGeometry,
1006                     t: f64|
1007     -> Option<ogeom_math::Point2> {
1008        if let Some(pc) = pc {
1009            return pc.point_at(t, tol).ok();
1010        }
1011        let p = curve.point_at(t, tol).ok()?;
1012        chart_inversion(surface, p, tol)
1013    };
1014    let (lo, hi) = curve.domain();
1015    // Offsets chosen off the round fractions, so a curve through a chart
1016    // degeneracy (a meridian's poles sit at quarters of its turn) is
1017    // sampled beside the degenerate points rather than on them. A sample
1018    // whose inversion still fails is skipped: the point tells us nothing,
1019    // not that the surfaces cross.
1020    let mut judged = 0_usize;
1021    for f in [0.07, 0.19, 0.37, 0.53, 0.71, 0.89] {
1022        let t = (hi - lo).mul_add(f, lo);
1023        let (Some(ua), Some(ub)) = (sample_uv(on_a, a, t), sample_uv(on_b, b, t)) else {
1024            continue;
1025        };
1026        let (Ok(na), Ok(nb)) = (a.normal_at(ua.x, ua.y, tol), b.normal_at(ub.x, ub.y, tol)) else {
1027            continue;
1028        };
1029        if na.vector().cross(nb.vector()).magnitude() > 1e-6 {
1030            return false;
1031        }
1032        judged += 1;
1033    }
1034    judged >= 3
1035}
1036
1037/// A point's chart position on an analytic surface, by closed form.
1038fn chart_inversion(
1039    surface: &SurfaceGeometry,
1040    p: ogeom_math::Point,
1041    tol: Tolerances,
1042) -> Option<ogeom_math::Point2> {
1043    use ogeom_math::elementary;
1044    let (u, v) = match surface {
1045        SurfaceGeometry::Plane(s) => elementary::plane_parameters(&s.plane(), p),
1046        SurfaceGeometry::Cylinder(s) => {
1047            elementary::cylinder_parameters(&s.cylinder(), p, tol).ok()?
1048        }
1049        SurfaceGeometry::Cone(s) => elementary::cone_parameters(&s.cone(), p, tol).ok()?,
1050        SurfaceGeometry::Sphere(s) => elementary::sphere_parameters(&s.sphere(), p, tol).ok()?,
1051        SurfaceGeometry::Torus(s) => elementary::torus_parameters(&s.torus(), p, tol).ok()?,
1052        _ => return None,
1053    };
1054    Some(ogeom_math::Point2::new(u, v))
1055}
1056
1057/// The parameter interval over which a 2D line stays inside a surface's
1058/// parameter box. `None` when it never enters.
1059fn inside_box(pcurve: &PlanarCurve, surface: &SurfaceGeometry) -> Option<(f64, f64)> {
1060    let PlanarCurve::Line(line) = pcurve else {
1061        return None;
1062    };
1063    let ((ua, ub), (va, vb)) = surface.domain();
1064    let axis = line.axis();
1065    let (o, d) = (axis.location, axis.direction.vector());
1066
1067    // The slab test, one axis at a time.
1068    let mut lo = f64::NEG_INFINITY;
1069    let mut hi = f64::INFINITY;
1070    for (origin, direction, low, high) in [(o.x, d.x, ua, ub), (o.y, d.y, va, vb)] {
1071        if direction.abs() <= f64::MIN_POSITIVE {
1072            if origin < low || origin > high {
1073                return None;
1074            }
1075            continue;
1076        }
1077        let (a, b) = ((low - origin) / direction, (high - origin) / direction);
1078        let (near, far) = if a < b { (a, b) } else { (b, a) };
1079        lo = lo.max(near);
1080        hi = hi.min(far);
1081    }
1082    if lo >= hi {
1083        return None;
1084    }
1085    Some((lo, hi))
1086}
1087
1088/// Whether a closed pcurve may pass through the surface's box.
1089fn touches_box(pcurve: &PlanarCurve, surface: &SurfaceGeometry, tol: Tolerances) -> bool {
1090    use ogeom_geom::Curve2d;
1091    let ((ua, ub), (va, vb)) = surface.domain();
1092    let (lo, hi) = pcurve.domain();
1093    // Asked of the spans between samples, not the samples alone: a plane all
1094    // but parallel to a cylinder's axis meets it in an ellipse kilometres
1095    // long, whose image on the cylinder's chart sweeps through a window a few
1096    // millimetres tall in a sliver of its turn, between any two samples.
1097    // Each span is taken as its chord's box widened by the chord's length,
1098    // which holds the curve between them wherever it bends no tighter than
1099    // the samples are apart. Kept wrongly, a curve costs a section the trim
1100    // then cuts to nothing; dropped wrongly, the faces never split.
1101    const SPANS: u32 = 64;
1102    let points: Vec<Option<ogeom_math::Point2>> = (0..=SPANS)
1103        .map(|i| {
1104            pcurve
1105                .point_at(lo + (hi - lo) * f64::from(i) / f64::from(SPANS), tol)
1106                .ok()
1107        })
1108        .collect();
1109    points.windows(2).any(|pair| {
1110        let (Some(p), Some(q)) = (pair[0], pair[1]) else {
1111            return false;
1112        };
1113        let pad = p.distance(q);
1114        // Periodic directions always contain; only a bounded one excludes.
1115        let u_ok =
1116            surface.is_periodic_u() || (p.x.max(q.x) + pad >= ua && p.x.min(q.x) - pad <= ub);
1117        let v_ok =
1118            surface.is_periodic_v() || (p.y.max(q.y) + pad >= va && p.y.min(q.y) - pad <= vb);
1119        u_ok && v_ok
1120    })
1121}
1122
1123/// The overlap of two intervals. `None` when they miss.
1124fn intersect_intervals(a: (f64, f64), b: Option<(f64, f64)>) -> Option<(f64, f64)> {
1125    let b = b?;
1126    let (lo, hi) = (a.0.max(b.0), a.1.min(b.1));
1127    if lo >= hi {
1128        return None;
1129    }
1130    Some((lo, hi))
1131}
1132
1133/// The general path: seed, trace, fit.
1134fn marched(
1135    a: &SurfaceGeometry,
1136    b: &SurfaceGeometry,
1137    options: IntersectOptions,
1138    tol: Tolerances,
1139) -> OgeomResult<SurfaceIntersection> {
1140    let traced = branches(a, b, options.marching, tol)?;
1141    if traced.is_empty() {
1142        return Ok(SurfaceIntersection::Apart);
1143    }
1144    let mut out = Vec::with_capacity(traced.len());
1145    let mut contacts: Vec<crate::march::Traced> = Vec::new();
1146    for branch in &traced {
1147        // A branch along which the two surfaces share their normal is a
1148        // tangency, not a crossing: the marcher's seeding cannot tell the
1149        // noise floor of a tangential valley from a genuine sign change, and
1150        // what it traces there is a stalled fragment of the valley, not a
1151        // section. The valley is still a curve, though, and the tangential
1152        // walker is the one that can follow it, so the fragment becomes a
1153        // seed rather than a discard, and what comes back is marked as
1154        // contact so nobody classifies by it.
1155        if branch_is_tangential(a, b, branch, tol)? {
1156            if let Some(contact) = walk_contact(a, b, branch, &contacts, options.marching, tol)? {
1157                contacts.push(contact);
1158            }
1159            continue;
1160        }
1161        if branch.stopped == crate::march::Stopped::RanOut {
1162            ogeom_bail!(
1163                NotDone,
1164                "a marched section ran out of its point budget before \
1165                 finishing; the seam is longer than the chord affords and \
1166                 fitting the truncation would state a curve that is not there"
1167            );
1168        }
1169        // A fit past its budget is still honest data: the error it reached
1170        // is carried on the record and every consumer widens by it: an
1171        // imported part's ragged pair can trace branches nothing fits, and
1172        // those sections fall outside every trim downstream. Only a trace
1173        // cut off by the point budget, refused above, states a curve that
1174        // is not there. (A boolean marching an *exact* pair whose image has
1175        // no closed form holds its own marched sections to a budget, in
1176        // its own fallback, where a miss is a miss.)
1177        for fitted in fitted_in_pieces(a, b, branch, options.tolerance, tol)? {
1178            out.push(SectionCurve {
1179                curve: fitted.curve.into(),
1180                on_a: Some(fitted.on_a.into()),
1181                on_b: Some(fitted.on_b.into()),
1182                // The sum of the stated parts: the trace is within its chord of
1183                // the truth, the fit within its error of the trace.
1184                tolerance: options.marching.chord + fitted.fit_error,
1185                exact: false,
1186                closed: fitted.closed,
1187                tangential: false,
1188            });
1189        }
1190    }
1191    for contact in &contacts {
1192        let fitted = approximate_branch(a, b, contact, options.tolerance, tol)?;
1193        out.push(SectionCurve {
1194            curve: fitted.curve.into(),
1195            on_a: Some(fitted.on_a.into()),
1196            on_b: Some(fitted.on_b.into()),
1197            tolerance: options.marching.chord + fitted.fit_error,
1198            exact: false,
1199            closed: fitted.closed,
1200            tangential: true,
1201        });
1202    }
1203    if out.is_empty() {
1204        return Ok(SurfaceIntersection::Apart);
1205    }
1206    Ok(SurfaceIntersection::Along(out))
1207}
1208
1209/// A traced branch fitted, in pieces where whole it will not fit.
1210///
1211/// A trace winding several turns round a drum (a thread's flank meeting a
1212/// bore) is long and turns the same way throughout, and one fit of it can
1213/// run out of room and come back with an error of the drum's size. An open
1214/// branch whose fit strays farther from the trace than the trace's own
1215/// step, and so is no longer the curve traced, is split at its middle
1216/// sample and each half fitted the same way, down to a floor of samples
1217/// and depth; the pieces meet at the shared sample. A fit that misses its
1218/// tolerance by less stands whole, its error stated: a caller takes one
1219/// curve per branch where it can, and a few microns do not warrant more.
1220/// So does a closed branch, or one no split helps.
1221fn fitted_in_pieces(
1222    a: &SurfaceGeometry,
1223    b: &SurfaceGeometry,
1224    branch: &crate::march::Traced,
1225    tolerance: f64,
1226    tol: Tolerances,
1227) -> OgeomResult<Vec<crate::approx::IntersectionCurve>> {
1228    const DEPTH: u32 = 6;
1229    const FLOOR: usize = 16;
1230    fn go(
1231        a: &SurfaceGeometry,
1232        b: &SurfaceGeometry,
1233        branch: &crate::march::Traced,
1234        tolerance: f64,
1235        depth: u32,
1236        tol: Tolerances,
1237    ) -> OgeomResult<Vec<crate::approx::IntersectionCurve>> {
1238        let whole = approximate_branch(a, b, branch, tolerance, tol)?;
1239        let step = branch
1240            .points
1241            .windows(2)
1242            .map(|w| w[0].distance(w[1]))
1243            .fold(0.0_f64, f64::max);
1244        if whole.met
1245            || whole.fit_error <= step
1246            || branch.closed()
1247            || depth == 0
1248            || branch.points.len() < 2 * FLOOR
1249        {
1250            return Ok(vec![whole]);
1251        }
1252        let middle = branch.points.len() / 2;
1253        let half = |range: core::ops::RangeInclusive<usize>| crate::march::Traced {
1254            points: branch.points[range.clone()].to_vec(),
1255            on_a: branch.on_a[range.clone()].to_vec(),
1256            on_b: branch.on_b[range].to_vec(),
1257            stopped: branch.stopped,
1258        };
1259        let mut pieces = go(a, b, &half(0..=middle), tolerance, depth - 1, tol)?;
1260        pieces.extend(go(
1261            a,
1262            b,
1263            &half(middle..=branch.points.len() - 1),
1264            tolerance,
1265            depth - 1,
1266            tol,
1267        )?);
1268        // Worse in pieces than whole (a trace that is noise, not length):
1269        // the whole stands.
1270        let worst = pieces.iter().map(|p| p.fit_error).fold(0.0_f64, f64::max);
1271        Ok(if worst < whole.fit_error {
1272            pieces
1273        } else {
1274            vec![whole]
1275        })
1276    }
1277    go(a, b, branch, tolerance, DEPTH, tol)
1278}
1279
1280/// Follow the contact a tangential fragment sits on, unless one already
1281/// traced covers it.
1282///
1283/// A tangential valley hands the crossing marcher several stalled fragments
1284/// (the seeds converge onto the contact from wherever they started and
1285/// wander there), so the fragments are candidates for *one* curve, not
1286/// several. A fragment whose middle already lies on a traced contact is one
1287/// of those repeats.
1288fn walk_contact(
1289    a: &SurfaceGeometry,
1290    b: &SurfaceGeometry,
1291    fragment: &crate::march::Traced,
1292    already: &[crate::march::Traced],
1293    marching: Marching,
1294    tol: Tolerances,
1295) -> OgeomResult<Option<crate::march::Traced>> {
1296    let middle = fragment.points.len() / 2;
1297    let Some(point) = fragment.points.get(middle).copied() else {
1298        return Ok(None);
1299    };
1300    for traced in already {
1301        // Traced points sit a step apart, so "on this curve" has to allow
1302        // half a step of gap to the nearest sample plus the chord budget.
1303        let spacing = traced
1304            .points
1305            .windows(2)
1306            .map(|w| w[0].distance(w[1]))
1307            .fold(0.0f64, f64::max);
1308        let near = traced
1309            .points
1310            .iter()
1311            .map(|p| p.distance(point))
1312            .fold(f64::INFINITY, f64::min);
1313        if near <= spacing.mul_add(0.5, marching.chord.max(tol.confusion())) {
1314            return Ok(None);
1315        }
1316    }
1317    let seed = crate::march::Contact {
1318        point,
1319        on_a: fragment.on_a[middle],
1320        on_b: fragment.on_b[middle],
1321    };
1322    // The walker refuses a seed that is not a contact; that refusal is an
1323    // answer, not a failure: the fragment simply had nothing to follow.
1324    // A walk that stalls where it started says the same thing in points:
1325    // too few to fit, so there is no contact curve to report here.
1326    Ok(trace_tangential(a, b, seed, marching, tol)
1327        .ok()
1328        .filter(|traced| traced.points.len() >= 4))
1329}
1330
1331/// Whether a traced branch runs along a tangency of the two surfaces:
1332/// their normals parallel, sampled along its length.
1333fn branch_is_tangential(
1334    a: &SurfaceGeometry,
1335    b: &SurfaceGeometry,
1336    branch: &crate::march::Traced,
1337    tol: Tolerances,
1338) -> OgeomResult<bool> {
1339    use ogeom_geom::Surface as _;
1340    let count = branch.points.len();
1341    if count == 0 {
1342        return Ok(true);
1343    }
1344    for k in 0..5 {
1345        let i = (k * (count - 1)) / 4;
1346        let (ua, va) = branch.on_a[i.min(count - 1)];
1347        let (ub, vb) = branch.on_b[i.min(count - 1)];
1348        let (dau, dav) = a.d1_at(ua, va, tol)?;
1349        let (dbu, dbv) = b.d1_at(ub, vb, tol)?;
1350        let na = dau.cross(dav);
1351        let nb = dbu.cross(dbv);
1352        let (ma, mb) = (na.magnitude(), nb.magnitude());
1353        if ma <= tol.confusion() || mb <= tol.confusion() {
1354            continue;
1355        }
1356        // The threshold carries the fitted world: a blend surface within a
1357        // fit tolerance of true tangency crosses its host at an angle that
1358        // grows as the square root of that tolerance, and calling such a
1359        // graze transversal splits faces along slivers no classifier can
1360        // hold. Genuinely transversal analytic pairs meeting under two
1361        // degrees are the pathology, not the rule.
1362        if na.cross(nb).magnitude() / (ma * mb) > 3e-2 {
1363            return Ok(false);
1364        }
1365    }
1366    Ok(true)
1367}
1368
1369/// The exact pcurve of a curve lying on a surface, where the projection has
1370/// a closed form; `None` where it does not.
1371///
1372/// Public because the boolean's same-domain handling needs it: two faces on
1373/// one geometric surface may still carry different charts, and the other
1374/// face's boundary edges have to be spoken in this face's parameters before
1375/// they can split it.
1376#[must_use]
1377pub fn exact_pcurve_of(
1378    curve: &Curve,
1379    surface: &SurfaceGeometry,
1380    tol: Tolerances,
1381) -> Option<PlanarCurve> {
1382    exact_pcurve(curve, curve.domain(), surface, tol)
1383}
1384
1385/// As [`exact_pcurve_of`], with the parameter range the caller actually
1386/// uses.
1387///
1388/// A curve's chart image can depend on *which part* of the curve is meant: a
1389/// ruling on a cone crosses the apex, and its angle on the far nappe is half
1390/// a turn from its angle on the near one. The curve's own domain may span
1391/// both (an imported line's usually does), so a caller that knows its edge's
1392/// range must say so, or the exact projection may answer for the wrong side.
1393#[must_use]
1394pub fn exact_pcurve_over(
1395    curve: &Curve,
1396    range: (f64, f64),
1397    surface: &SurfaceGeometry,
1398    tol: Tolerances,
1399) -> Option<PlanarCurve> {
1400    exact_pcurve(curve, range, surface, tol)
1401}
1402
1403/// The exact pcurve of an analytic curve on an analytic surface, where the
1404/// projection has a closed form.
1405///
1406/// Same-parameter by construction: each 2D curve inherits the 3D curve's own
1407/// parameterization, so the two evaluate to the same point of the intersection
1408/// at the same `t`. The cases are the ones where that inheritance is exact;
1409/// anything else returns `None` rather than a fit, because an *exact* result
1410/// with a fitted pcurve would be a curve whose descriptions disagree by an
1411/// amount nothing on it records.
1412fn exact_pcurve(
1413    curve: &Curve,
1414    range: (f64, f64),
1415    surface: &SurfaceGeometry,
1416    tol: Tolerances,
1417) -> Option<PlanarCurve> {
1418    // A trim is a statement about *where* on a curve, not about what it is:
1419    // the basis carries the shape and the trim shares its parameter, so the
1420    // pcurve is the basis's own pcurve trimmed the same way. Answered here
1421    // rather than in every surface's own case, because the answer does not
1422    // depend on the surface at all. A *reversed* trim renumbers, and is left
1423    // alone rather than mis-read.
1424    if let Curve::Trimmed(trimmed) = curve
1425        && !trimmed.is_reversed()
1426    {
1427        let window = ogeom_geom::Curve3d::domain(&**trimmed);
1428        let basis = exact_pcurve(trimmed.basis(), range, surface, tol)?;
1429        return ogeom_geom::Trimmed2d::new(basis, window.0, window.1, tol)
1430            .ok()
1431            .map(Into::into);
1432    }
1433    match surface {
1434        SurfaceGeometry::Plane(p) => on_plane(curve, p.plane(), tol),
1435        SurfaceGeometry::Cylinder(c) => on_cylinder(curve, range, c.cylinder(), tol),
1436        SurfaceGeometry::Sphere(s) => on_sphere(curve, range, s.sphere(), tol),
1437        SurfaceGeometry::Torus(t) => on_torus(curve, t.torus(), tol),
1438        SurfaceGeometry::Cone(c) => on_cone(curve, range, c.cone(), tol),
1439        _ => None,
1440    }
1441}
1442
1443/// The pcurve of a curve on a cone, for the two straight-line families.
1444///
1445/// A ruling (through the apex, on the surface) runs at constant `u`; a
1446/// circle perpendicular to the axis, centred on it, with the radius the cone
1447/// has at that height, runs at constant `v`. Both inherit the 3D curve's own
1448/// parameter, the circle with phase and winding exactly as the cylinder case.
1449/// The ruling's angle is measured over `range`, because the same line has
1450/// the opposite angle on the other side of the apex.
1451fn on_cone(
1452    curve: &Curve,
1453    range: (f64, f64),
1454    cone: ogeom_math::Cone,
1455    tol: Tolerances,
1456) -> Option<PlanarCurve> {
1457    let frame = cone.frame();
1458    let axis_z = frame.z().vector();
1459    let tau = core::f64::consts::TAU;
1460    match curve {
1461        Curve::Circle(c) => {
1462            let circle = c.circle();
1463            if circle.frame().z().vector().cross(axis_z).magnitude() > tol.angular() {
1464                return None;
1465            }
1466            let local = frame.to_local(circle.centre());
1467            if local.x.hypot(local.y) > tol.confusion() {
1468                return None;
1469            }
1470            // The cone's radius at the circle's height must be the circle's.
1471            let expected = cone
1472                .half_angle()
1473                .tan()
1474                .mul_add(local.z, cone.reference_radius());
1475            if (expected - circle.radius()).abs() > tol.confusion() * 10.0 {
1476                return None;
1477            }
1478            let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1479            let at = frame.to_local(start);
1480            let phase = at.y.atan2(at.x);
1481            let winding = circle.frame().z().vector().dot(axis_z).signum();
1482            let towards =
1483                ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1484            Some(
1485                Line2d::over(
1486                    ogeom_math::Axis2::new(Point2::new(phase, local.z), towards),
1487                    0.0,
1488                    tau,
1489                )
1490                .ok()?
1491                .into(),
1492            )
1493        }
1494        Curve::Line(line) => {
1495            // A ruling: verified by sample, not assumed: three points on
1496            // the surface pin a line to it.
1497            let axis = line.axis();
1498            let on = |t: f64| {
1499                let p = axis.location + axis.direction.vector() * t;
1500                cone.distance_to(p) <= tol.confusion() * 10.0
1501            };
1502            if !on(0.0) || !on(1.0) || !on(-1.0) {
1503                return None;
1504            }
1505            // A ruling reaching the tip may be *stated* from the apex
1506            // itself (where the angle is atan2(0, 0), garbage) and its
1507            // own domain usually spans both nappes, where the angles differ
1508            // by half a turn. Measure the angle at whichever end of the
1509            // *used* range stands farthest from the axis: that is the side
1510            // the caller means.
1511            let (lo, hi) = if range.0.is_finite() && range.1.is_finite() && range.0 != range.1 {
1512                range
1513            } else {
1514                line.domain()
1515            };
1516            // Only the used range votes. The line's own origin is stated
1517            // wherever the file likes (some writers park it hundreds of
1518            // kilometres down the infinite line, past the apex on the other
1519            // nappe), and letting it compete reads the angle half a turn
1520            // from the side the edge actually uses.
1521            let mut local: Option<ogeom_math::Point> = None;
1522            for t in [lo, hi] {
1523                if !t.is_finite() {
1524                    continue;
1525                }
1526                let candidate = frame.to_local(axis.location + axis.direction.vector() * t);
1527                if local.is_none_or(|held| candidate.x.hypot(candidate.y) > held.x.hypot(held.y)) {
1528                    local = Some(candidate);
1529                }
1530            }
1531            let local = local?;
1532            if local.x.hypot(local.y) <= tol.confusion() {
1533                return None;
1534            }
1535            let u = local.y.atan2(local.x).rem_euclid(tau);
1536            // Same-parameter exactly: a degree-one spline over the used
1537            // range maps t linearly onto the chart column, whatever rate
1538            // the slant climbs at.
1539            let v_at = |t: f64| {
1540                frame
1541                    .to_local(axis.location + axis.direction.vector() * t)
1542                    .z
1543            };
1544            let knots = ogeom_math::KnotVector::new(vec![lo, lo, hi, hi], 1).ok()?;
1545            Some(
1546                ogeom_geom::BSpline2d::new(
1547                    knots,
1548                    vec![Point2::new(u, v_at(lo)), Point2::new(u, v_at(hi))],
1549                    tol,
1550                )
1551                .ok()?
1552                .into(),
1553            )
1554        }
1555        _ => None,
1556    }
1557}
1558
1559/// The pcurve of a circle on a torus, for the two families that are straight
1560/// lines in `(u, v)`.
1561///
1562/// A *parallel* (centred on the axis, in a plane perpendicular to it) runs
1563/// at constant `v`; a *tube circle* (minor radius, centred on the tube's
1564/// spine, in a plane through the axis) runs at constant `u`. Both inherit
1565/// the circle's own angle, phase and winding included, exactly as the
1566/// cylinder case does; the STEP reader is the consumer that forced the torus
1567/// into this list, fillet faces being tori more often than not.
1568fn on_torus(curve: &Curve, torus: ogeom_math::Torus, tol: Tolerances) -> Option<PlanarCurve> {
1569    let Curve::Circle(c) = curve else {
1570        return None;
1571    };
1572    let circle = c.circle();
1573    let frame = torus.frame();
1574    let axis_z = frame.z().vector();
1575    let normal = circle.frame().z().vector();
1576    let local = frame.to_local(circle.centre());
1577    let tau = core::f64::consts::TAU;
1578
1579    // A parallel of the sweep.
1580    if normal.cross(axis_z).magnitude() <= tol.angular()
1581        && local.x.hypot(local.y) <= tol.confusion()
1582    {
1583        let sin_v = local.z / torus.minor_radius();
1584        let cos_v = (circle.radius() - torus.major_radius()) / torus.minor_radius();
1585        if (sin_v.hypot(cos_v) - 1.0).abs() > tol.confusion() {
1586            return None;
1587        }
1588        let v = sin_v.atan2(cos_v);
1589        let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1590        let at = frame.to_local(start);
1591        let phase = at.y.atan2(at.x);
1592        let winding = normal.dot(axis_z).signum();
1593        let towards =
1594            ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1595        return Some(
1596            Line2d::over(
1597                ogeom_math::Axis2::new(Point2::new(phase, v), towards),
1598                0.0,
1599                tau,
1600            )
1601            .ok()?
1602            .into(),
1603        );
1604    }
1605
1606    // A circle of the tube.
1607    if (circle.radius() - torus.minor_radius()).abs() <= tol.confusion()
1608        && normal.dot(axis_z).abs() <= tol.angular()
1609        && (local.x.hypot(local.y) - torus.major_radius()).abs() <= tol.confusion()
1610        && local.z.abs() <= tol.confusion()
1611    {
1612        let u = local.y.atan2(local.x);
1613        let radial = frame.x().vector() * u.cos() + frame.y().vector() * u.sin();
1614        let xc = circle.frame().x().vector();
1615        let phase = xc.dot(axis_z).atan2(xc.dot(radial));
1616        let winding = normal.dot(radial.cross(axis_z)).signum();
1617        let towards =
1618            ogeom_math::Direction2::new(ogeom_math::Vector2::new(0.0, winding), tol).ok()?;
1619        return Some(
1620            Line2d::over(
1621                ogeom_math::Axis2::new(Point2::new(u, phase), towards),
1622                0.0,
1623                tau,
1624            )
1625            .ok()?
1626            .into(),
1627        );
1628    }
1629    None
1630}
1631
1632/// Project a curve lying in a plane into the plane's own coordinates.
1633///
1634/// Exact for a line, a circle and an ellipse: the plane's frame is orthonormal,
1635/// so lengths and the curves' own parameterizations survive the projection
1636/// unchanged.
1637fn on_plane(curve: &Curve, plane: ogeom_math::Plane, tol: Tolerances) -> Option<PlanarCurve> {
1638    let frame = plane.frame();
1639    let flat = |p: Point| {
1640        let local = frame.to_local(p);
1641        Point2::new(local.x, local.y)
1642    };
1643    let flat_direction = |d: ogeom_math::Direction| {
1644        let tip = flat(frame.origin() + d.vector());
1645        ogeom_math::Direction2::new(tip - flat(frame.origin()), tol).ok()
1646    };
1647    match curve {
1648        Curve::Line(line) => {
1649            let axis = line.axis();
1650            let through = flat(axis.location);
1651            let direction = flat_direction(axis.direction)?;
1652            let (lo, hi) = line.domain();
1653            Some(
1654                Line2d::over(ogeom_math::Axis2::new(through, direction), lo, hi)
1655                    .ok()?
1656                    .into(),
1657            )
1658        }
1659        Curve::Circle(c) => {
1660            let circle = c.circle();
1661            let frame2 = Frame2::from_axes(
1662                flat(circle.centre()),
1663                flat_direction(circle.frame().x())?,
1664                flat_direction(circle.frame().y())?,
1665                tol,
1666            )
1667            .ok()?;
1668            Some(Circle2d::new(Circle2::new(frame2, circle.radius(), tol).ok()?).into())
1669        }
1670        Curve::Ellipse(e) => {
1671            let ellipse = e.ellipse();
1672            let frame2 = Frame2::from_axes(
1673                flat(ellipse.centre()),
1674                flat_direction(ellipse.frame().x())?,
1675                flat_direction(ellipse.frame().y())?,
1676                tol,
1677            )
1678            .ok()?;
1679            Some(
1680                Ellipse2d::new(
1681                    Ellipse2::new(frame2, ellipse.major_radius(), ellipse.minor_radius(), tol)
1682                        .ok()?,
1683                )
1684                .into(),
1685            )
1686        }
1687        Curve::BSpline(b) => {
1688            // Affine invariance: a (rational) B-spline in the plane projects
1689            // into the plane's own coordinates control point by control
1690            // point, knots and weights untouched: exact, and same-parameter
1691            // by construction.
1692            let control = b
1693                .control_points()
1694                .iter()
1695                .map(|w| ogeom_math::Weighted::new(flat((*w).point()), w.weight, tol))
1696                .collect::<Result<Vec<_>, _>>()
1697                .ok()?;
1698            Some(
1699                ogeom_geom::BSpline2d::rational(b.knots().clone(), control)
1700                    .ok()?
1701                    .into(),
1702            )
1703        }
1704        _ => None,
1705    }
1706}
1707
1708/// The pcurve of a curve on a cylinder, where it is a straight line in
1709/// parameter space.
1710///
1711/// A line along the axis runs at constant `u`; a full circle around it runs at
1712/// constant `v`. Both are lines in `(u, v)`, exactly, and both inherit the 3D
1713/// curve's own parameter: height for the line, angle for the circle.
1714fn on_cylinder(
1715    curve: &Curve,
1716    range: (f64, f64),
1717    cylinder: ogeom_math::Cylinder,
1718    tol: Tolerances,
1719) -> Option<PlanarCurve> {
1720    let axis = cylinder.axis();
1721    let frame = cylinder.frame();
1722    match curve {
1723        Curve::Line(line) => {
1724            // Parallel to the axis, on the surface.
1725            let direction = line.axis().direction;
1726            let along = direction.dot(axis.direction);
1727            if !direction.is_parallel(axis.direction, tol) {
1728                return None;
1729            }
1730            let through = line.axis().location;
1731            if (axis.distance_to(through) - cylinder.radius()).abs() > tol.confusion() {
1732                return None;
1733            }
1734            let local = frame.to_local(through);
1735            let u = local.y.atan2(local.x).rem_euclid(core::f64::consts::TAU);
1736            // The 3D line's parameter is length from its origin; at constant u
1737            // the pcurve's `v` runs at the same rate, signed by whether the
1738            // line runs with the axis or against it.
1739            let (lo, hi) = line.domain();
1740            let start = Point2::new(u, local.z);
1741            let towards =
1742                ogeom_math::Direction2::new(ogeom_math::Vector2::new(0.0, along.signum()), tol)
1743                    .ok()?;
1744            Some(
1745                Line2d::over(ogeom_math::Axis2::new(start, towards), lo, hi)
1746                    .ok()?
1747                    .into(),
1748            )
1749        }
1750        Curve::Circle(c) => {
1751            let circle = c.circle();
1752            // Perpendicular to the axis, centred on it, of the same radius.
1753            if circle
1754                .frame()
1755                .z()
1756                .cross_with(axis.direction.vector())
1757                .magnitude()
1758                > tol.angular()
1759            {
1760                return None;
1761            }
1762            if axis.distance_to(circle.centre()) > tol.confusion() {
1763                return None;
1764            }
1765            if (circle.radius() - cylinder.radius()).abs() > tol.confusion() {
1766                return None;
1767            }
1768            let local = frame.to_local(circle.centre());
1769            // Where the circle's own angle zero sits in the cylinder's angle,
1770            // and which way its parameter runs around the axis. A section
1771            // circle inherits its winding from the pair that made it, and one
1772            // wound against the cylinder's `u` (a circle cut by a plane whose
1773            // normal opposes the axis) runs its pcurve in `-u`. Writing `+u`
1774            // unconditionally here was the bug the boolean's drill test found:
1775            // the pcurve evaluated half a turn away from the curve, and the
1776            // face's arrangement tore along a seam that was not there.
1777            let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1778            let at = frame.to_local(start);
1779            let phase = at.y.atan2(at.x);
1780            let winding = circle.frame().z().dot(axis.direction).signum();
1781            let towards =
1782                ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1783            Some(
1784                Line2d::over(
1785                    ogeom_math::Axis2::new(Point2::new(phase, local.z), towards),
1786                    0.0,
1787                    core::f64::consts::TAU,
1788                )
1789                .ok()?
1790                .into(),
1791            )
1792        }
1793        Curve::Ellipse(_) => {
1794            // An oblique plane's section: its plan projection is the
1795            // cylinder's own cross-section circle traced *uniformly*, so
1796            // the chart trace is u = sยทt + ฯ†, v = cโ‚€ + aยทcos t + bยทsin t:
1797            // the trig-affine family. Derived from the curve's own
1798            // evaluations and verified by sample, never assumed.
1799            use ogeom_geom::Curve3d as _;
1800            let tau = core::f64::consts::TAU;
1801            let local = |t: f64| -> Option<ogeom_math::Point> {
1802                Some(frame.to_local(curve.point_at(t, tol).ok()?))
1803            };
1804            let l0 = local(0.0)?;
1805            let lq = local(tau / 4.0)?;
1806            let lh = local(tau / 2.0)?;
1807            // On the surface at all: plan radius must be the cylinder's.
1808            let r = cylinder.radius();
1809            for l in [&l0, &lq, &lh] {
1810                if (l.x.hypot(l.y) - r).abs() > tol.confusion() * 10.0 {
1811                    return None;
1812                }
1813            }
1814            let phase = l0.y.atan2(l0.x);
1815            // Winding from the quarter-turn sample: uniform tracing puts it
1816            // a quarter turn away, one side or the other.
1817            let uq = lq.y.atan2(lq.x);
1818            let step = (uq - phase).rem_euclid(tau);
1819            let winding = if (step - tau / 4.0).abs() < 1e-6 {
1820                1.0
1821            } else if (step - 3.0 * tau / 4.0).abs() < 1e-6 {
1822                -1.0
1823            } else {
1824                return None;
1825            };
1826            // Height coefficients from three samples.
1827            let c0 = f64::midpoint(l0.z, lh.z);
1828            let a = (l0.z - lh.z) / 2.0;
1829            let b = lq.z - c0;
1830            // The trig formula is global (cosine wraps, the linear angle
1831            // unwraps the chart), so the pcurve lives on whatever range the
1832            // edge actually spans, a loop crossing the period included.
1833            let candidate = ogeom_geom::Trig2d::new(
1834                Point2::new(phase, c0),
1835                ogeom_math::Vector2::new(winding, 0.0),
1836                ogeom_math::Vector2::new(0.0, a),
1837                ogeom_math::Vector2::new(0.0, b),
1838                range,
1839            )
1840            .ok()?;
1841            // The same-parameter law, verified at points the derivation
1842            // never touched, inside the range the edge will use.
1843            use ogeom_geom::Curve2d as _;
1844            for i in 0..7 {
1845                let t = range.0 + (range.1 - range.0) * (0.09 + 0.13 * f64::from(i)) / 0.91;
1846                let l = local(t)?;
1847                let chart = candidate.point_at(t, tol).ok()?;
1848                let du = (chart.x - l.y.atan2(l.x)).rem_euclid(tau);
1849                if du.min(tau - du) > 1e-9 {
1850                    return None;
1851                }
1852                if (chart.y - l.z).abs() > tol.confusion() * 10.0 {
1853                    return None;
1854                }
1855            }
1856            Some(PlanarCurve::Trig(candidate))
1857        }
1858        _ => None,
1859    }
1860}
1861
1862/// The pcurve of half a meridian: a great circle through both poles,
1863/// restricted to one side of them.
1864///
1865/// The whole circle has no chart image a single curve can carry (its
1866/// longitude jumps by half a turn at each pole), but each *half* does, and it
1867/// is a straight line. Writing the circle's own parameter as `t` and the
1868/// sphere's axis as `Z = cos ฮฑยทX + sin ฮฑยทY` in the circle's own frame, the
1869/// point's height above the equator is `rยทcos(t โˆ’ ฮฑ)`, so the latitude is
1870/// `asin(cos(t โˆ’ ฮฑ))`, which on `t โˆ’ ฮฑ โˆˆ [0, ฯ€]` is exactly `ฯ€/2 โˆ’ (t โˆ’ ฮฑ)`,
1871/// affine in `t`, with slope one. The longitude is constant on that half and
1872/// half a turn away on the other. So the pcurve is a vertical line in the
1873/// chart, sharing the circle's parameter exactly, and the caller's `range` is
1874/// what says which half is meant.
1875///
1876/// The half is not assumed: the returned line is lifted back through the
1877/// sphere at stations along the range and compared against the circle, so a
1878/// misread orientation is caught here rather than downstream.
1879fn on_meridian(
1880    curve: &ogeom_geom::CircleCurve,
1881    range: (f64, f64),
1882    sphere: ogeom_math::Sphere,
1883    tol: Tolerances,
1884) -> Option<PlanarCurve> {
1885    let circle = curve.circle();
1886    // A reversed circle runs its own angle backwards, and the shifted angle
1887    // below is measured in the *curve's* parameter, so the sign travels with
1888    // it: the sweep flips and so do both the latitude's slope and which half
1889    // of the circle a range names.
1890    let sweep = if curve.is_reversed() { -1.0 } else { 1.0 };
1891    let frame = sphere.frame();
1892    let z = frame.z().vector();
1893    // A great circle: the sphere's own centre and radius, in a plane holding
1894    // the axis. Anything else is not a meridian.
1895    if circle.centre().distance(sphere.centre()) > tol.confusion() {
1896        return None;
1897    }
1898    if (circle.radius() - sphere.radius()).abs() > tol.confusion() {
1899        return None;
1900    }
1901    let (cx, cy) = (circle.frame().x().vector(), circle.frame().y().vector());
1902    let (xz, yz) = (cx.dot(z), cy.dot(z));
1903    // The axis must lie *in* the circle's plane, or the circle is neither a
1904    // parallel nor a meridian and has no closed-form chart image at all.
1905    if xz.hypot(yz) < 1.0 - tol.angular() {
1906        return None;
1907    }
1908    let raw_alpha = yz.atan2(xz);
1909    // `w` is the circle's own horizontal direction: the axis turned a quarter
1910    // turn within the circle's plane.
1911    let w = cx * -raw_alpha.sin() + cy * raw_alpha.cos();
1912    let local = frame.to_local(sphere.centre() + w);
1913    let longitude = local.y.atan2(local.x);
1914
1915    let half = core::f64::consts::PI;
1916    let mid = f64::midpoint(range.0, range.1);
1917    // Where the range sits relative to the poles, in the shifted angle
1918    // `x = sweepยทt โˆ’ ฮฑ` that measures the descent from the north pole.
1919    let x_mid = (sweep * mid - raw_alpha).rem_euclid(core::f64::consts::TAU);
1920    let x_mid = if x_mid > half {
1921        x_mid - core::f64::consts::TAU
1922    } else {
1923        x_mid
1924    };
1925    let span = sweep * (range.1 - range.0);
1926    let (mut x0, mut x1) = (x_mid - span / 2.0, x_mid + span / 2.0);
1927    if x0 > x1 {
1928        core::mem::swap(&mut x0, &mut x1);
1929    }
1930    // The turn count `ฮฑ` was written with is what decides whether the
1931    // latitude comes out inside the chart or a whole turn away from it, so
1932    // the branch the range actually sits on is the one the line is built
1933    // from.
1934    let alpha = sweep.mul_add(mid, -x_mid);
1935    let slack = tol.parametric().max(1e-9);
1936    let (axis_point, towards) = if x0 >= -slack && x1 <= half + slack {
1937        // The descending half: latitude ฯ€/2 โˆ’ (sweepยทt โˆ’ ฮฑ), longitude
1938        // constant.
1939        (
1940            Point2::new(longitude, half.mul_add(0.5, alpha)),
1941            ogeom_math::Vector2::new(0.0, -sweep),
1942        )
1943    } else if x0 >= -half - slack && x1 <= slack {
1944        // The ascending half, half a turn round the chart.
1945        (
1946            Point2::new(longitude + half, half.mul_add(0.5, -alpha)),
1947            ogeom_math::Vector2::new(0.0, sweep),
1948        )
1949    } else {
1950        // The range straddles a pole: no one line covers it.
1951        return None;
1952    };
1953    let towards = ogeom_math::Direction2::new(towards, tol).ok()?;
1954    let margin = (range.1 - range.0) * 0.25;
1955    let line: PlanarCurve = Line2d::over(
1956        ogeom_math::Axis2::new(axis_point, towards),
1957        range.0 - margin,
1958        range.1 + margin,
1959    )
1960    .ok()?
1961    .into();
1962
1963    // Measured, not assumed: the chart line lifted back through the sphere is
1964    // the circle it claims to be.
1965    for k in 0..=4 {
1966        let t = (range.1 - range.0).mul_add(f64::from(k) / 4.0, range.0);
1967        let uv = line.point_at(t, tol).ok()?;
1968        let lifted = ogeom_math::elementary::sphere_at(&sphere, uv.x, uv.y).point;
1969        let want = curve.point_at(t, tol).ok()?;
1970        if lifted.distance(want) > tol.confusion() {
1971            return None;
1972        }
1973    }
1974    Some(line)
1975}
1976
1977/// The pcurve of a circle on a sphere: a parallel of latitude, or one half of
1978/// a meridian.
1979fn on_sphere(
1980    curve: &Curve,
1981    range: (f64, f64),
1982    sphere: ogeom_math::Sphere,
1983    tol: Tolerances,
1984) -> Option<PlanarCurve> {
1985    let Curve::Circle(c) = curve else {
1986        return None;
1987    };
1988    let circle = c.circle();
1989    let frame = sphere.frame();
1990    // Perpendicular to the sphere's axis and centred on it: a parallel of
1991    // latitude, which is a horizontal line in (longitude, latitude).
1992    if circle
1993        .frame()
1994        .z()
1995        .cross_with(frame.z().vector())
1996        .magnitude()
1997        > tol.angular()
1998    {
1999        return on_meridian(c, range, sphere, tol);
2000    }
2001    let local = frame.to_local(circle.centre());
2002    if local.x.abs() > tol.confusion() || local.y.abs() > tol.confusion() {
2003        return None;
2004    }
2005    let latitude = (local.z / sphere.radius()).clamp(-1.0, 1.0).asin();
2006    // Sanity: the circle's radius must be the parallel's.
2007    if (circle.radius() - sphere.radius() * latitude.cos()).abs() > tol.confusion() {
2008        return None;
2009    }
2010    let start = circle.centre() + circle.frame().x().vector() * circle.radius();
2011    let at = frame.to_local(start);
2012    let phase = at.y.atan2(at.x);
2013    // Phase and winding exactly as the cylinder case: a parallel whose own
2014    // axis opposes the sphere's marches its angle *down* the longitude.
2015    let winding = circle.frame().z().vector().dot(frame.z().vector()).signum();
2016    let towards = ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
2017    Some(
2018        Line2d::over(
2019            ogeom_math::Axis2::new(Point2::new(phase, latitude), towards),
2020            0.0,
2021            core::f64::consts::TAU,
2022        )
2023        .ok()?
2024        .into(),
2025    )
2026}
2027
2028#[cfg(test)]
2029#[allow(clippy::unwrap_used, clippy::expect_used)]
2030mod tests {
2031    use super::*;
2032    use ogeom_geom::{Curve2d, Curve3d, CylinderSurface, PlaneSurface, SphereSurface};
2033    use ogeom_math::{Cylinder, Direction, Frame, Plane, Sphere, Vector};
2034
2035    const T: Tolerances = Tolerances::millimetres();
2036
2037    fn sphere(centre: Point, radius: f64) -> SurfaceGeometry {
2038        SphereSurface::new(Sphere::centred(centre, radius, T).unwrap()).into()
2039    }
2040
2041    fn cylinder(axis: Vector, radius: f64) -> SurfaceGeometry {
2042        let frame = Frame::new(
2043            Point::ORIGIN,
2044            Direction::new(axis, T).unwrap(),
2045            Direction::from_cross(axis, Vector::new(0.3, 0.5, 0.9), T).unwrap(),
2046            T,
2047        )
2048        .unwrap();
2049        CylinderSurface::new(Cylinder::new(frame, radius, T).unwrap(), (-4.0, 4.0))
2050            .unwrap()
2051            .into()
2052    }
2053
2054    fn plane(origin: Point, normal: Vector) -> SurfaceGeometry {
2055        PlaneSurface::over(
2056            Plane::through(origin, Direction::new(normal, T).unwrap()),
2057            (-6.0, 6.0),
2058            (-6.0, 6.0),
2059        )
2060        .unwrap()
2061        .into()
2062    }
2063
2064    /// Same-parameter: pcurve lifted through its surface equals the 3D curve,
2065    /// at the same parameter, everywhere sampled.
2066    fn assert_same_parameter(
2067        section: &SectionCurve,
2068        surface: &SurfaceGeometry,
2069        pcurve: &PlanarCurve,
2070        samples: usize,
2071    ) {
2072        let (lo, hi) = section.curve.domain();
2073        let (plo, phi) = pcurve.domain();
2074        assert!(
2075            (lo - plo).abs() < 1e-9 && (hi - phi).abs() < 1e-9,
2076            "domains disagree: [{lo}, {hi}] against [{plo}, {phi}]"
2077        );
2078        for i in 0..=samples {
2079            #[allow(clippy::cast_precision_loss)]
2080            let t = lo + (hi - lo) * i as f64 / samples as f64;
2081            let on_curve = section.curve.point_at(t, T).unwrap();
2082            let at = pcurve.point_at(t, T).unwrap();
2083            let lifted = surface.point_at(at.x, at.y, T).unwrap();
2084            assert!(
2085                on_curve.is_equal(lifted, T),
2086                "at t = {t}: curve {on_curve:?}, lifted {lifted:?}"
2087            );
2088        }
2089    }
2090
2091    #[test]
2092    fn an_analytic_pair_comes_back_exact_with_matching_pcurves() {
2093        // A plane through a cylinder's axis: two lines, and every description
2094        // agrees at the same parameter, which is the claim edges carry and
2095        // booleans rely on.
2096        let drum = cylinder(Vector::Z, 2.0);
2097        let cut = plane(Point::ORIGIN, Vector::X);
2098        let SurfaceIntersection::Along(curves) =
2099            intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2100        else {
2101            panic!("a plane through a cylinder meets it along curves");
2102        };
2103        assert_eq!(curves.len(), 2);
2104        for section in &curves {
2105            assert!(section.exact);
2106            assert!((section.tolerance - 0.0).abs() < f64::EPSILON);
2107            let on_a = section.on_a.as_ref().expect("a line has a cylinder pcurve");
2108            let on_b = section.on_b.as_ref().expect("and a plane pcurve");
2109            assert_same_parameter(section, &drum, on_a, 50);
2110            assert_same_parameter(section, &cut, on_b, 50);
2111        }
2112    }
2113
2114    #[test]
2115    fn an_oblique_cut_gives_the_ellipse_a_trig_pcurve_on_the_drum() {
2116        // The pcurve an earlier plan owed: the oblique ellipse runs
2117        // linearly in the chart angle and sinusoidally in height (the
2118        // trig-affine family), exactly, same-parameter, both sides.
2119        let drum = cylinder(Vector::Z, 2.0);
2120        let angle: f64 = 0.5;
2121        let cut = plane(Point::ORIGIN, Vector::new(0.0, angle.sin(), angle.cos()));
2122        let SurfaceIntersection::Along(curves) =
2123            intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2124        else {
2125            panic!("an oblique plane meets the cylinder along its ellipse");
2126        };
2127        assert_eq!(curves.len(), 1);
2128        let section = &curves[0];
2129        assert!(section.exact);
2130        assert!(matches!(section.curve, Curve::Ellipse(_)));
2131        let on_drum = section
2132            .on_a
2133            .as_ref()
2134            .expect("the oblique ellipse now carries its cylinder pcurve");
2135        assert!(
2136            matches!(on_drum, PlanarCurve::Trig(_)),
2137            "the chart trace is trig-affine: {on_drum:?}"
2138        );
2139        assert_same_parameter(section, &drum, on_drum, 60);
2140        let on_plane = section.on_b.as_ref().expect("and its plane pcurve");
2141        assert_same_parameter(section, &cut, on_plane, 60);
2142    }
2143
2144    #[test]
2145    fn a_perpendicular_cut_gives_a_circle_with_a_straight_pcurve() {
2146        let drum = cylinder(Vector::Z, 2.0);
2147        let cut = plane(Point::new(0.0, 0.0, 1.0), Vector::Z);
2148        let SurfaceIntersection::Along(curves) =
2149            intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2150        else {
2151            panic!("expected curves");
2152        };
2153        assert_eq!(curves.len(), 1);
2154        let section = &curves[0];
2155        assert!(section.closed);
2156        assert!(matches!(section.curve, Curve::Circle(_)));
2157        // On the cylinder the circle is a horizontal line in (u, v).
2158        assert!(matches!(
2159            section.on_a.as_ref().unwrap(),
2160            PlanarCurve::Line(_)
2161        ));
2162        assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 60);
2163        assert_same_parameter(section, &cut, section.on_b.as_ref().unwrap(), 60);
2164    }
2165
2166    #[test]
2167    fn coaxial_cylinder_and_sphere_give_circles_with_pcurves_on_both() {
2168        let drum = cylinder(Vector::Z, 1.5);
2169        let ball = sphere(Point::ORIGIN, 3.0);
2170        let SurfaceIntersection::Along(curves) =
2171            intersect_surfaces(&drum, &ball, IntersectOptions::default(), T).unwrap()
2172        else {
2173            panic!("expected curves");
2174        };
2175        assert_eq!(curves.len(), 2);
2176        for section in &curves {
2177            assert!(section.exact);
2178            assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 40);
2179            assert_same_parameter(section, &ball, section.on_b.as_ref().unwrap(), 40);
2180        }
2181    }
2182
2183    fn torus(origin: Point, axis: Vector, major: f64, minor: f64) -> SurfaceGeometry {
2184        let frame = Frame::new(
2185            origin,
2186            Direction::new(axis, T).unwrap(),
2187            Direction::from_cross(axis, Vector::new(0.3, 0.5, 0.9), T).unwrap(),
2188            T,
2189        )
2190        .unwrap();
2191        ogeom_geom::TorusSurface::new(ogeom_math::Torus::new(frame, major, minor, T).unwrap())
2192            .into()
2193    }
2194
2195    #[test]
2196    fn an_axis_normal_plane_meets_a_torus_in_two_parallels_with_pcurves() {
2197        let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2198        let cut = plane(Point::new(0.0, 0.0, 0.3), Vector::Z);
2199        let SurfaceIntersection::Along(curves) =
2200            intersect_surfaces(&ring, &cut, IntersectOptions::default(), T).unwrap()
2201        else {
2202            panic!("an axis-normal plane through the tube meets it along curves");
2203        };
2204        assert_eq!(curves.len(), 2);
2205        let spread = 0.5_f64.mul_add(0.5, -(0.3 * 0.3)).sqrt();
2206        let mut radii: Vec<f64> = curves
2207            .iter()
2208            .map(|s| {
2209                let Curve::Circle(c) = &s.curve else {
2210                    panic!("a parallel is a circle");
2211                };
2212                c.circle().radius()
2213            })
2214            .collect();
2215        radii.sort_by(|a, b| a.partial_cmp(b).unwrap());
2216        assert!((radii[0] - (2.0 - spread)).abs() < 1e-12);
2217        assert!((radii[1] - (2.0 + spread)).abs() < 1e-12);
2218        for section in &curves {
2219            assert!(section.exact);
2220            assert_same_parameter(section, &ring, section.on_a.as_ref().unwrap(), 48);
2221            assert_same_parameter(section, &cut, section.on_b.as_ref().unwrap(), 48);
2222        }
2223    }
2224
2225    #[test]
2226    fn the_plane_a_ball_rolls_on_touches_its_torus_along_the_circle_it_rolled() {
2227        // Tangency with length is reported as the curve it is (the way a
2228        // tangent plane reports its line on a cylinder), because the blend
2229        // machinery builds faces whose boundaries are exactly these circles,
2230        // and a Touching with no curve in it would read as a refusal upstream.
2231        let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2232        let cut = plane(Point::new(0.0, 0.0, 0.5), Vector::Z);
2233        let SurfaceIntersection::Along(curves) =
2234            intersect_surfaces(&ring, &cut, IntersectOptions::default(), T).unwrap()
2235        else {
2236            panic!("the rolling plane touches along a circle, not at points");
2237        };
2238        assert_eq!(curves.len(), 1);
2239        let Curve::Circle(c) = &curves[0].curve else {
2240            panic!("the tangency is a circle");
2241        };
2242        assert!((c.circle().radius() - 2.0).abs() < 1e-12);
2243        assert_same_parameter(&curves[0], &ring, curves[0].on_a.as_ref().unwrap(), 48);
2244        assert_same_parameter(&curves[0], &cut, curves[0].on_b.as_ref().unwrap(), 48);
2245    }
2246
2247    #[test]
2248    fn a_coaxial_cylinder_meets_a_torus_in_two_parallels_and_touches_in_one() {
2249        let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2250        let drum = cylinder(Vector::Z, 2.2);
2251        let SurfaceIntersection::Along(curves) =
2252            intersect_surfaces(&drum, &ring, IntersectOptions::default(), T).unwrap()
2253        else {
2254            panic!("a coaxial cylinder through the tube meets it along curves");
2255        };
2256        assert_eq!(curves.len(), 2);
2257        for section in &curves {
2258            assert!(section.exact);
2259            let Curve::Circle(c) = &section.curve else {
2260                panic!("a parallel is a circle");
2261            };
2262            assert!((c.circle().radius() - 2.2).abs() < 1e-12);
2263            assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 48);
2264            assert_same_parameter(section, &ring, section.on_b.as_ref().unwrap(), 48);
2265        }
2266
2267        // Tangent at the tube's outer equator: one circle, with both pcurves.
2268        let grazing = cylinder(Vector::Z, 2.5);
2269        let SurfaceIntersection::Along(touch) =
2270            intersect_surfaces(&grazing, &ring, IntersectOptions::default(), T).unwrap()
2271        else {
2272            panic!("the grazing cylinder touches along the equator");
2273        };
2274        assert_eq!(touch.len(), 1);
2275        assert_same_parameter(&touch[0], &grazing, touch[0].on_a.as_ref().unwrap(), 48);
2276        assert_same_parameter(&touch[0], &ring, touch[0].on_b.as_ref().unwrap(), 48);
2277    }
2278
2279    #[test]
2280    fn coaxial_tori_are_the_same_or_meet_in_parallels() {
2281        let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2282        assert!(matches!(
2283            intersect_surfaces(&ring, &ring.clone(), IntersectOptions::default(), T).unwrap(),
2284            SurfaceIntersection::Same
2285        ));
2286
2287        // The same tube lifted half a radius: the profile circles cross
2288        // twice, and each crossing revolves into a parallel shared exactly.
2289        let lifted = torus(Point::new(0.0, 0.0, 0.5), Vector::Z, 2.0, 0.5);
2290        let SurfaceIntersection::Along(curves) =
2291            intersect_surfaces(&ring, &lifted, IntersectOptions::default(), T).unwrap()
2292        else {
2293            panic!("lifted coaxial tori meet along curves");
2294        };
2295        assert_eq!(curves.len(), 2);
2296        for section in &curves {
2297            assert!(section.exact);
2298            assert_same_parameter(section, &ring, section.on_a.as_ref().unwrap(), 48);
2299            assert_same_parameter(section, &lifted, section.on_b.as_ref().unwrap(), 48);
2300        }
2301    }
2302
2303    #[test]
2304    fn a_pair_with_no_closed_form_comes_back_fitted_with_pcurves() {
2305        // Crossed cylinders: the marched path, end to end through one call.
2306        let a = cylinder(Vector::Z, 1.0);
2307        let b = cylinder(Vector::X, 1.6);
2308        let options = IntersectOptions {
2309            tolerance: 1e-5,
2310            marching: Marching {
2311                chord: 1e-5,
2312                ..Marching::default()
2313            },
2314        };
2315        let SurfaceIntersection::Along(curves) = intersect_surfaces(&a, &b, options, T).unwrap()
2316        else {
2317            panic!("crossed cylinders meet along curves");
2318        };
2319        assert_eq!(curves.len(), 2);
2320        for section in &curves {
2321            assert!(!section.exact);
2322            assert!(section.closed);
2323            assert!(
2324                section.tolerance <= 1e-5 + 1e-4,
2325                "got {}",
2326                section.tolerance
2327            );
2328            assert!(section.on_a.is_some() && section.on_b.is_some());
2329
2330            // The fitted curve lies on both cylinders to its stated tolerance.
2331            let (lo, hi) = section.curve.domain();
2332            for i in 0..=200 {
2333                #[allow(clippy::cast_precision_loss)]
2334                let t = lo + (hi - lo) * f64::from(i) / 200.0;
2335                let p = section.curve.point_at(t, T).unwrap();
2336                let (SurfaceGeometry::Cylinder(x), SurfaceGeometry::Cylinder(y)) = (&a, &b) else {
2337                    unreachable!()
2338                };
2339                let off = x
2340                    .cylinder()
2341                    .distance_to(p)
2342                    .abs()
2343                    .max(y.cylinder().distance_to(p).abs());
2344                assert!(
2345                    off <= section.tolerance * 2.0,
2346                    "at t = {t} the fitted curve is {off:e} off, tolerance {}",
2347                    section.tolerance
2348                );
2349            }
2350        }
2351    }
2352
2353    /// A plane all but parallel to a drum's axis meets it in an ellipse ten
2354    /// metres long, which crosses the drum's few units of height only in a
2355    /// sliver of its turn. It is still a section of the two.
2356    #[test]
2357    fn a_plane_all_but_along_the_axis_still_meets_a_short_drum() {
2358        let drum = cylinder(Vector::Z, 1.0);
2359        let wall: SurfaceGeometry = PlaneSurface::over(
2360            Plane::through(
2361                Point::new(0.0, 0.6, 0.0),
2362                Direction::new(Vector::new(0.0, 1.0, 1e-4), T).unwrap(),
2363            ),
2364            (-1e9, 1e9),
2365            (-1e9, 1e9),
2366        )
2367        .unwrap()
2368        .into();
2369        let met = intersect_surfaces(&wall, &drum, IntersectOptions::default(), T).unwrap();
2370        let SurfaceIntersection::Along(sections) = met else {
2371            panic!("the wall crosses the drum: {met:?}");
2372        };
2373        assert_eq!(sections.len(), 1);
2374        let curve = &sections[0].curve;
2375        let (lo, hi) = curve.domain();
2376        let inside = (0..=100_000).any(|k| {
2377            let p = curve
2378                .point_at(lo + (hi - lo) * f64::from(k) / 100_000.0, T)
2379                .unwrap();
2380            p.z.abs() <= 4.0
2381        });
2382        assert!(inside, "and the section runs through the drum's height");
2383    }
2384
2385    /// Every point of a section within its stated tolerance of both
2386    /// surfaces, sampled along it.
2387    fn on_both(section: &SectionCurve, a: &SurfaceGeometry, b: &SurfaceGeometry) {
2388        let (lo, hi) = section.curve.domain();
2389        for k in 0..=64 {
2390            let p = section
2391                .curve
2392                .point_at(lo + (hi - lo) * f64::from(k) / 64.0, T)
2393                .unwrap();
2394            for surface in [a, b] {
2395                let off = match surface {
2396                    SurfaceGeometry::Plane(plane) => plane.plane().signed_distance_to(p).abs(),
2397                    SurfaceGeometry::Cylinder(drum) => {
2398                        let axis = drum.cylinder().axis();
2399                        let rel = p - axis.location;
2400                        let d = axis.direction.vector();
2401                        ((rel - d * rel.dot(d)).magnitude() - drum.cylinder().radius()).abs()
2402                    }
2403                    _ => unreachable!("planes and drums only"),
2404                };
2405                assert!(
2406                    off <= section.tolerance + 1e-9,
2407                    "{p:?} is {off:e} off, stated {:e}",
2408                    section.tolerance
2409                );
2410            }
2411        }
2412    }
2413
2414    /// A plane leaning two hundred-thousandths off a drum's axis, grazing
2415    /// it: the closed form's ellipse is fifty metres long, its parameter
2416    /// too coarse for the drum's eight units of height. The two sections
2417    /// come back as curves along that height, within their stated
2418    /// tolerance of both surfaces.
2419    #[test]
2420    fn a_plane_all_but_along_a_drums_axis_meets_it_in_two_near_lines() {
2421        let drum = cylinder(Vector::Z, 1.0);
2422        let wall: SurfaceGeometry = PlaneSurface::over(
2423            Plane::through(
2424                Point::new(0.0, 0.99, 0.0),
2425                Direction::new(Vector::new(0.0, 1.0, 2e-5), T).unwrap(),
2426            ),
2427            (-1e9, 1e9),
2428            (-1e9, 1e9),
2429        )
2430        .unwrap()
2431        .into();
2432        let met = intersect_surfaces(&wall, &drum, IntersectOptions::default(), T).unwrap();
2433        let SurfaceIntersection::Along(sections) = met else {
2434            panic!("the wall crosses the drum: {met:?}");
2435        };
2436        assert_eq!(sections.len(), 2);
2437        for section in &sections {
2438            assert!(section.tolerance > 0.0 && section.tolerance <= 1e-5);
2439            on_both(section, &wall, &drum);
2440        }
2441    }
2442
2443    /// Two drums whose axes lean five hundred-thousandths apart meet in two
2444    /// curves all but straight, returned as such over the height they share
2445    /// rather than marched.
2446    #[test]
2447    fn drums_all_but_parallel_meet_in_two_near_lines() {
2448        let drill = cylinder(Vector::Z, 1.0);
2449        let frame = Frame::new(
2450            Point::new(1.5, 0.0, 0.0),
2451            Direction::new(Vector::new(5e-5, 0.0, 1.0), T).unwrap(),
2452            Direction::X,
2453            T,
2454        )
2455        .unwrap();
2456        let bore: SurfaceGeometry =
2457            CylinderSurface::new(Cylinder::new(frame, 1.0, T).unwrap(), (-3.0, 3.0))
2458                .unwrap()
2459                .into();
2460        let met = intersect_surfaces(&drill, &bore, IntersectOptions::default(), T).unwrap();
2461        let SurfaceIntersection::Along(sections) = met else {
2462            panic!("the drums cross: {met:?}");
2463        };
2464        assert_eq!(sections.len(), 2);
2465        for section in &sections {
2466            assert!(!section.exact && section.tolerance <= 1e-5);
2467            let (lo, hi) = section.curve.domain();
2468            let (p, q) = (
2469                section.curve.point_at(lo, T).unwrap(),
2470                section.curve.point_at(hi, T).unwrap(),
2471            );
2472            assert!(
2473                (p.z - q.z).abs() > 5.9,
2474                "over the shared height: {p:?} {q:?}"
2475            );
2476            on_both(section, &drill, &bore);
2477        }
2478    }
2479
2480    #[test]
2481    fn exact_lines_are_clipped_to_the_surfaces_extents() {
2482        // The analytic layer answers for the unbounded geometry; the surfaces
2483        // are finite. A section line a billion units long is not something an
2484        // edge can be built on, and one wholly outside the extents is a
2485        // phantom.
2486        let drum = cylinder(Vector::Z, 2.0);
2487        let cut = plane(Point::ORIGIN, Vector::X);
2488        let SurfaceIntersection::Along(curves) =
2489            intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2490        else {
2491            panic!("expected curves");
2492        };
2493        for section in &curves {
2494            let (lo, hi) = section.curve.domain();
2495            // Bounded by the cylinder's height, not by LINE_EXTENT.
2496            assert!(
2497                hi - lo <= 8.0 + 1e-9,
2498                "the line was not clipped: [{lo}, {hi}]"
2499            );
2500            let start = section.curve.point_at(lo, T).unwrap();
2501            let end = section.curve.point_at(hi, T).unwrap();
2502            assert!(start.z >= -4.0 - 1e-9 && end.z <= 4.0 + 1e-9);
2503        }
2504
2505        // A circle at a height the bounded cylinder does not reach is not an
2506        // intersection of these surfaces, however truly the unbounded ones
2507        // meet there.
2508        let high = plane(Point::new(0.0, 0.0, 10.0), Vector::Z);
2509        assert_eq!(
2510            intersect_surfaces(&drum, &high, IntersectOptions::default(), T).unwrap(),
2511            SurfaceIntersection::Apart
2512        );
2513    }
2514
2515    #[test]
2516    fn the_degenerate_answers_pass_through() {
2517        assert_eq!(
2518            intersect_surfaces(
2519                &sphere(Point::ORIGIN, 1.0),
2520                &sphere(Point::new(5.0, 0.0, 0.0), 1.0),
2521                IntersectOptions::default(),
2522                T
2523            )
2524            .unwrap(),
2525            SurfaceIntersection::Apart
2526        );
2527        assert_eq!(
2528            intersect_surfaces(
2529                &sphere(Point::ORIGIN, 1.0),
2530                &sphere(Point::ORIGIN, 1.0),
2531                IntersectOptions::default(),
2532                T
2533            )
2534            .unwrap(),
2535            SurfaceIntersection::Same
2536        );
2537        assert!(matches!(
2538            intersect_surfaces(
2539                &plane(Point::ORIGIN, Vector::Z),
2540                &sphere(Point::new(0.0, 0.0, 2.0), 2.0),
2541                IntersectOptions::default(),
2542                T
2543            )
2544            .unwrap(),
2545            SurfaceIntersection::Touching(ref p) if p.len() == 1
2546        ));
2547    }
2548
2549    #[test]
2550    fn unusable_options_are_refused() {
2551        let a = sphere(Point::ORIGIN, 1.0);
2552        let b = plane(Point::ORIGIN, Vector::Z);
2553        for tolerance in [0.0, -1.0, f64::NAN] {
2554            let options = IntersectOptions {
2555                tolerance,
2556                ..IntersectOptions::default()
2557            };
2558            assert!(intersect_surfaces(&a, &b, options, T).is_err());
2559        }
2560    }
2561
2562    #[test]
2563    fn a_circle_wound_against_the_axis_keeps_its_pcurve_same_parameter() {
2564        // The winding bug the boolean's drill test found: a plane whose
2565        // normal opposes the cylinder's axis cuts a circle wound against the
2566        // cylinder's `u`, and the pcurve must run in `-u` with it. Written
2567        // `+u` unconditionally, the pcurve evaluated half a turn away from
2568        // the curve and every face built on the section tore in parameter
2569        // space. Both windings are pinned by lifting the pcurve through the
2570        // surface and demanding the curve's own point back.
2571        let drum: SurfaceGeometry = CylinderSurface::new(
2572            Cylinder::new(
2573                Frame::new(Point::new(2.0, 2.0, -1.0), Direction::Z, Direction::X, T).unwrap(),
2574                0.5,
2575                T,
2576            )
2577            .unwrap(),
2578            (0.0, 3.0),
2579        )
2580        .unwrap()
2581        .into();
2582        for normal in [Direction::Z, -Direction::Z] {
2583            let frame = Frame::new(Point::ORIGIN, normal, Direction::X, T).unwrap();
2584            let ground: SurfaceGeometry =
2585                PlaneSurface::over(Plane::new(frame), (-4.0, 4.0), (-4.0, 4.0))
2586                    .unwrap()
2587                    .into();
2588            let met = intersect_surfaces(&ground, &drum, IntersectOptions::default(), T).unwrap();
2589            let SurfaceIntersection::Along(curves) = met else {
2590                panic!("a plane through a cylinder sections it");
2591            };
2592            for sc in &curves {
2593                let pcurve = sc
2594                    .on_b
2595                    .as_ref()
2596                    .expect("a circle on its cylinder has a pcurve");
2597                let (lo, hi) = sc.curve.domain();
2598                for i in 0..8 {
2599                    let t = lo + (hi - lo) * f64::from(i) / 8.0;
2600                    let p3 = sc.curve.point_at(t, T).unwrap();
2601                    let uv = pcurve.point_at(t, T).unwrap();
2602                    let lifted = drum
2603                        .point_at(uv.x.rem_euclid(core::f64::consts::TAU), uv.y, T)
2604                        .unwrap();
2605                    assert!(
2606                        p3.distance(lifted) < 1e-9,
2607                        "normal {normal:?}, t {t}: pcurve lifts {lifted:?} against {p3:?}"
2608                    );
2609                }
2610            }
2611        }
2612    }
2613
2614    /// A plane through a ball's own axis cuts a meridian. The whole circle has
2615    /// no chart image (its longitude jumps half a turn at each pole), but
2616    /// each half is a straight line in the chart, exactly, at the circle's own
2617    /// parameter. Pinned by lifting the line back through the sphere and
2618    /// demanding the circle's point, on every half of every orientation.
2619    #[test]
2620    fn a_meridian_half_has_an_exact_line_for_a_pcurve() {
2621        use ogeom_geom::Surface as _;
2622        let half = core::f64::consts::PI;
2623        for (centre, radius) in [(Point::ORIGIN, 4.0), (Point::new(1.0, -2.0, 0.5), 1.25)] {
2624            let ball = sphere(centre, radius);
2625            let SurfaceGeometry::Sphere(s) = &ball else {
2626                panic!("a sphere surface");
2627            };
2628            // Three planes through the axis, at different azimuths, so the
2629            // constant longitude is not accidentally zero.
2630            for azimuth in [0.0_f64, 0.7, 2.4] {
2631                let normal = Vector::new(-azimuth.sin(), azimuth.cos(), 0.0);
2632                let cut = plane(centre, normal);
2633                let SurfaceIntersection::Along(curves) =
2634                    intersect_surfaces(&ball, &cut, IntersectOptions::default(), T).unwrap()
2635                else {
2636                    panic!("a plane through the centre meets the ball along a circle");
2637                };
2638                assert_eq!(curves.len(), 1, "one great circle");
2639                let circle = &curves[0].curve;
2640                assert!(curves[0].exact);
2641                // The whole circle has no chart image; each half does.
2642                assert!(
2643                    exact_pcurve_over(circle, circle.domain(), &ball, T).is_none(),
2644                    "the whole meridian has no single chart image"
2645                );
2646                for (lo, hi) in [(0.0, half), (half, 2.0 * half), (0.3, half - 0.1)] {
2647                    let pcurve = exact_pcurve_over(circle, (lo, hi), &ball, T)
2648                        .expect("half a meridian has an exact pcurve");
2649                    assert!(
2650                        matches!(pcurve, PlanarCurve::Line(_)),
2651                        "and it is a straight line in the chart"
2652                    );
2653                    for i in 0..=16 {
2654                        let t = (hi - lo).mul_add(f64::from(i) / 16.0, lo);
2655                        let want = circle.point_at(t, T).unwrap();
2656                        let uv = pcurve.point_at(t, T).unwrap();
2657                        assert!(
2658                            uv.y >= -half.mul_add(0.5, 1e-12) && uv.y <= half.mul_add(0.5, 1e-12),
2659                            "the latitude stays inside the chart: {}",
2660                            uv.y
2661                        );
2662                        let lifted = ball
2663                            .point_at(uv.x.rem_euclid(core::f64::consts::TAU), uv.y, T)
2664                            .unwrap();
2665                        assert!(
2666                            want.distance(lifted) < 1e-9,
2667                            "azimuth {azimuth}, t {t}: {lifted:?} against {want:?}"
2668                        );
2669                    }
2670                }
2671                // A range straddling a pole has none, and says so rather than
2672                // answering for one side.
2673                assert!(
2674                    exact_pcurve_over(circle, (half - 0.2, half + 0.2), &ball, T).is_none(),
2675                    "a range across a pole has no one line"
2676                );
2677                let _ = s;
2678            }
2679        }
2680    }
2681
2682    /// A trim says *where* on a curve, not what it is. The basis carries the
2683    /// shape and the trim shares its parameter, so a trimmed curve's pcurve is
2684    /// the basis's own pcurve trimmed the same way, on every surface, since
2685    /// the answer does not depend on the surface at all.
2686    ///
2687    /// Found by a corner blend: a fillet's own end cap is a plane, the edges
2688    /// bounding it are trimmed curves, and the boolean refused the coincidence
2689    /// because it could not put a trimmed curve into a chart it plainly lies in.
2690    #[test]
2691    fn a_trimmed_curve_carries_its_basis_pcurve_trimmed_the_same_way() {
2692        use ogeom_geom::TrimmedCurve;
2693        let drum = cylinder(Vector::Z, 2.0);
2694        let ground = plane(Point::new(0.0, 0.0, 1.0), Vector::Z);
2695        // The circle where they meet, and a quarter of it.
2696        let SurfaceIntersection::Along(curves) =
2697            intersect_surfaces(&drum, &ground, IntersectOptions::default(), T).unwrap()
2698        else {
2699            panic!("a plane across a cylinder meets it in a circle");
2700        };
2701        let whole = curves[0].curve.clone();
2702        let (lo, hi) = whole.domain();
2703        let quarter: Curve = TrimmedCurve::new(whole.clone(), lo + 0.3, lo + (hi - lo) / 4.0, T)
2704            .unwrap()
2705            .into();
2706
2707        for surface in [&drum, &ground] {
2708            let full = exact_pcurve_of(&whole, surface, T).expect("the whole circle has one");
2709            let part = exact_pcurve_of(&quarter, surface, T).expect("and so does a quarter of it");
2710            // Same parameter, same point: the trim changed the range and
2711            // nothing else.
2712            let (a, b) = quarter.domain();
2713            for i in 0..=8 {
2714                let t = (b - a).mul_add(f64::from(i) / 8.0, a);
2715                let (whole_at, part_at) =
2716                    (full.point_at(t, T).unwrap(), part.point_at(t, T).unwrap());
2717                assert!(
2718                    whole_at.distance(part_at) < 1e-12,
2719                    "the trim carries the basis: {whole_at:?} against {part_at:?}"
2720                );
2721                // And it lifts back onto the curve it came from.
2722                let lifted = surface
2723                    .point_at(part_at.x.rem_euclid(core::f64::consts::TAU), part_at.y, T)
2724                    .or_else(|_| surface.point_at(part_at.x, part_at.y, T))
2725                    .unwrap();
2726                assert!(
2727                    lifted.distance(quarter.point_at(t, T).unwrap()) < 1e-9,
2728                    "same-parameter, still"
2729                );
2730            }
2731        }
2732    }
2733    #[test]
2734    fn a_far_stated_ruling_reads_its_angle_on_the_used_nappe() {
2735        use ogeom_geom::ConeSurface;
2736        // A 45-degree cone opening along +z, reference radius 24 at the
2737        // frame's origin; a ruling at chart angle 0.01, exactly as a real
2738        // file states it: the line's own origin parked seven hundred
2739        // kilometres down the infinite line, past the apex on the other
2740        // nappe. Only the used range may vote on the angle, or the pcurve
2741        // lands half a turn away and the face triangulates as a fan across
2742        // the whole chart.
2743        let cone =
2744            ogeom_math::Cone::new(Frame::WORLD, 24.0, core::f64::consts::FRAC_PI_4, T).unwrap();
2745        let surface: SurfaceGeometry = ConeSurface::new(cone, (-1e5, 1e5)).unwrap().into();
2746        let u_true = 0.01_f64;
2747        let radial = Vector::new(u_true.cos(), u_true.sin(), 0.0);
2748        // The ruling climbs outward at 45 degrees; its stated origin sits
2749        // far beyond the apex (z = -24 on this cone), on the other nappe.
2750        let direction =
2751            Direction::new((radial + Vector::new(0.0, 0.0, 1.0)) / 2f64.sqrt(), T).unwrap();
2752        let far = -7.0e5;
2753        let origin = Point::ORIGIN + radial * 24.0 + direction.vector() * far;
2754        let line = ogeom_geom::LineCurve::over(
2755            ogeom_math::Axis::new(origin, direction),
2756            far.abs() - 1.0,
2757            far.abs() + 1.0,
2758        )
2759        .unwrap();
2760        let curve: Curve = line.into();
2761        let range = ogeom_geom::Curve3d::domain(&curve);
2762        let pcurve = exact_pcurve_over(&curve, range, &surface, T).expect("a ruling inverts");
2763        let at = pcurve.point_at(range.0, T).unwrap();
2764        let tau = core::f64::consts::TAU;
2765        let gap = (at.x - u_true)
2766            .rem_euclid(tau)
2767            .min(tau - (at.x - u_true).rem_euclid(tau));
2768        assert!(
2769            gap < 1e-6,
2770            "the ruling's chart angle must be the used side's: got u {} against {u_true}",
2771            at.x
2772        );
2773    }
2774}