Skip to main content

brep_construction/construction/
solid_sweep_caps.rs

1//! The WHOLE sweep of a solid along a one-parameter motion, ends included:
2//! caps and wall.
3//!
4//! Along a screw (a turn is a screw of zero advance, a slide one of zero turn)
5//! the velocity field, read in the tool's own frame, does not change with time:
6//! at a boundary point x with outward normal n it is
7//! `g(x, n) = (ω e × (x − a) + c e) · n`. So the tool's boundary splits once
8//! and for all into FRONT (g > 0) and BACK (g < 0) parts, and the GRAZING LOOP
9//! K between them (g = 0 inside a face, or a sharp edge whose two faces have
10//! opposite signs) is fixed on the tool. Where every point of space is inside
11//! the moving tool for ONE interval of time, the sweep over [t0, t1] is bounded
12//! by exactly
13//!
14//! - the back of the tool at t0 (where points start to be covered),
15//! - the front of the tool at t1 (where they stop),
16//! - the WALL: K carried by the motion from t0 to t1.
17//!
18//! The body is assembled directly from those faces with shared edges, never as
19//! a boolean of the tool with a tube (the two meet tangentially along K).
20//!
21//! The one-interval condition is CHECKED, not assumed: points just outside
22//! every built face are walked through the whole motion, and a sweep that
23//! covers any of them (a fold, a buried cap, a turn running into itself) is
24//! refused by name.
25//!
26//! Tools: a convex polyhedron (K a polygon of edges and face chords); a solid
27//! of revolution whose faces are cylinders or cones (split along standing
28//! generators, or along two grazing curves moving round them, fitted), flat
29//! ends wholly front or back, a hemisphere from a pole to an equator or a whole
30//! ball (split along a great circle), or a ring (torus, split along its two
31//! grazing curves round it). Caps keep the tool's exact surfaces; walls are
32//! the K curves carried by quintic splines through the exact motion and its
33//! first two derivatives (error h⁶, 48 spans a turn), a row per quarter turn.
34//!
35//! Moving grazing loops: [`sweep_solid_along`] (a solid of revolution carried
36//! by a frame along a planar curve) and [`sweep_solid_tumbled`] (two turns
37//! about skew axes) split the tool at sample times, sample each piece of K
38//! exactly and loft the walls through time; a tumble that passes over a point
39//! twice is built from one-pass spans of its time, joined.
40//! [`sweep_prism_along`] sweeps a prism along a frame by the plane region the
41//! moving outline covers (an arrangement of its corners', grazing points' and
42//! end positions' paths), extruded. [`sweep_solid_parts`] returns a folding
43//! polyhedron's sweep as the sweeps of its halves through the motion's axis.
44//!
45//! [`sweep_solid_clipped`] adds the case the caller only needs inside a
46//! region: a polyhedron TURNED about the region's axis with both end positions
47//! outside the region's wedge fills the wedge with its (ρ, z) shadow turned,
48//! bounded by exact conic arcs (edges) and segments (face chords).
49use crate::solid_sweep::outline_signed_distance;
50use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
51pub use crate::{make_line, make_revolution, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, OrRefuse, OutlinePiece, SolidMotion, Vec3, Vec4};
52use std::collections::HashMap;
53use std::f64::consts::{FRAC_PI_2, PI, TAU};
54
55/// A tool the whole sweep takes.
56#[derive(Clone, Debug)]
57pub enum SolidTool {
58    /// A convex polyhedron: its corners, and its faces as loops of corner
59    /// indices (either winding; outward is found from the centroid).
60    Polyhedron { vertices: Vec<Vec3>, faces: Vec<Vec<usize>> },
61    /// A solid of revolution: the region `meridian` bounds in the
62    /// half-plane spanned by `radial` (first coordinate, the distance from the
63    /// axis, ≥ 0) and `axis_direction` (second coordinate), turned about the
64    /// axis through `axis_origin` (as [`crate::SweptTool::Revolved`]).
65    Revolved { axis_origin: Vec3, axis_direction: Vec3, radial: Vec3, meridian: Vec<OutlinePiece> },
66}
67
68/// Samples of a fitted pcurve: the image of its edge through the surface's
69/// exact inverse, interpolated (quintic). A rational chart's parameter has a
70/// second-derivative jump at its span joints, so the interpolant errs there
71/// as h³; at 576 that is below 1e-10 of a face's area.
72const PCURVE_SAMPLES: usize = 576;
73
74/// The prefix of every refusal of this operation.
75pub const SOLID_SWEEP_WHOLE_REFUSAL: &str = "sweepSolid";
76
77fn refuse(what: &'static str, message: String) -> KernelRefusal {
78    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
79}
80
81/// The stable slug of an unsupported-geometry refusal of this module.
82fn refused_as(error: &KernelRefusal) -> Option<&str> {
83    match &error.class {
84        crate::RefusalClass::UnsupportedGeometry { what } => Some(what.as_str()),
85        _ => None,
86    }
87}
88
89fn input(what: &'static str, message: String) -> KernelRefusal {
90    KernelRefusal::input(KernelStage::Collect, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
91}
92
93fn frag<T>(result: Result<T, String>, what: &'static str) -> Result<T, KernelRefusal> {
94    result.or_refuse(KernelStage::Fragment, what)
95}
96
97/// The motion `x ↦ a + R(ω t)(x − a) + (c t + c₂ t²) e`: a screw (c₂ = 0;
98/// a turn has c = 0, a slide ω = 0), or a turn whose rise grows as it turns.
99#[derive(Clone, Copy, Debug)]
100pub struct Screw {
101    pub a: Vec3,
102    pub e: Vec3,
103    pub omega: f64,
104    pub c: f64,
105    pub c2: f64,
106    pub t0: f64,
107    pub t1: f64,
108    /// A frame riding a curve instead (then `a` is the curve's start, `e` the
109    /// frame's fixed up direction, `omega` a bound on its turning rate and `c`
110    /// on its speed).
111    pub frame: Option<Frame>,
112    /// Two turns about fixed axes instead (then `a` is the first axis' point).
113    pub turns: Option<Turns>,
114    /// The time whose velocity field splits the tool (default: the middle).
115    pub frozen: Option<f64>,
116    /// How many spans a ring's grazing loop is sampled over, per half of the
117    /// ring (`LOFT_SAMPLES` unless a loft found its rows too coarse).
118    pub loop_samples: usize,
119    /// How far the frame's origin travels from `a` (for speed bounds).
120    pub extent: f64,
121}
122
123/// Two turns driven by one parameter: first `rates[0]·t` about the first
124/// axis, then `rates[1]·t` about the second; both axes fixed in the world.
125#[derive(Clone, Copy, Debug)]
126pub struct Turns {
127    points: [Vec3; 2],
128    directions: [Vec3; 2],
129    rates: [f64; 2],
130}
131
132impl Turns {
133    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
134        let y = self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t));
135        self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t))
136    }
137    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
138        let x = self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], -self.rates[1] * t));
139        self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], -self.rates[0] * t))
140    }
141    /// Velocity of the tool point x at t, read back in the tool's frame.
142    fn velocity(&self, t: f64, x: Vec3) -> Vec3 {
143        let first = x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t);
144        let y = self.points[0].add(first);
145        let moved = y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t);
146        let inner = self.directions[0].cross(first).scale(self.rates[0]);
147        let world = self.directions[1].cross(moved).scale(self.rates[1]).add(inner.rotate_about(self.directions[1], self.rates[1] * t));
148        world.rotate_about(self.directions[1], -self.rates[1] * t).rotate_about(self.directions[0], -self.rates[0] * t)
149    }
150}
151
152/// A frame riding a planar cubic Bézier curve: origin on the curve, first
153/// axis along its tangent, a fixed up direction square to its plane.
154#[derive(Clone, Copy, Debug)]
155pub struct Frame {
156    pub control: [Vec3; 4],
157    pub up: Vec3,
158    /// The tangent's direction at the start.
159    pub start_tangent: Vec3,
160}
161
162impl Frame {
163    fn point(&self, s: f64) -> Vec3 {
164        let [p0, p1, p2, p3] = self.control;
165        let r = 1.0 - s;
166        p0.scale(r * r * r).add(p1.scale(3.0 * r * r * s)).add(p2.scale(3.0 * r * s * s)).add(p3.scale(s * s * s))
167    }
168    fn first(&self, s: f64) -> Vec3 {
169        let [p0, p1, p2, p3] = self.control;
170        let r = 1.0 - s;
171        p1.sub(p0).scale(3.0 * r * r).add(p2.sub(p1).scale(6.0 * r * s)).add(p3.sub(p2).scale(3.0 * s * s))
172    }
173    fn second(&self, s: f64) -> Vec3 {
174        let [p0, p1, p2, p3] = self.control;
175        p2.sub(p1.scale(2.0)).add(p0).scale(6.0 * (1.0 - s)).add(p3.sub(p2.scale(2.0)).add(p1).scale(6.0 * s))
176    }
177    /// The frame's turn from its start, about `up`.
178    fn angle(&self, s: f64) -> f64 {
179        let t = self.first(s);
180        self.up.dot(self.start_tangent.cross(t)).atan2(self.start_tangent.dot(t))
181    }
182    fn angle_rate(&self, s: f64) -> f64 {
183        let (d1, d2) = (self.first(s), self.second(s));
184        self.up.dot(d1.cross(d2)) / d1.dot(d1)
185    }
186}
187
188/// A turn about an axis whose rise along it grows as it turns: turned by t
189/// (radians, right-handed about `axis_direction`) the tool has risen
190/// `rise[0] t + rise[1] t²`, for t from `from` to `to` (a variable-lead
191/// screw).
192#[derive(Clone, Copy, Debug)]
193pub struct RisingTurn {
194    pub axis_origin: Vec3,
195    pub axis_direction: Vec3,
196    pub rise: [f64; 2],
197    pub from: f64,
198    pub to: f64,
199}
200
201impl Screw {
202    pub fn from_motion(motion: &SolidMotion) -> Result<Self, KernelRefusal> {
203        let [step] = motion.steps.as_slice() else {
204            return Err(refuse("motion_steps", "only a single screw, turn or slide is swept whole here".into()));
205        };
206        let e = step
207            .axis_direction
208            .normalized()
209            .map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
210        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
211            return Err(input("range", "the motion's range must run forward".into()));
212        }
213        if step.turn == 0.0 && step.advance == 0.0 {
214            return Err(input("still", "the motion does not move".into()));
215        }
216        Ok(Self { a: step.axis_origin, e, omega: step.turn, c: step.advance, c2: 0.0, t0: motion.from, t1: motion.to, frame: None, turns: None, frozen: None,
217        loop_samples: LOFT_SAMPLES, extent: 0.0 })
218    }
219
220    fn from_rising(motion: &RisingTurn) -> Result<Self, KernelRefusal> {
221        let e = motion.axis_direction.normalized().map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
222        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
223            return Err(input("range", "the motion's range must run forward".into()));
224        }
225        // The rise's rate must keep one sign, or the tool's front and back swap.
226        let rate = |t: f64| motion.rise[0] + 2.0 * motion.rise[1] * t;
227        if rate(motion.from) * rate(motion.to) <= 0.0 {
228            return Err(refuse("rise_turns", "the rise stops or turns back within the motion".into()));
229        }
230        Ok(Self { a: motion.axis_origin, e, omega: 1.0, c: motion.rise[0], c2: motion.rise[1], t0: motion.from, t1: motion.to, frame: None, turns: None, frozen: None,
231        loop_samples: LOFT_SAMPLES, extent: 0.0 })
232    }
233
234    fn advance(&self, t: f64) -> f64 {
235        self.c * t + self.c2 * t * t
236    }
237
238    /// The fastest the motion advances along its axis.
239    fn rate_bound(&self) -> f64 {
240        (self.c + 2.0 * self.c2 * self.t0).abs().max((self.c + 2.0 * self.c2 * self.t1).abs())
241    }
242
243    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
244        if let Some(turns) = &self.turns {
245            return turns.apply(t, x);
246        }
247        if let Some(frame) = &self.frame {
248            return frame.point(t).add(x.sub(self.a).rotate_about(frame.up, frame.angle(t)));
249        }
250        self.a.add(x.sub(self.a).rotate_about(self.e, self.omega * t)).add(self.e.scale(self.advance(t)))
251    }
252
253    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
254        if let Some(turns) = &self.turns {
255            return turns.invert(t, y);
256        }
257        if let Some(frame) = &self.frame {
258            return self.a.add(y.sub(frame.point(t)).rotate_about(frame.up, -frame.angle(t)));
259        }
260        self.a.add(y.sub(self.e.scale(self.advance(t))).sub(self.a).rotate_about(self.e, -self.omega * t))
261    }
262
263    /// Velocity, in the tool's frame, of the tool point x (the same at every t
264    /// for a screw; for a growing rise, at the middle of the motion; the split
265    /// it gives is checked against both ends).
266    pub fn velocity(&self, x: Vec3) -> Vec3 {
267        self.velocity_at(self.frozen.unwrap_or(0.5 * (self.t0 + self.t1)), x)
268    }
269
270    fn velocity_at(&self, t: f64, x: Vec3) -> Vec3 {
271        if let Some(turns) = &self.turns {
272            return turns.velocity(t, x);
273        }
274        if let Some(frame) = &self.frame {
275            // In the riding frame: the speed along the start tangent and the
276            // turn about up through the frame's origin.
277            return frame.start_tangent.scale(frame.first(t).length()).add(frame.up.cross(x.sub(self.a)).scale(frame.angle_rate(t)));
278        }
279        self.e.cross(x.sub(self.a)).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t))
280    }
281
282    /// Value, first and second t-derivative of the path of the tool point x.
283    fn jet(&self, t: f64, x: Vec3) -> (Vec3, Vec3, Vec3) {
284        let r = x.sub(self.a).rotate_about(self.e, self.omega * t);
285        let axial = self.e.scale(r.dot(self.e));
286        let radial = r.sub(axial);
287        let value = self.a.add(r).add(self.e.scale(self.advance(t)));
288        let first = self.e.cross(radial).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t));
289        let second = radial.scale(-self.omega * self.omega).add(self.e.scale(2.0 * self.c2));
290        (value, first, second)
291    }
292
293    fn move_point(&self, t: f64, p: &Vec4) -> Result<Vec4, KernelRefusal> {
294        let x = frag(p.point(), "control_point")?;
295        Ok(Vec4::from_point(self.apply(t, x), p.w))
296    }
297
298    fn move_curve(&self, t: f64, curve: &NurbsCurve) -> Result<NurbsCurve, KernelRefusal> {
299        let points = curve.control_points.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?;
300        frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "moved_curve")
301    }
302
303    fn move_surface(&self, t: f64, surface: &NurbsSurface) -> Result<NurbsSurface, KernelRefusal> {
304        let mut rows = Vec::with_capacity(surface.control_points.len());
305        for row in &surface.control_points {
306            rows.push(row.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?);
307        }
308        frag(
309            NurbsSurface::new(surface.degree_u, surface.degree_v, surface.knots_u.clone(), surface.knots_v.clone(), rows),
310            "moved_surface",
311        )
312    }
313}
314
315/// The motion's times at the ends of its rows: each row of wall turns at most
316/// a quarter turn (long thin faces cost every later reading, and the cut).
317fn row_times(screw: &Screw) -> Vec<f64> {
318    let turned = (screw.omega * (screw.t1 - screw.t0)).abs();
319    let rows = ((turned / (0.5 * PI)).ceil() as usize).max(1);
320    // Breaks off the round fractions of the range, where a caller's workpiece
321    // faces tend to lie (a precaution: an edge lying in a face makes a
322    // degenerate cut).
323    let at = |k: usize| match k {
324        0 => screw.t0,
325        k if k == rows => screw.t1,
326        k => screw.t0 + (screw.t1 - screw.t0) * (k as f64 - 0.381966011250105) / rows as f64,
327    };
328    (0..=rows).map(at).collect()
329}
330
331/// Spans of the quintic carry over [ta, tb]: 48 per turn (error ≈ r·h⁶/46080
332/// ≈ 1e-10·r), at least 4.
333fn carry_segments(screw: &Screw, ta: f64, tb: f64) -> usize {
334    let turned = (screw.omega * (tb - ta)).abs();
335    ((turned / TAU * 48.0).ceil() as usize).max(4)
336}
337
338/// Knots of the C² quintic carry on [0, 1].
339fn carry_knots(segments: usize) -> Vec<f64> {
340    let mut knots = vec![0.0; 6];
341    for k in 1..segments {
342        knots.extend([k as f64 / segments as f64; 3]);
343    }
344    knots.extend([1.0; 6]);
345    knots
346}
347
348/// Control points of the C² quintic spline through the exact path of the tool
349/// point x, its first and second derivatives at `segments + 1` times. Affine
350/// in x, so carrying a rational curve's control points carries the curve.
351fn carry_points(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Vec<Vec3> {
352    let h = (tb - ta) / segments as f64;
353    let at = |k: usize| screw.jet(ta + h * k as f64, x);
354    let piece = |k: usize| {
355        let ((f0, d0, a0), (f1, d1, a1)) = (at(k), at(k + 1));
356        [
357            f0,
358            f0.add(d0.scale(h / 5.0)),
359            f0.add(d0.scale(2.0 * h / 5.0)).add(a0.scale(h * h / 20.0)),
360            f1.sub(d1.scale(2.0 * h / 5.0)).add(a1.scale(h * h / 20.0)),
361            f1.sub(d1.scale(h / 5.0)),
362            f1,
363        ]
364    };
365    let mut points = Vec::with_capacity(3 * segments + 3);
366    let first = piece(0);
367    points.extend_from_slice(&first[..3]);
368    for k in 0..segments - 1 {
369        let (here, next) = (piece(k), piece(k + 1));
370        points.push(here[3]);
371        points.push(here[4].scale(2.0).sub(here[3]));
372        points.push(next[2]);
373    }
374    let last = piece(segments - 1);
375    points.extend_from_slice(&last[3..]);
376    points
377}
378
379fn carry_curve(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Result<NurbsCurve, KernelRefusal> {
380    frag(
381        NurbsCurve::new(5, carry_knots(segments), carry_points(screw, x, ta, tb, segments).into_iter().map(|p| Vec4::from_point(p, 1.0)).collect()),
382        "carry_curve",
383    )
384}
385
386/// A boundary curve of the tool (in its own frame), from point `start` to
387/// point `end` along its parameter.
388struct ToolCurve {
389    curve: NurbsCurve,
390    start: usize,
391    end: usize,
392    degenerate: bool,
393    /// Exact points at `LOFT_SAMPLES + 1` even steps of a natural parameter
394    /// from start to end (meridian place, angle), where a grazing curve
395    /// moves on the tool and its wall is lofted through time.
396    samples: Option<Vec<Vec3>>,
397}
398
399/// Steps of a grazing curve's exact samples for a lofted wall.
400pub const LOFT_SAMPLES: usize = 128;
401
402/// How near a lofted wall keeps to its exact grazing loop, as a fraction of
403/// the sweep's size: every exact sample of the loop, in the middle of every
404/// time span, is within this of the wall.
405///
406/// It was 5e-10. A wall that tight is heavy (a quintic's miss falls as the
407/// sixth power of its span, so each tenfold costs half again as many spans
408/// each way), and whoever reads the solid pays for every span. The measures
409/// do not need it: an interpolant's miss changes sign from span to span and
410/// all but cancels in a volume or an area. Over this hundredfold the lofted
411/// cases' volumes and areas moved by 2e-10 or less.
412const LOFT_TARGET: f64 = 5e-8;
413
414/// A face of the tool after the split along K: its exact surface (normal
415/// outward), its side, and its loop (curve, traversed forward?, pcurve in the
416/// direction of traversal).
417struct Cap {
418    surface: NurbsSurface,
419    front: bool,
420    coedges: Vec<(usize, bool, NurbsCurve)>,
421    /// The surface's exact parameters of a point (in the tool's frame), where
422    /// known: a lofted edge's pcurve is then its exact image.
423    chart: Option<Chart>,
424}
425
426/// How a cap's surface is parameterized, to invert it exactly.
427#[derive(Clone, Copy, Debug)]
428enum Chart {
429    /// `plane_patch(origin, u, v, …)`: (x − origin)·u, (x − origin)·v.
430    Plane { origin: Vec3, u: Vec3, v: Vec3 },
431    /// `make_revolution(origin, w, generatrix, theta)` with the generatrix in the
432    /// meridian half-plane at angle `alpha` (from u1 towards u2).
433    Revolution { origin: Vec3, w: Vec3, u1: Vec3, u2: Vec3, alpha: f64, theta: f64, spans_u: usize, meridian: MeridianChart },
434}
435
436#[derive(Clone, Copy, Debug)]
437enum MeridianChart {
438    /// A segment from m0 to m1 in (ρ, z), parameter 0 -> 1.
439    Line { m0: [f64; 2], m1: [f64; 2] },
440    /// An arc about `centre` in (ρ, z) from angle `start` through `sweep`, as
441    /// `make_revolution` of a point makes it (`spans` arcs).
442    Arc { centre: [f64; 2], start: f64, sweep: f64, spans: usize },
443}
444
445impl Chart {
446    /// Is `x` on the chart's own axis, where its first parameter (the angle
447    /// about the axis) is not defined? A ball's pole.
448    fn at_pole(&self, x: Vec3) -> bool {
449        match *self {
450            Chart::Plane { .. } => false,
451            Chart::Revolution { origin, w, .. } => {
452                let r = x.sub(origin);
453                r.sub(w.scale(r.dot(w))).length() <= 1e-6 * r.length()
454            }
455        }
456    }
457
458    /// The chart's span joints in each parameter (`make_revolution`'s arcs
459    /// in equal spans of [0, 1]), where its parameter's second derivative
460    /// jumps along the surface.
461    fn joints(&self) -> (Vec<f64>, Vec<f64>) {
462        let inner = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
463        match *self {
464            Chart::Plane { .. } => (Vec::new(), Vec::new()),
465            Chart::Revolution { spans_u, meridian, .. } => (
466                inner(spans_u),
467                match meridian {
468                    MeridianChart::Arc { spans, .. } => inner(spans),
469                    MeridianChart::Line { .. } => Vec::new(),
470                },
471            ),
472        }
473    }
474
475    fn invert(&self, x: Vec3) -> [f64; 2] {
476        match *self {
477            Chart::Plane { origin, u, v } => {
478                let d = x.sub(origin);
479                [d.dot(u), d.dot(v)]
480            }
481            Chart::Revolution { origin, w, u1, u2, alpha, theta, spans_u, meridian } => {
482                let r = x.sub(origin);
483                let z = r.dot(w);
484                let rho = r.sub(w.scale(z)).length();
485                let mid = alpha + 0.5 * theta;
486                let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
487                let u = crate::circle_angle_to_parameter(spans_u, theta, psi - alpha);
488                let v = match meridian {
489                    MeridianChart::Line { m0, m1 } => {
490                        let (a, b) = (m1[0] - m0[0], m1[1] - m0[1]);
491                        ((rho - m0[0]) * a + (z - m0[1]) * b) / (a * a + b * b)
492                    }
493                    MeridianChart::Arc { centre, start, sweep, spans } => {
494                        let mid = start + 0.5 * sweep;
495                        let angle = mid + ((z - centre[1]).atan2(rho - centre[0]) - mid + PI).rem_euclid(TAU) - PI;
496                        crate::circle_angle_to_parameter(spans, sweep, angle - start)
497                    }
498                };
499                [u, v]
500            }
501        }
502    }
503}
504
505/// The spans `make_revolution` gives a sweep of `theta`.
506fn spans_of(surface_knots_u: &[f64]) -> usize {
507    (surface_knots_u.len() - 6) / 2 + 1
508}
509
510/// The tool's boundary split along K, in the tool's own frame.
511struct Split {
512    points: Vec<Vec3>,
513    curves: Vec<ToolCurve>,
514    caps: Vec<Cap>,
515    /// Flat ends that slide within their own plane all through the motion.
516    slides: Vec<SlideDisc>,
517    /// Cylinders that slide along their own generators all through it.
518    slide_sides: Vec<SlideSide>,
519    scale: f64,
520    shape: Shape,
521}
522
523/// A flat end about the tool's axis whose every point moves within the
524/// end's own plane (a turn about a parallel axis, a slide across the tool's
525/// axis): neither front nor back. What it sweeps is one face of the sweep in
526/// that plane, bounded by the rim's arcs beside back faces where the motion
527/// starts, its arcs beside front faces where it stops, and the paths of the
528/// points between them. `rim`: the rim's arcs counter-clockwise about the
529/// outward normal `u × v`, each with its direction of traversal.
530struct SlideDisc {
531    centre: Vec3,
532    u: Vec3,
533    v: Vec3,
534    rim: Vec<(usize, bool)>,
535}
536
537/// A cylinder about the tool's axis slid along that axis: every point moves
538/// along its own generator. What it sweeps is the cylinder from one rim where
539/// that rim's neighbour sits (back at the start, front at the end) to the
540/// other rim where its neighbour sits. `patches`: per stretch between two
541/// seam angles, (the angle it starts at, its sweep, the start rim's arc, the
542/// end rim's arc, the rim points at the start angle: start rim, end rim).
543struct SlideSide {
544    origin: Vec3,
545    w: Vec3,
546    patches: Vec<(f64, f64, usize, usize, [usize; 2])>,
547}
548
549/// What the membership oracle measures.
550enum Shape {
551    Planes(Vec<(Vec3, f64)>),
552    Revolved { origin: Vec3, axis: Vec3, meridian: Vec<OutlinePiece> },
553}
554
555impl Split {
556    /// Signed distance to the tool in its own frame (negative inside).
557    fn distance(&self, x: Vec3) -> f64 {
558        match &self.shape {
559            Shape::Planes(planes) => planes.iter().map(|(n, d)| n.dot(x) - d).fold(f64::NEG_INFINITY, f64::max),
560            Shape::Revolved { origin, axis, meridian } => {
561                let r = x.sub(*origin);
562                let z = r.dot(*axis);
563                let rho = r.sub(axis.scale(z)).length();
564                outline_signed_distance(meridian, [rho, z])
565            }
566        }
567    }
568
569    /// K: each curve with a front cap on one side and a back cap on the
570    /// other, with the direction in which the back cap runs along it (the back
571    /// on its left seen from outside).
572    fn grazing(&self) -> Result<Vec<(usize, bool)>, KernelRefusal> {
573        let mut uses: HashMap<usize, Vec<(bool, bool)>> = HashMap::new();
574        for cap in &self.caps {
575            for &(curve, forward, _) in &cap.coedges {
576                uses.entry(curve).or_default().push((forward, cap.front));
577            }
578        }
579        let mut grazing = Vec::new();
580        for (curve, list) in uses {
581            if self.curves[curve].degenerate {
582                continue;
583            }
584            // A sliding end's rim carries no wall: it moves within the end's plane.
585            if list.len() == 1
586                && (self.slides.iter().any(|slide| slide.rim.iter().any(|&(c, _)| c == curve))
587                    || self.slide_sides.iter().any(|side| side.patches.iter().any(|patch| patch.2 == curve || patch.3 == curve)))
588            {
589                continue;
590            }
591            match list.as_slice() {
592                [(fa, front_a), (fb, front_b)] => {
593                    if fa == fb {
594                        return Err(refuse("split_topology", "two caps run one boundary curve the same way".into()));
595                    }
596                    if front_a != front_b {
597                        grazing.push((curve, if *front_a { *fb } else { *fa }));
598                    }
599                }
600                _ => return Err(refuse("split_topology", format!("a boundary curve is used {} times", list.len()))),
601            }
602        }
603        grazing.sort_unstable();
604        Ok(grazing)
605    }
606}
607
608fn uv_line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
609    frag(make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)), "pcurve")
610}
611
612/// The plane through `origin` with in-plane axes u, v (u × v outward), as a
613/// patch covering `points`; and the map to its parameters.
614fn plane_patch(origin: Vec3, u: Vec3, v: Vec3, points: &[Vec3]) -> Result<NurbsSurface, KernelRefusal> {
615    let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
616    for p in points {
617        let q = [p.sub(origin).dot(u), p.sub(origin).dot(v)];
618        for k in 0..2 {
619            lo[k] = lo[k].min(q[k]);
620            hi[k] = hi[k].max(q[k]);
621        }
622    }
623    let at = |s: f64, t: f64| Vec4::from_point(origin.add(u.scale(s)).add(v.scale(t)), 1.0);
624    frag(
625        NurbsSurface::new(
626            1,
627            1,
628            vec![lo[0], lo[0], hi[0], hi[0]],
629            vec![lo[1], lo[1], hi[1], hi[1]],
630            vec![vec![at(lo[0], lo[1]), at(lo[0], hi[1])], vec![at(hi[0], lo[1]), at(hi[0], hi[1])]],
631        ),
632        "plane_surface",
633    )
634}
635
636/// A curve lying in the plane (origin, u, v), as a pcurve of that plane:
637/// its control points projected, weights kept (exact, the map is affine).
638fn plane_pcurve(origin: Vec3, u: Vec3, v: Vec3, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
639    let mut points = Vec::with_capacity(curve.control_points.len());
640    for p in &curve.control_points {
641        let x = frag(p.point(), "control_point")?.sub(origin);
642        points.push(Vec4::from_point(Vec3::new(x.dot(u), x.dot(v), 0.0), p.w));
643    }
644    let pcurve = frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "plane_pcurve")?;
645    if forward { Ok(pcurve) } else { frag(pcurve.reversed(), "plane_pcurve") }
646}
647
648fn split_polyhedron(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<Split, KernelRefusal> {
649    if vertices.len() < 4 || faces.len() < 4 {
650        return Err(input("polyhedron", "a polyhedron needs at least four corners and four faces".into()));
651    }
652    let centroid = vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &p| s.add(p)).scale(1.0 / vertices.len() as f64);
653    let scale = vertices.iter().map(|p| p.sub(centroid).length()).fold(0.0f64, f64::max).max(1e-300);
654    let tolerance = 1e-12 * scale.max(screw.a.sub(centroid).length());
655    let mut loops: Vec<Vec<usize>> = Vec::with_capacity(faces.len());
656    let mut planes = Vec::with_capacity(faces.len());
657    for face in faces {
658        if face.len() < 3 || face.iter().any(|&i| i >= vertices.len()) {
659            return Err(input("face", "a face needs three or more existing corners".into()));
660        }
661        let mut normal = Vec3::new(0.0, 0.0, 0.0);
662        for k in 0..face.len() {
663            let (p, q) = (vertices[face[k]], vertices[face[(k + 1) % face.len()]]);
664            normal = normal.add(p.sub(centroid).cross(q.sub(centroid)));
665        }
666        let mut normal = normal.normalized().map_err(|_| input("face", "a face has no area".into()))?;
667        let mut face = face.clone();
668        if normal.dot(vertices[face[0]].sub(centroid)) < 0.0 {
669            normal = normal.scale(-1.0);
670            face.reverse();
671        }
672        let offset = normal.dot(vertices[face[0]]);
673        for p in vertices {
674            if normal.dot(*p) - offset > 1e-9 * scale {
675                return Err(refuse("not_convex", "the polyhedron is not convex".into()));
676            }
677        }
678        for &i in &face {
679            if (normal.dot(vertices[i]) - offset).abs() > 1e-9 * scale {
680                return Err(input("face", "a face's corners are not in one plane".into()));
681            }
682        }
683        loops.push(face);
684        planes.push((normal, offset));
685    }
686    // Each face's grazing value (affine along the face).
687    let g = |face: usize, x: Vec3| -> f64 {
688        let value = screw.velocity(x).dot(planes[face].0);
689        if value.abs() <= tolerance * screw.velocity(x).length().max(1.0) { 0.0 } else { value }
690    };
691    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
692    for (index, face) in loops.iter().enumerate() {
693        for k in 0..face.len() {
694            owner.insert((face[k], face[(k + 1) % face.len()]), index);
695        }
696    }
697    for &(i, j) in owner.keys() {
698        if !owner.contains_key(&(j, i)) {
699            return Err(input("closed", "the polyhedron's faces do not close".into()));
700        }
701    }
702    // Split points on edges: where either neighbour's grazing value crosses zero.
703    let mut points: Vec<Vec3> = vertices.to_vec();
704    let mut edge_splits: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
705    let mut keys: Vec<(usize, usize)> = owner.keys().copied().filter(|&(i, j)| i < j).collect();
706    keys.sort_unstable();
707    for (i, j) in keys {
708        let mut params: Vec<f64> = Vec::new();
709        for f in [owner[&(i, j)], owner[&(j, i)]] {
710            let (gi, gj) = (g(f, vertices[i]), g(f, vertices[j]));
711            if gi * gj < 0.0 {
712                params.push(gi / (gi - gj));
713            }
714        }
715        params.sort_by(|a, b| a.total_cmp(b));
716        params.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
717        let mut list = Vec::new();
718        for s in params {
719            points.push(vertices[i].add(vertices[j].sub(vertices[i]).scale(s)));
720            list.push(points.len() - 1);
721        }
722        edge_splits.insert((i, j), list);
723    }
724    let splits_along = |i: usize, j: usize| -> Vec<usize> {
725        if i < j {
726            edge_splits[&(i, j)].clone()
727        } else {
728            edge_splits[&(j, i)].iter().rev().copied().collect()
729        }
730    };
731    // Sub-faces as point rings, counter-clockwise from outside.
732    let mut rings: Vec<(Vec<usize>, usize, bool)> = Vec::new();
733    for (index, face) in loops.iter().enumerate() {
734        let mut ring: Vec<usize> = Vec::new();
735        for k in 0..face.len() {
736            ring.push(face[k]);
737            ring.extend(splits_along(face[k], face[(k + 1) % face.len()]));
738        }
739        let values: Vec<f64> = ring.iter().map(|&p| g(index, points[p])).collect();
740        let positive = values.iter().any(|&v| v > 0.0);
741        let negative = values.iter().any(|&v| v < 0.0);
742        if !positive && !negative {
743            return Err(refuse("face_in_own_plane", format!("face {index} moves in its own plane (its sweep is flat)")));
744        }
745        if !(positive && negative) {
746            rings.push((ring, index, positive));
747            continue;
748        }
749        let zeros: Vec<usize> = (0..ring.len()).filter(|&k| values[k] == 0.0).collect();
750        if zeros.len() != 2 {
751            return Err(refuse("grazing_split", format!("face {index} meets its grazing line {} times", zeros.len())));
752        }
753        let (za, zb) = (zeros[0], zeros[1]);
754        if za + 1 == zb || (zb + 1) % ring.len() == za {
755            return Err(refuse("grazing_split", format!("face {index} is split along one of its own edges")));
756        }
757        let first: Vec<usize> = (za..=zb).map(|k| ring[k]).collect();
758        let second: Vec<usize> = (zb..ring.len()).chain(0..=za).map(|k| ring[k]).collect();
759        let first_front = values[za + 1] > 0.0;
760        rings.push((first, index, first_front));
761        rings.push((second, index, !first_front));
762    }
763    // A growing rise moves the grazing lines: every sub-face must keep its side
764    // at both ends of the motion.
765    if screw.c2 != 0.0 {
766        for (ring, face, front) in &rings {
767            for &p in ring {
768                for t in [screw.t0, screw.t1] {
769                    let value = screw.velocity_at(t, points[p]).dot(planes[*face].0);
770                    let slack = tolerance * screw.velocity_at(t, points[p]).length().max(1.0);
771                    if (*front && value < -slack) || (!*front && value > slack) {
772                        return Err(refuse("rising_sides", format!("face {face} changes side as the rise grows")));
773                    }
774                }
775            }
776        }
777    }
778    // Curves: one straight segment per point pair.
779    let mut curves: Vec<ToolCurve> = Vec::new();
780    let mut by_pair: HashMap<(usize, usize), usize> = HashMap::new();
781    let mut caps = Vec::with_capacity(rings.len());
782    for (ring, face, front) in rings {
783        let normal = planes[face].0;
784        let origin = points[ring[0]];
785        let u = frag(points[ring[1]].sub(origin).normalized(), "plane_axis")?;
786        let v = normal.cross(u);
787        let corners: Vec<Vec3> = ring.iter().map(|&p| points[p]).collect();
788        let surface = plane_patch(origin, u, v, &corners)?;
789        let mut coedges = Vec::with_capacity(ring.len());
790        for k in 0..ring.len() {
791            let (p, q) = (ring[k], ring[(k + 1) % ring.len()]);
792            let key = (p.min(q), p.max(q));
793            let index = match by_pair.get(&key) {
794                Some(&index) => index,
795                None => {
796                    curves.push(ToolCurve {
797                        curve: frag(make_line(points[key.0], points[key.1]), "line")?,
798                        start: key.0,
799                        end: key.1,
800                        degenerate: false,
801                        samples: None,
802                    });
803                    by_pair.insert(key, curves.len() - 1);
804                    curves.len() - 1
805                }
806            };
807            let forward = p == key.0;
808            coedges.push((index, forward, plane_pcurve(origin, u, v, &curves[index].curve, forward)?));
809        }
810        caps.push(Cap { surface, front, coedges, chart: Some(Chart::Plane { origin, u, v }) });
811    }
812    Ok(Split { points, curves, caps, slides: Vec::new(), slide_sides: Vec::new(), scale, shape: Shape::Planes(planes) })
813}
814
815/// The grazing value `A cos ψ + B sin ψ + C` of a face of revolution at one
816/// meridian point, from three samples.
817pub fn harmonic(g: impl Fn(f64) -> f64) -> (f64, f64, f64) {
818    let (g0, g90, g180) = (g(0.0), g(0.5 * PI), g(PI));
819    let c = 0.5 * (g0 + g180);
820    (0.5 * (g0 - g180), g90 - c, c)
821}
822
823pub fn piece_point(piece: &OutlinePiece, s: f64) -> [f64; 2] {
824    match *piece {
825        OutlinePiece::Line { from, to } => [from[0] + (to[0] - from[0]) * s, from[1] + (to[1] - from[1]) * s],
826        OutlinePiece::Arc { centre, radius, start, end } => {
827            let angle = start + (end - start) * s;
828            [centre[0] + radius * angle.cos(), centre[1] + radius * angle.sin()]
829        }
830        OutlinePiece::Ellipse { centre, semi, rotation, start, end } => crate::solid_sweep::ellipse_point(centre, semi, rotation, start + (end - start) * s),
831    }
832}
833
834/// The whole sweep takes meridians of lines and circular arcs; an elliptic
835/// piece is swept only by [`crate::sweep_solid_within`]'s region engine.
836fn refuse_elliptic(meridian: &[OutlinePiece]) -> Result<(), KernelRefusal> {
837    if meridian.iter().any(|piece| matches!(piece, OutlinePiece::Ellipse { .. })) {
838        return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into()));
839    }
840    Ok(())
841}
842
843fn split_revolved(
844    screw: &Screw,
845    origin: Vec3,
846    axis: Vec3,
847    radial: Vec3,
848    meridian: &[OutlinePiece],
849) -> Result<Split, KernelRefusal> {
850    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
851    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
852    let u2 = w.cross(u1);
853    refuse_elliptic(meridian)?;
854    if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian {
855        if ((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius {
856            return split_torus(screw, origin, w, u1, u2, *centre, *radius, meridian);
857        }
858    }
859    let at = |rho: f64, z: f64, psi: f64| origin.add(w.scale(z)).add(u1.scale(rho * psi.cos())).add(u2.scale(rho * psi.sin()));
860    let scale = meridian
861        .iter()
862        .flat_map(|p| [piece_point(p, 0.0), piece_point(p, 1.0)])
863        .map(|q| q[0].abs().max(q[1].abs()))
864        .fold(0.0f64, f64::max)
865        .max(1e-300);
866    let on_axis = |q: [f64; 2]| q[0].abs() <= 1e-12 * scale;
867    // Orientation of the meridian outline (+1 counter-clockwise in (ρ, z)).
868    let mut area = 0.0;
869    for piece in meridian {
870        for k in 0..16 {
871            let (p, q) = (piece_point(piece, k as f64 / 16.0), piece_point(piece, (k + 1) as f64 / 16.0));
872            area += p[0] * q[1] - q[0] * p[1];
873        }
874    }
875    // Work counter-clockwise in (ρ, z): a revolved patch's u × v is then outward.
876    let reversed_meridian: Vec<OutlinePiece>;
877    let meridian: &[OutlinePiece] = if area > 0.0 {
878        meridian
879    } else {
880        reversed_meridian = meridian
881            .iter()
882            .rev()
883            .map(|piece| match *piece {
884                OutlinePiece::Line { from, to } => OutlinePiece::Line { from: to, to: from },
885                OutlinePiece::Arc { centre, radius, start, end } => OutlinePiece::Arc { centre, radius, start: end, end: start },
886                OutlinePiece::Ellipse { centre, semi, rotation, start, end } => OutlinePiece::Ellipse { centre, semi, rotation, start: end, end: start },
887            })
888            .collect();
889        &reversed_meridian
890    };
891    let ccw = true;
892    // Outward normal in (ρ, z) of a piece at s.
893    let normal = |piece: &OutlinePiece, s: f64| -> [f64; 2] {
894        let (p, q) = (piece_point(piece, (s - 1e-6).max(0.0)), piece_point(piece, (s + 1e-6).min(1.0)));
895        let (dx, dz) = (q[0] - p[0], q[1] - p[1]);
896        let length = dx.hypot(dz);
897        if ccw { [dz / length, -dx / length] } else { [-dz / length, dx / length] }
898    };
899    let g = |piece: &OutlinePiece, s: f64, psi: f64| -> f64 {
900        let m = piece_point(piece, s);
901        let n = normal(piece, s);
902        let x = at(m[0], m[1], psi);
903        let normal = w.scale(n[1]).add(u1.scale(n[0] * psi.cos())).add(u2.scale(n[0] * psi.sin()));
904        screw.velocity(x).dot(normal)
905    };
906    // The faces: pieces off the axis.
907    let faces: Vec<usize> = (0..meridian.len())
908        .filter(|&i| !(matches!(meridian[i], OutlinePiece::Line { .. }) && on_axis(piece_point(&meridian[i], 0.0)) && on_axis(piece_point(&meridian[i], 1.0))))
909        .collect();
910    // Each face's split angles (where K meets it, constant along it), or its
911    // great circle.
912    enum Kind {
913        /// A cylinder or cone (or a flat end) split along generators at these
914        /// angles (empty: one side).
915        Ruled(Vec<f64>),
916        /// A cylinder or cone whose two grazing curves move round it along
917        /// the meridian (`branches`), from rim to rim.
918        Moving,
919        /// A hemisphere from a pole to an equator rim, split by the great
920        /// circle square to its centre's velocity.
921        Sphere { centre: Vec3, pole_at_start: bool },
922        /// A whole ball (a half circle from pole to pole), split by that
923        /// great circle into two hemispheres.
924        Ball { centre: Vec3, radius: f64 },
925        /// A rounded corner (a zone of a torus: an arc whose centre is off the
926        /// axis), crossed by K as a graph v(ψ) of the tube angle for ψ from
927        /// `psi_a` to `psi_b`, entering and leaving at the same rim (the end
928        /// rim when `at_end`).
929        TorusZone { psi_a: f64, psi_b: f64, at_end: bool },
930        /// A flat end that slides within its own plane (`SlideDisc`).
931        Slide,
932        /// A cylinder slid along its own axis (`SlideSide`).
933        SlideSide,
934        /// A rounded corner split along meridian arcs at these angles (the
935        /// grazing curve keeps its angle about the axis: a turn about a
936        /// parallel axis, a slide across the tool's axis).
937        RuledArc(Vec<f64>),
938    }
939    // The two grazing angles of a cylinder or cone at s, the lower and the
940    // upper, unwrapped against s = 0: the front lies between them.
941    let branches = |piece: &OutlinePiece, s: f64| -> Option<(f64, f64)> {
942        let reference = {
943            let (a, b, _) = harmonic(|psi| g(piece, 0.0, psi));
944            b.atan2(a)
945        };
946        let (a, b, c) = harmonic(|psi| g(piece, s, psi));
947        let r = a.hypot(b);
948        if !(c.abs() < r * (1.0 - 1e-9)) {
949            return None;
950        }
951        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
952        let spread = (-c / r).acos();
953        Some((base - spread, base + spread))
954    };
955    let mut kinds: Vec<Kind> = Vec::with_capacity(faces.len());
956    for &i in &faces {
957        let piece = &meridian[i];
958        match *piece {
959            OutlinePiece::Ellipse { .. } => return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into())),
960            OutlinePiece::Line { .. } => {
961                let roots = |s: f64| -> Vec<f64> {
962                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
963                    let r = a.hypot(b);
964                    if c.abs() >= r * (1.0 - 1e-12) {
965                        return Vec::new();
966                    }
967                    let base = b.atan2(a);
968                    let spread = (-c / r).acos();
969                    let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
970                    list.sort_by(|x, y| x.total_cmp(y));
971                    list
972                };
973                // Where the grazing value vanishes all round (a rim through
974                // the motion's axis turning in its own plane) it names no
975                // angle; read the roots where it does not.
976                let alive = |s: f64| {
977                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
978                    a.hypot(b).max(c.abs()) > 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound())
979                };
980                let readings: Vec<Vec<f64>> = [0.0, 0.5, 1.0].into_iter().filter(|&t| alive(t)).map(roots).collect();
981                if readings.is_empty() {
982                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
983                    let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
984                    if flat && (on_axis(m0) || on_axis(m1)) {
985                        kinds.push(Kind::Slide);
986                        continue;
987                    }
988                    let upright = (m0[0] - m1[0]).abs() <= 1e-12 * scale;
989                    if upright && screw.omega == 0.0 && screw.turns.is_none() && screw.frame.is_none() {
990                        kinds.push(Kind::SlideSide);
991                        continue;
992                    }
993                    return Err(refuse("revolved_grazing", format!("meridian piece {i} grazes all over")));
994                }
995                let r0 = readings[0].clone();
996                let still = readings.iter().all(|r| r.len() == r0.len() && r.iter().zip(&r0).all(|(x, y)| (x - y).abs() < 1e-10));
997                if still {
998                    // A face wholly on one side that is not a disc about the
999                    // axis (a cone to its point, an annulus, a whole side):
1000                    // two halves of the same side, seamed at 0 and π.
1001                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1002                    let disc = (m0[1] - m1[1]).abs() <= 1e-12 * scale && (on_axis(m0) || on_axis(m1));
1003                    kinds.push(Kind::Ruled(if r0.is_empty() && !disc { vec![0.0, PI] } else { r0 }));
1004                    continue;
1005                }
1006                let mut previous: Option<(f64, f64)> = None;
1007                for k in 0..=64 {
1008                    let Some(pair) = branches(piece, k as f64 / 64.0) else {
1009                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} do not run rim to rim")));
1010                    };
1011                    if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
1012                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} turn too fast")));
1013                    }
1014                    previous = Some(pair);
1015                }
1016                kinds.push(Kind::Moving);
1017            }
1018            OutlinePiece::Arc { centre, radius, start, end } => {
1019                let (p0, p1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1020                let span = (end - start).abs();
1021                let centre_on_axis = on_axis(centre);
1022                let pole_at_start = on_axis(p0);
1023                let equator = |p: [f64; 2]| (p[1] - centre[1]).abs() <= 1e-12 * scale && (p[0] - radius).abs() <= 1e-12 * scale;
1024                if centre_on_axis && (span - PI).abs() < 1e-12 && pole_at_start && on_axis(p1) {
1025                    kinds.push(Kind::Ball { centre: origin.add(w.scale(centre[1])), radius });
1026                    continue;
1027                }
1028                if centre[0] > radius * (1.0 + 1e-9) && end > start && span <= PI + 1e-12 {
1029                    let at_rim = |v: f64| [centre[0] + radius * v.cos(), centre[1] + radius * v.sin()];
1030                    let g_tube = |psi: f64, v: f64| -> f64 {
1031                        let m = at_rim(v);
1032                        let x = at(m[0], m[1], psi);
1033                        let normal = w.scale(v.sin()).add(u1.scale(v.cos() * psi.cos())).add(u2.scale(v.cos() * psi.sin()));
1034                        screw.velocity(x).dot(normal)
1035                    };
1036                    // K at the same angles about the axis all along the arc?
1037                    {
1038                        let roots_at = |v: f64| -> Option<Vec<f64>> {
1039                            let (a, b, c) = harmonic(|psi| g_tube(psi, v));
1040                            let r = a.hypot(b);
1041                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1042                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1043                                return None;
1044                            }
1045                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1046                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1047                            list.sort_by(|x, y| x.total_cmp(y));
1048                            Some(list)
1049                        };
1050                        let readings: Vec<Option<Vec<f64>>> = [0.25, 0.5, 0.75].into_iter().map(|t| roots_at(start + (end - start) * t)).collect();
1051                        if let [Some(r0), Some(r1), Some(r2)] = readings.as_slice() {
1052                            if r0.iter().zip(r1).chain(r0.iter().zip(r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1053                                kinds.push(Kind::RuledArc(r0.clone()));
1054                                continue;
1055                            }
1056                        }
1057                    }
1058                    if span >= PI {
1059                        return Err(refuse("revolved_arc", format!("meridian piece {i}: a half-round rim is swept only where its grazing curves keep their angle")));
1060                    }
1061                    let in_zone = |psi: f64| -> Result<Option<f64>, KernelRefusal> {
1062                        let (a, b, c) = harmonic(|v| g_tube(psi, v));
1063                        let r = a.hypot(b);
1064                        if !(c.abs() < r) {
1065                            return Ok(None);
1066                        }
1067                        let base = b.atan2(a);
1068                        let spread = (-c / r).acos();
1069                        let inside: Vec<f64> = [base - spread, base + spread]
1070                            .into_iter()
1071                            .map(|v| start + (v - start).rem_euclid(TAU))
1072                            .filter(|&v| v <= end)
1073                            .collect();
1074                        match inside.as_slice() {
1075                            [] => Ok(None),
1076                            [v] => Ok(Some(*v)),
1077                            _ => Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner twice at one angle"))),
1078                        }
1079                    };
1080                    let count = 720;
1081                    let has: Vec<bool> = (0..count).map(|k| in_zone(TAU * k as f64 / count as f64).map(|r| r.is_some())).collect::<Result<_, _>>()?;
1082                    let rises: Vec<usize> = (0..count).filter(|&k| has[k] && !has[(k + count - 1) % count]).collect();
1083                    let falls: Vec<usize> = (0..count).filter(|&k| !has[k] && has[(k + count - 1) % count]).collect();
1084                    let ([rise], [fall]) = (rises.as_slice(), falls.as_slice()) else {
1085                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve does not cross the rounded corner once")));
1086                    };
1087                    // The crossing's ends: roots of the grazing value along the rim it meets.
1088                    let estimate = |k: usize| TAU * (k as f64 - 0.5) / count as f64;
1089                    let (ea, eb) = (estimate(*rise), estimate(*fall));
1090                    let sample = |k: usize| TAU * (k % count) as f64 / count as f64;
1091                    let probe_v = in_zone(sample(*rise))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1092                    let at_end = (probe_v - end).abs() < (probe_v - start).abs();
1093                    let rim_v = if at_end { end } else { start };
1094                    let (a, b, c) = harmonic(|psi| g_tube(psi, rim_v));
1095                    let r = a.hypot(b);
1096                    let base = b.atan2(a);
1097                    let spread = (-c / r).acos();
1098                    let roots = [base - spread, base + spread];
1099                    let nearest = |e: f64| roots.iter().copied().min_by(|x, y| ((x - e + PI).rem_euclid(TAU) - PI).abs().total_cmp(&((y - e + PI).rem_euclid(TAU) - PI).abs())).expect("two");
1100                    let (psi_a, psi_b) = (nearest(ea).rem_euclid(TAU), nearest(eb).rem_euclid(TAU));
1101                    let psi_b = if psi_b <= psi_a { psi_b + TAU } else { psi_b };
1102                    let leave_v = in_zone(sample(*fall + count - 1))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1103                    if ((leave_v - end).abs() < (leave_v - start).abs()) != at_end {
1104                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner from rim to rim")));
1105                    }
1106                    kinds.push(Kind::TorusZone { psi_a, psi_b, at_end });
1107                    continue;
1108                }
1109                if !(centre_on_axis && (span - 0.5 * PI).abs() < 1e-12 && (pole_at_start && equator(p1) || on_axis(p1) && equator(p0))) {
1110                    // A cap of a sphere about the axis, from its pole to a rim
1111                    // short of (or past) the equator: swept where its grazing
1112                    // curves keep their angle about the axis (meridian arcs
1113                    // through the pole).
1114                    if centre_on_axis && end > start && span < PI && (pole_at_start != on_axis(p1)) {
1115                        let roots_at = |s: f64| -> Option<Vec<f64>> {
1116                            let (a, b, c) = harmonic(|psi| g(piece, s, psi));
1117                            let r = a.hypot(b);
1118                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1119                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1120                                return None;
1121                            }
1122                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1123                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1124                            list.sort_by(|x, y| x.total_cmp(y));
1125                            Some(list)
1126                        };
1127                        if let [Some(r0), Some(r1), Some(r2)] = [0.25, 0.5, 0.75].map(roots_at) {
1128                            if r0.iter().zip(&r1).chain(r0.iter().zip(&r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1129                                kinds.push(Kind::RuledArc(r0));
1130                                continue;
1131                            }
1132                        }
1133                    }
1134                    return Err(refuse("revolved_arc", format!("meridian piece {i}: only a quarter circle from a pole to an equator is swept here")));
1135                }
1136                kinds.push(Kind::Sphere { centre: origin.add(w.scale(centre[1])), pole_at_start });
1137            }
1138        }
1139    }
1140    // Rims: junctions off the axis, with the angles they are split at.
1141    let count = meridian.len();
1142    let junction = |k: usize| piece_point(&meridian[k], 1.0); // between piece k and k + 1
1143    let face_of = |piece: usize| faces.iter().position(|&f| f == piece);
1144    let mut rim_angles: HashMap<usize, Vec<f64>> = HashMap::new();
1145    for k in 0..count {
1146        if on_axis(junction(k)) {
1147            continue;
1148        }
1149        let mut angles: Vec<f64> = Vec::new();
1150        for (piece, s_end) in [(k, 1.0), ((k + 1) % count, 0.0)] {
1151            let Some(f) = face_of(piece) else { continue };
1152            match &kinds[f] {
1153                Kind::Ruled(roots) | Kind::RuledArc(roots) => angles.extend(roots.iter().copied()),
1154                Kind::Ball { .. } | Kind::Slide => {}
1155                Kind::SlideSide => angles.extend([0.0, PI]),
1156                Kind::TorusZone { psi_a, psi_b, .. } => angles.extend([psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)]),
1157                Kind::Moving => {
1158                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1159                    angles.extend([lower.rem_euclid(TAU), upper.rem_euclid(TAU)]);
1160                }
1161                Kind::Sphere { centre, .. } => {
1162                    let d = screw.velocity(*centre).cross(w);
1163                    let base = d.dot(u2).atan2(d.dot(u1)).rem_euclid(TAU);
1164                    angles.extend([base, (base + PI).rem_euclid(TAU)]);
1165                }
1166            }
1167        }
1168        angles.sort_by(|a, b| a.total_cmp(b));
1169        let mut merged: Vec<f64> = Vec::new();
1170        for a in angles {
1171            if merged.last().is_some_and(|&b| (a - b).abs() < 1e-9) || merged.first().is_some_and(|&b| (b + TAU - a).abs() < 1e-9) {
1172                continue;
1173            }
1174            merged.push(a);
1175        }
1176        rim_angles.insert(k, merged);
1177    }
1178    // Every face's own split angles must be its rims' (one arc per patch side).
1179    for (f, &piece) in faces.iter().enumerate() {
1180        for (k, s_end) in [((piece + count - 1) % count, 0.0), (piece, 1.0)] {
1181            let own: Vec<f64> = match &kinds[f] {
1182                Kind::Ruled(roots) | Kind::RuledArc(roots) => roots.clone(),
1183                Kind::Moving => {
1184                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1185                    let mut list = vec![lower.rem_euclid(TAU), upper.rem_euclid(TAU)];
1186                    list.sort_by(|a, b| a.total_cmp(b));
1187                    list
1188                }
1189                Kind::TorusZone { psi_a, psi_b, .. } => {
1190                    let mut list = vec![psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)];
1191                    list.sort_by(|a, b| a.total_cmp(b));
1192                    list
1193                }
1194                Kind::Sphere { .. } | Kind::Ball { .. } | Kind::Slide => continue,
1195                Kind::SlideSide => vec![0.0, PI],
1196            };
1197            if let Some(angles) = rim_angles.get(&k) {
1198                if own.is_empty() {
1199                    continue;
1200                }
1201                if angles.len() != own.len() || angles.iter().zip(&own).any(|(a, b)| (a - b).abs() > 1e-9) {
1202                    return Err(refuse("revolved_rims", format!("meridian piece {piece} splits at other angles than its rim")));
1203                }
1204            }
1205        }
1206    }
1207    let mut points: Vec<Vec3> = Vec::new();
1208    let mut curves: Vec<ToolCurve> = Vec::new();
1209    let mut caps: Vec<Cap> = Vec::new();
1210    let mut slides: Vec<SlideDisc> = Vec::new();
1211    let mut slide_sides: Vec<SlideSide> = Vec::new();
1212    // Rim points and arcs: arc j of rim k runs from angle j to angle j + 1.
1213    let mut rim_points: HashMap<(usize, usize), usize> = HashMap::new();
1214    let mut rim_arcs: HashMap<(usize, usize), usize> = HashMap::new();
1215    let mut rim_keys: Vec<usize> = rim_angles.keys().copied().collect();
1216    rim_keys.sort_unstable();
1217    for &k in &rim_keys {
1218        let q = junction(k);
1219        let angles = rim_angles[&k].clone();
1220        let angles = if angles.is_empty() { vec![0.0] } else { angles };
1221        for (j, &a) in angles.iter().enumerate() {
1222            points.push(at(q[0], q[1], a));
1223            rim_points.insert((k, j), points.len() - 1);
1224        }
1225        for j in 0..angles.len() {
1226            let a = angles[j];
1227            let b = if j + 1 < angles.len() { angles[j + 1] } else { angles[0] + TAU };
1228            let base = at(q[0], q[1], a);
1229            let surface = frag(make_revolution(origin, w, &frag(make_line(base, base.add(w)), "line")?, b - a), "rim")?;
1230            curves.push(ToolCurve {
1231                curve: frag(surface.iso_curve_v(0.0), "rim_arc")?,
1232                start: rim_points[&(k, j)],
1233                end: rim_points[&(k, (j + 1) % angles.len())],
1234                degenerate: false,
1235                samples: Some((0..=LOFT_SAMPLES).map(|i| at(q[0], q[1], a + (b - a) * i as f64 / LOFT_SAMPLES as f64)).collect()),
1236            });
1237            rim_arcs.insert((k, j), curves.len() - 1);
1238        }
1239        rim_angles.insert(k, angles);
1240    }
1241    let arc_index = |k: usize, angle: f64| -> Result<usize, KernelRefusal> {
1242        rim_angles[&k]
1243            .iter()
1244            .position(|&a| ((a - angle).rem_euclid(TAU)).min((angle - a).rem_euclid(TAU)) < 1e-9)
1245            .ok_or_else(|| refuse("revolved_rims", "a patch corner is not on its rim's split".into()))
1246    };
1247    let sign_at = |piece: &OutlinePiece, psi: f64| g(piece, 0.5, psi) > 0.0;
1248    for (f, &piece_index) in faces.iter().enumerate() {
1249        let piece = &meridian[piece_index];
1250        let below = (piece_index + count - 1) % count; // rim at the piece's start
1251        let above = piece_index; // rim at its end
1252        let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1253        match &kinds[f] {
1254            Kind::SlideSide => {
1255                if on_axis(m0) || on_axis(m1) {
1256                    return Err(refuse("revolved_grazing", format!("meridian piece {piece_index} grazes all over")));
1257                }
1258                let seams = [0.0, PI];
1259                let mut patches = Vec::with_capacity(2);
1260                for j in 0..2 {
1261                    let (alpha, theta) = (seams[j], PI);
1262                    let (ib, ia) = (arc_index(below, alpha)?, arc_index(above, alpha)?);
1263                    patches.push((alpha, theta, rim_arcs[&(below, ib)], rim_arcs[&(above, ia)], [rim_points[&(below, ib)], rim_points[&(above, ia)]]));
1264                }
1265                slide_sides.push(SlideSide { origin, w, patches });
1266            }
1267            Kind::RuledArc(roots) => {
1268                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1269                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1270                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1271                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1272                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1273                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1274                    let from = tube_point(psi, start);
1275                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1276                    frag(surface.iso_curve_v(0.0), "tube")
1277                };
1278                // A cap to its pole: the meridian arcs start (or end) there,
1279                // and each patch has a pole in place of a rim arc.
1280                let apex = if on_axis(m0) || on_axis(m1) {
1281                    let m = if on_axis(m0) { m0 } else { m1 };
1282                    points.push(at(0.0, m[1], 0.0));
1283                    Some(points.len() - 1)
1284                } else {
1285                    None
1286                };
1287                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1288                    match (on, apex) {
1289                        (true, Some(p)) => Ok(p),
1290                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1291                    }
1292                };
1293                let mut generators = Vec::with_capacity(roots.len());
1294                for &root in roots {
1295                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1296                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES).map(|i| tube_point(root, start + (end - start) * i as f64 / LOFT_SAMPLES as f64)).collect();
1297                    exact[0] = points[a];
1298                    exact[LOFT_SAMPLES] = points[b];
1299                    curves.push(ToolCurve { curve: generatrix(root)?, start: a, end: b, degenerate: false, samples: Some(exact) });
1300                    generators.push(curves.len() - 1);
1301                }
1302                for j in 0..roots.len() {
1303                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1304                    let surface = frag(make_revolution(origin, w, &generatrix(alpha)?, beta - alpha), "patch")?;
1305                    let (mid_psi, mid_v) = (0.5 * (alpha + beta), 0.5 * (start + end));
1306                    let mid_normal = w.scale(mid_v.sin()).add(u1.scale(mid_v.cos() * mid_psi.cos())).add(u2.scale(mid_v.cos() * mid_psi.sin()));
1307                    let front = screw.velocity(tube_point(mid_psi, mid_v)).dot(mid_normal) > 0.0;
1308                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1309                        let p = apex.expect("apex");
1310                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1311                        curves.len() - 1
1312                    };
1313                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1314                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1315                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1316                    let coedges = vec![
1317                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1318                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1319                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1320                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1321                    ];
1322                    let chart = Chart::Revolution {
1323                        origin,
1324                        w,
1325                        u1,
1326                        u2,
1327                        alpha,
1328                        theta: beta - alpha,
1329                        spans_u: spans_of(&surface.knots_u),
1330                        meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_of(&surface.knots_v) },
1331                    };
1332                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1333                }
1334            }
1335            Kind::Slide => {
1336                let rim = if on_axis(m0) { above } else { below };
1337                let n = normal(piece, 0.5);
1338                let outward = w.scale(n[1].signum());
1339                let arcs = rim_angles[&rim].len();
1340                // Counter-clockwise about the outward normal: increasing ψ about +w.
1341                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1342                slides.push(SlideDisc {
1343                    centre: origin.add(w.scale(m0[1])),
1344                    u: u1,
1345                    v: outward.cross(u1),
1346                    rim: order.into_iter().map(|j| (rim_arcs[&(rim, j)], n[1] > 0.0)).collect(),
1347                });
1348            }
1349            Kind::Ruled(roots) if roots.is_empty() => {
1350                // A flat end wholly on one side: a disc about the axis.
1351                let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
1352                if !flat || !(on_axis(m0) || on_axis(m1)) {
1353                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a whole side or ring is not swept here")));
1354                }
1355                let rim = if on_axis(m0) { above } else { below };
1356                let front = sign_at(piece, 0.0);
1357                if (0..64).any(|k| sign_at(piece, TAU * k as f64 / 64.0) != front) {
1358                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a flat end meets its grazing line")));
1359                }
1360                let n = normal(piece, 0.5);
1361                let outward = w.scale(n[1].signum());
1362                let centre = origin.add(w.scale(m0[1]));
1363                let (u, v) = (u1, outward.cross(u1));
1364                let arcs = rim_angles[&rim].len();
1365                let mut coedges = Vec::with_capacity(arcs);
1366                let mut corners = Vec::new();
1367                // Counter-clockwise about the outward normal: increasing ψ about +w.
1368                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1369                for j in order {
1370                    let c = rim_arcs[&(rim, j)];
1371                    let forward = n[1] > 0.0;
1372                    coedges.push((c, forward, plane_pcurve(centre, u, v, &curves[c].curve, forward)?));
1373                    corners.push(points[curves[c].start]);
1374                }
1375                let r = junction(rim)[0];
1376                corners.extend([centre.add(u.scale(r)).add(v.scale(r)), centre.sub(u.scale(r)).sub(v.scale(r))]);
1377                caps.push(Cap { surface: plane_patch(centre, u, v, &corners)?, front, coedges, chart: Some(Chart::Plane { origin: centre, u, v }) });
1378            }
1379            Kind::Ruled(roots) => {
1380                // A cone to a point: its generators start (or end) at the
1381                // apex, and each patch has a pole there in place of a rim arc.
1382                let apex = if on_axis(m0) || on_axis(m1) {
1383                    let m = if on_axis(m0) { m0 } else { m1 };
1384                    points.push(at(0.0, m[1], 0.0));
1385                    Some(points.len() - 1)
1386                } else {
1387                    None
1388                };
1389                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1390                    match (on, apex) {
1391                        (true, Some(p)) => Ok(p),
1392                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1393                    }
1394                };
1395                // Generators at each root, from the start rim to the end rim.
1396                let mut generators = Vec::with_capacity(roots.len());
1397                for &root in roots {
1398                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1399                    let line_samples = (0..=LOFT_SAMPLES).map(|i| points[a].add(points[b].sub(points[a]).scale(i as f64 / LOFT_SAMPLES as f64))).collect();
1400                    curves.push(ToolCurve { curve: frag(make_line(points[a], points[b]), "generator")?, start: a, end: b, degenerate: false, samples: Some(line_samples) });
1401                    generators.push(curves.len() - 1);
1402                }
1403                for j in 0..roots.len() {
1404                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1405                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1406                    let surface = frag(make_revolution(origin, w, &generatrix, beta - alpha), "patch")?;
1407                    let front = sign_at(piece, 0.5 * (alpha + beta));
1408                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1409                        let p = apex.expect("apex");
1410                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1411                        curves.len() - 1
1412                    };
1413                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1414                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1415                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1416                    let coedges = vec![
1417                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1418                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1419                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1420                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1421                    ];
1422                    let chart = Chart::Revolution { origin, w, u1, u2, alpha, theta: beta - alpha, spans_u: spans_of(&surface.knots_u), meridian: MeridianChart::Line { m0, m1 } };
1423                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1424                }
1425            }
1426            Kind::Moving => {
1427                if on_axis(m0) || on_axis(m1) {
1428                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a split cone to a point is not swept here")));
1429                }
1430                let n = 128;
1431                let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1432                let pairs: Vec<(f64, f64)> = params.iter().map(|&t| branches(piece, t).expect("checked")).collect();
1433                let pick = |pair: (f64, f64), which: usize| if which == 0 { pair.0 } else { pair.1 };
1434                // K: the lower and upper branch, each from the start rim to the end rim.
1435                let mut branch_curves = [0usize; 2];
1436                for which in 0..2 {
1437                    let (psi0, psi1) = (pick(pairs[0], which), pick(pairs[n], which));
1438                    let start = rim_points[&(below, arc_index(below, psi0)?)];
1439                    let end = rim_points[&(above, arc_index(above, psi1)?)];
1440                    let mut samples: Vec<Vec3> = params
1441                        .iter()
1442                        .zip(&pairs)
1443                        .map(|(&t, &pair)| {
1444                            let m = piece_point(piece, t);
1445                            at(m[0], m[1], pick(pair, which))
1446                        })
1447                        .collect();
1448                    samples[0] = points[start];
1449                    samples[n] = points[end];
1450                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES)
1451                        .map(|i| {
1452                            let t = i as f64 / LOFT_SAMPLES as f64;
1453                            let m = piece_point(piece, t);
1454                            at(m[0], m[1], pick(branches(piece, t).expect("checked"), which))
1455                        })
1456                        .collect();
1457                    exact[0] = points[start];
1458                    exact[LOFT_SAMPLES] = points[end];
1459                    curves.push(ToolCurve { curve: frag(fit_tool_curve(&samples, &params), "branch")?, start, end, degenerate: false, samples: Some(exact) });
1460                    branch_curves[which] = curves.len() - 1;
1461                }
1462                // Front between lower and upper; back from upper to lower + 2π.
1463                for (lo_which, hi_which, hi_turn) in [(0usize, 1usize, 0.0), (1, 0, TAU)] {
1464                    let lo = |i: usize| pick(pairs[i], lo_which);
1465                    let hi = |i: usize| pick(pairs[i], hi_which) + hi_turn;
1466                    let alpha = (0..=n).map(lo).fold(f64::INFINITY, f64::min) - 1e-3;
1467                    let theta = (0..=n).map(hi).fold(f64::NEG_INFINITY, f64::max) + 1e-3 - alpha;
1468                    if theta >= TAU {
1469                        return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a side patch wraps all the way round")));
1470                    }
1471                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1472                    let surface = frag(make_revolution(origin, w, &generatrix, theta), "patch")?;
1473                    let spans = (surface.knots_u.len() - 6) / 2 + 1;
1474                    let u_of = |psi: f64| crate::circle_angle_to_parameter(spans, theta, psi - alpha);
1475                    let angle_near = |x: Vec3, guess: f64| -> f64 {
1476                        let r = x.sub(origin);
1477                        let a = r.dot(u2).atan2(r.dot(u1));
1478                        guess + (a - guess + PI).rem_euclid(TAU) - PI
1479                    };
1480                    let front = sign_at(piece, 0.5 * (lo(n / 2) + hi(n / 2)));
1481                    // A rim arc's pcurve on this patch, through its own parameter.
1482                    let rim_pcurve = |arc: usize, v: f64| -> Result<NurbsCurve, KernelRefusal> {
1483                        let curve = &curves[arc].curve;
1484                        let [d0, d1] = frag(curve.domain(), "domain")?;
1485                        let ts: Vec<f64> = pcurve_stations(d0, d1);
1486                        let mut uv = Vec::with_capacity(ts.len());
1487                        for &t in &ts {
1488                            let x = frag(curve.evaluate(t), "rim")?;
1489                            uv.push(Vec3::new(u_of(angle_near(x, alpha + 0.5 * theta)), v, 0.0));
1490                        }
1491                        if pcurve_joints_on() {
1492                            let (ju, jv) = surface_joints(&surface);
1493                            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok([u_of(angle_near(frag(curve.evaluate(t), "rim")?, alpha + 0.5 * theta)), v]) };
1494                            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &ju, &jv, curve)? {
1495                                return Ok(fitted);
1496                            }
1497                        }
1498                        frag(fit_pcurve(&uv, &ts), "rim_pcurve")
1499                    };
1500                    // A grazing branch's pcurve: the image of the built edge,
1501                    // through its own parameter (angle about the axis; place
1502                    // along the meridian line).
1503                    let branch_pcurve = |which: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> {
1504                        let curve = &curves[branch_curves[which]].curve;
1505                        let [d0, d1] = frag(curve.domain(), "domain")?;
1506                        let (span_rho, span_z) = (m1[0] - m0[0], m1[1] - m0[1]);
1507                        let length2 = span_rho * span_rho + span_z * span_z;
1508                        let ts: Vec<f64> = pcurve_stations(d0, d1);
1509                        let mut uv = Vec::with_capacity(ts.len());
1510                        let read = |x: Vec3| -> [f64; 2] {
1511                            let r = x.sub(origin);
1512                            let z = r.dot(w);
1513                            let rho = r.sub(w.scale(z)).length();
1514                            let along = ((rho - m0[0]) * span_rho + (z - m0[1]) * span_z) / length2;
1515                            [u_of(angle_near(x, alpha + 0.5 * theta)), along]
1516                        };
1517                        for &t in &ts {
1518                            let [u, along] = read(frag(curve.evaluate(t), "branch")?);
1519                            uv.push(Vec3::new(u, along, 0.0));
1520                        }
1521                        if pcurve_joints_on() {
1522                            let (ju, jv) = surface_joints(&surface);
1523                            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok(read(frag(curve.evaluate(t), "branch")?)) };
1524                            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &ju, &jv, curve)? {
1525                                return Ok(fitted);
1526                            }
1527                        }
1528                        frag(fit_pcurve(&uv, &ts), "branch_pcurve")
1529                    };
1530                    let bottom = rim_arcs[&(below, arc_index(below, lo(0))?)];
1531                    let top = rim_arcs[&(above, arc_index(above, lo(n))?)];
1532                    let coedges = vec![
1533                        (bottom, true, rim_pcurve(bottom, 0.0)?),
1534                        (branch_curves[hi_which], true, branch_pcurve(hi_which, hi_turn)?),
1535                        (top, false, frag(rim_pcurve(top, 1.0)?.reversed(), "reversed")?),
1536                        (branch_curves[lo_which], false, frag(branch_pcurve(lo_which, 0.0)?.reversed(), "reversed")?),
1537                    ];
1538                    let chart_spans = spans_of(&surface.knots_u);
1539                    caps.push(Cap { surface, front, coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha, theta, spans_u: chart_spans, meridian: MeridianChart::Line { m0, m1 } }) });
1540                }
1541            }
1542            Kind::TorusZone { psi_a, psi_b, at_end } => {
1543                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1544                let (psi_a, psi_b, at_end) = (*psi_a, *psi_b, *at_end);
1545                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1546                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1547                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1548                let normal_at = |psi: f64, v: f64| w.scale(v.sin()).add(u1.scale(v.cos() * psi.cos())).add(u2.scale(v.cos() * psi.sin()));
1549                let root = |psi: f64| -> Option<f64> {
1550                    let (a, b, c) = harmonic(|v| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)));
1551                    let r = a.hypot(b);
1552                    if !(c.abs() < r) {
1553                        return None;
1554                    }
1555                    let base = b.atan2(a);
1556                    let spread = (-c / r).acos();
1557                    [base - spread, base + spread].into_iter().map(|v| start + (v - start).rem_euclid(TAU)).find(|&v| v <= end + 1e-12)
1558                };
1559                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1560                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1561                    let from = tube_point(psi, start);
1562                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1563                    frag(surface.iso_curve_v(0.0), "tube")
1564                };
1565                let (rim_k, other_k) = if at_end { (above, below) } else { (below, above) };
1566                let ka = rim_points[&(rim_k, arc_index(rim_k, psi_a)?)];
1567                let kb = rim_points[&(rim_k, arc_index(rim_k, psi_b)?)];
1568                // K: the graph over ψ ∈ [ψa, ψb].
1569                let n = 256;
1570                let params: Vec<f64> = (0..=n).map(|j| j as f64 / n as f64).collect();
1571                // Spaced as 1 − cos: where K meets its rim it runs along the
1572                // meridian, so its tube angle goes as √(ψ − ψa); in this
1573                // parameter it is regular.
1574                let psi_of = |t: f64| psi_a + (psi_b - psi_a) * 0.5 * (1.0 - (PI * t).cos());
1575                let mut xyz = Vec::with_capacity(n + 1);
1576                for j in 0..=n {
1577                    let psi = psi_of(params[j]);
1578                    let v = if j == 0 || j == n { if at_end { end } else { start } } else {
1579                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1580                    };
1581                    xyz.push(tube_point(psi, v));
1582                }
1583                xyz[0] = points[ka];
1584                xyz[n] = points[kb];
1585                let mut exact = Vec::with_capacity(LOFT_SAMPLES + 1);
1586                for i in 0..=LOFT_SAMPLES {
1587                    let psi = psi_of(i as f64 / LOFT_SAMPLES as f64);
1588                    let v = if i == 0 || i == LOFT_SAMPLES { if at_end { end } else { start } } else {
1589                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1590                    };
1591                    exact.push(tube_point(psi, v));
1592                }
1593                exact[0] = points[ka];
1594                exact[LOFT_SAMPLES] = points[kb];
1595                curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "torus_k")?, start: ka, end: kb, degenerate: false, samples: Some(exact) });
1596                let k_curve = curves.len() - 1;
1597                // Cut meridians at ψa and ψb, from the start rim to the end rim.
1598                let mut cut = [0usize; 2];
1599                for (slot, psi) in [(0, psi_a), (1, psi_b)] {
1600                    let (lo, hi) = (rim_points[&(below, arc_index(below, psi)?)], rim_points[&(above, arc_index(above, psi)?)]);
1601                    curves.push(ToolCurve { curve: generatrix(psi)?, start: lo, end: hi, degenerate: false, samples: None });
1602                    cut[slot] = curves.len() - 1;
1603                }
1604                let label = |psi: f64, v: f64| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)) > 0.0;
1605                // The patch over [α, β] and its exact inverse.
1606                let patch = |alpha: f64, beta: f64| -> Result<(NurbsSurface, usize, usize), KernelRefusal> {
1607                    let g = generatrix(alpha)?;
1608                    let surface = frag(make_revolution(origin, w, &g, beta - alpha), "torus_patch")?;
1609                    let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1610                    let spans_v = (g.knots.len() - 6) / 2 + 1;
1611                    Ok((surface, spans_u, spans_v))
1612                };
1613                let inverse_pcurve = |curve: &NurbsCurve, alpha: f64, beta: f64, spans_u: usize, spans_v: usize, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
1614                    let [d0, d1] = frag(curve.domain(), "domain")?;
1615                    let ts: Vec<f64> = pcurve_stations(d0, d1);
1616                    let mut uv = Vec::with_capacity(ts.len());
1617                    let read = |x: Vec3| -> [f64; 2] {
1618                        let r = x.sub(origin);
1619                        let mid = 0.5 * (alpha + beta);
1620                        let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
1621                        let q = x.sub(tube_centre(psi));
1622                        let radial = u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1623                        let vmid = 0.5 * (start + end);
1624                        let v = vmid + (q.dot(w).atan2(q.dot(radial)) - vmid + PI).rem_euclid(TAU) - PI;
1625                        [crate::circle_angle_to_parameter(spans_u, beta - alpha, psi - alpha), crate::circle_angle_to_parameter(spans_v, end - start, v - start)]
1626                    };
1627                    for &t in &ts {
1628                        let [u, v] = read(frag(curve.evaluate(t), "point")?);
1629                        uv.push(Vec3::new(u, v, 0.0));
1630                    }
1631                    if pcurve_joints_on() {
1632                        let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
1633                        let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok(read(frag(curve.evaluate(t), "point")?)) };
1634                        if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
1635                            return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
1636                        }
1637                    }
1638                    let fitted = frag(fit_pcurve(&uv, &ts), "torus_pcurve")?;
1639                    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
1640                };
1641                // The band away from K: a natural patch over [ψb, ψa + 2π].
1642                {
1643                    let (surface, _, band_spans_v) = patch(psi_b, psi_a + TAU)?;
1644                    let (bottom, top) = (rim_arcs[&(below, arc_index(below, psi_b)?)], rim_arcs[&(above, arc_index(above, psi_b)?)]);
1645                    let coedges = vec![
1646                        (bottom, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1647                        (cut[0], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1648                        (top, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1649                        (cut[1], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1650                    ];
1651                    let mid = psi_b + 0.5 * (psi_a + TAU - psi_b);
1652                    let chart_spans = spans_of(&surface.knots_u);
1653                    caps.push(Cap { surface, front: label(mid, 0.5 * (start + end)), coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_b, theta: psi_a + TAU - psi_b, spans_u: chart_spans, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: band_spans_v } }) });
1654                }
1655                // Over [ψa, ψb]: the lens between K and its rim, and the rest.
1656                let (surface, spans_u, spans_v) = patch(psi_a, psi_b)?;
1657                let rim_arc = rim_arcs[&(rim_k, arc_index(rim_k, psi_a)?)];
1658                let other_arc = rim_arcs[&(other_k, arc_index(other_k, psi_a)?)];
1659                let mid = 0.5 * (psi_a + psi_b);
1660                let v_k = root(mid).ok_or_else(|| refuse("torus_zone", "no grazing point mid-way".into()))?;
1661                let k_pc = |forward: bool| inverse_pcurve(&curves[k_curve].curve, psi_a, psi_b, spans_u, spans_v, forward);
1662                let lens_v = if at_end { 0.5 * (v_k + end) } else { 0.5 * (v_k + start) };
1663                let rest_v = if at_end { 0.5 * (v_k + start) } else { 0.5 * (v_k + end) };
1664                if at_end {
1665                    // Lens: K (ψa -> ψb) under the end rim, then the end rim back.
1666                    let lens = vec![(k_curve, true, k_pc(true)?), (rim_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?)];
1667                    caps.push(Cap { surface: surface.clone(), front: label(mid, lens_v), coedges: lens, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1668                    let rest = vec![
1669                        (other_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1670                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1671                        (k_curve, false, k_pc(false)?),
1672                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1673                    ];
1674                    caps.push(Cap { surface, front: label(mid, rest_v), coedges: rest, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1675                } else {
1676                    let lens = vec![(rim_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?), (k_curve, false, k_pc(false)?)];
1677                    caps.push(Cap { surface: surface.clone(), front: label(mid, lens_v), coedges: lens, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1678                    let rest = vec![
1679                        (k_curve, true, k_pc(true)?),
1680                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1681                        (other_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1682                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1683                    ];
1684                    caps.push(Cap { surface, front: label(mid, rest_v), coedges: rest, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1685                }
1686            }
1687            Kind::Ball { centre, radius } => {
1688                let m = frag(screw.velocity(*centre).normalized(), "ball_still")?;
1689                let d = frag(w.cross(m).normalized().or_else(|_| u1.cross(m).normalized()), "ball_axis")?;
1690                let (e1, e2) = (centre.add(d.scale(*radius)), centre.sub(d.scale(*radius)));
1691                points.push(e1);
1692                points.push(e2);
1693                let (i1, i2) = (points.len() - 2, points.len() - 1);
1694                let half = frag(make_revolution(*centre, m, &frag(make_line(e1, e1.add(m)), "line")?, PI), "great")?;
1695                let k_a = frag(half.iso_curve_v(0.0), "great")?;
1696                // Exact samples at even angles from e1 round to e2 (for a
1697                // lofted wall), turned the way the curve runs.
1698                let k_a_samples: Vec<Vec3> = {
1699                    let [a0, a1] = frag(k_a.domain(), "domain")?;
1700                    let middle = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?;
1701                    let arm = e1.sub(*centre);
1702                    let sense = if arm.rotate_about(m, 0.5 * PI).add(*centre).sub(middle).length() < arm.rotate_about(m, -0.5 * PI).add(*centre).sub(middle).length() { 1.0 } else { -1.0 };
1703                    let mut list: Vec<Vec3> = (0..=LOFT_SAMPLES).map(|i| centre.add(arm.rotate_about(m, sense * PI * i as f64 / LOFT_SAMPLES as f64))).collect();
1704                    list[0] = e1;
1705                    list[LOFT_SAMPLES] = e2;
1706                    list
1707                };
1708                curves.push(ToolCurve { curve: k_a.clone(), start: i1, end: i2, degenerate: false, samples: Some(k_a_samples.clone()) });
1709                let k_a_index = curves.len() - 1;
1710                let [a0, a1] = frag(k_a.domain(), "domain")?;
1711                let h = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?.sub(*centre);
1712                let mut k_b_index: Option<usize> = None;
1713                for front in [true, false] {
1714                    let toward = if front { m } else { m.scale(-1.0) };
1715                    let da = if d.cross(h).dot(toward) > 0.0 { d } else { d.scale(-1.0) };
1716                    let mut generatrix = k_a.clone();
1717                    let mut surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1718                    let outward = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1719                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1720                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1721                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1722                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1723                    };
1724                    let mut forward = true;
1725                    if !outward(&surface)? {
1726                        generatrix = frag(generatrix.reversed(), "reversed")?;
1727                        surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1728                        forward = false;
1729                    }
1730                    let (start, end) = if forward { (i1, i2) } else { (i2, i1) };
1731                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1732                    let k_b = match k_b_index {
1733                        Some(index) => index,
1734                        None => {
1735                            // The other half of the great circle: the first half turned half way about `da`.
1736                            let mut samples: Vec<Vec3> = k_a_samples.iter().map(|&x| centre.add(x.sub(*centre).rotate_about(da, PI))).collect();
1737                            if !forward {
1738                                samples.reverse();
1739                            }
1740                            samples[0] = points[start];
1741                            samples[LOFT_SAMPLES] = points[end];
1742                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: Some(samples) });
1743                            k_b_index = Some(curves.len() - 1);
1744                            curves.len() - 1
1745                        }
1746                    };
1747                    let k_b_forward = curves[k_b].start == start;
1748                    let k_b_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1749                    let poles = [start, end].map(|p| {
1750                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1751                        curves.len() - 1
1752                    });
1753                    let coedges = vec![
1754                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1755                        (k_b, k_b_forward, k_b_pcurve),
1756                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1757                        (k_a_index, !forward, uv_line([0.0, g1], [0.0, g0])?),
1758                    ];
1759                    caps.push(Cap { surface, front, coedges, chart: None });
1760                }
1761            }
1762            Kind::Sphere { centre, pole_at_start } => {
1763                let rim = if *pole_at_start { above } else { below };
1764                let angles = rim_angles[&rim].clone();
1765                if angles.len() != 2 {
1766                    return Err(refuse("revolved_rims", "a hemisphere's rim is not split in two".into()));
1767                }
1768                let pole_side = w.scale(if *pole_at_start { m0[1] - m1[1] } else { m1[1] - m0[1] }.signum());
1769                let m = screw.velocity(*centre);
1770                let e1 = points[rim_points[&(rim, 0)]];
1771                let d = frag(e1.sub(*centre).normalized(), "lune_axis")?;
1772                let mut great: Option<usize> = None;
1773                for j in 0..2 {
1774                    let arc = rim_arcs[&(rim, j)];
1775                    let [a0, a1] = frag(curves[arc].curve.domain(), "domain")?;
1776                    let middle = frag(curves[arc].curve.evaluate(0.5 * (a0 + a1)), "middle")?;
1777                    let hv = middle.sub(*centre);
1778                    let da = if d.cross(hv).dot(pole_side) > 0.0 { d } else { d.scale(-1.0) };
1779                    // Turn the rim arc about da until its middle reaches K's plane.
1780                    let theta = (-m.dot(hv)).atan2(m.dot(da.cross(hv))).rem_euclid(TAU);
1781                    let theta = if theta > PI { theta - PI } else { theta };
1782                    if !(theta > 1e-9 && theta < PI - 1e-9) {
1783                        return Err(refuse("revolved_lune", "the great circle meets the rim's plane edge-on".into()));
1784                    }
1785                    let mut generatrix = curves[arc].curve.clone();
1786                    let mut surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1787                    // Outward: (x − centre) at the lune's middle.
1788                    let probe = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1789                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1790                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1791                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1792                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1793                    };
1794                    let mut forward = true;
1795                    if !probe(&surface)? {
1796                        generatrix = frag(generatrix.reversed(), "reversed")?;
1797                        surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1798                        forward = false;
1799                    }
1800                    let (start, end) = if forward { (curves[arc].start, curves[arc].end) } else { (curves[arc].end, curves[arc].start) };
1801                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1802                    // The great-circle half: the turned generatrix (u = 1), from
1803                    // `start` to `end`; made once, by the first lune.
1804                    let k_curve = match great {
1805                        Some(index) => index,
1806                        None => {
1807                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: None });
1808                            great = Some(curves.len() - 1);
1809                            curves.len() - 1
1810                        }
1811                    };
1812                    let k_forward = curves[k_curve].start == start;
1813                    let poles = [start, end].map(|p| {
1814                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1815                        curves.len() - 1
1816                    });
1817                    let k_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1818                    let coedges = vec![
1819                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1820                        (k_curve, k_forward, k_pcurve),
1821                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1822                        (arc, !forward, uv_line([0.0, g1], [0.0, g0])?),
1823                    ];
1824                    let mid_psi = if j == 0 { 0.5 * (angles[0] + angles[1]) } else { 0.5 * (angles[1] + angles[0] + TAU) };
1825                    let front = m.dot(at(1.0, 0.0, mid_psi).sub(origin)) > 0.0;
1826                    caps.push(Cap { surface, front, coedges, chart: None });
1827                }
1828            }
1829        }
1830    }
1831    Ok(Split {
1832        points,
1833        curves,
1834        caps,
1835        slides,
1836        slide_sides,
1837        scale,
1838        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
1839    })
1840}
1841
1842/// `BREP_SWEEP_RING_WINDING` (default off): a ring whose grazing curves wind
1843/// round its tube as they go once round the ring is split along their
1844/// continuous unwrapping, in six pieces, instead of refused.
1845fn ring_winding_on() -> bool {
1846    crate::switch!("BREP_SWEEP_RING_WINDING", false)
1847}
1848
1849/// A ring split by grazing curves that wind round its tube: the curves' angle
1850/// v on the tube, unwrapped continuously along ψ, gains a whole number of
1851/// turns going once round the ring. None where it gains none (the two-halves
1852/// split serves). Six pieces along ψ keep each band's stretch of v short of a
1853/// whole turn while the curves turn, and leave the tumble's eight trial seams
1854/// (π/4 apart) four distinct placements.
1855#[allow(clippy::too_many_arguments)]
1856fn split_torus_wound(
1857    screw: &Screw,
1858    origin: Vec3,
1859    w: Vec3,
1860    u1: Vec3,
1861    u2: Vec3,
1862    centre: [f64; 2],
1863    radius: f64,
1864    meridian: &[OutlinePiece],
1865) -> Result<Option<Split>, KernelRefusal> {
1866    const PIECES: usize = 6;
1867    let (rho_c, z_c) = (centre[0], centre[1]);
1868    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1869    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
1870    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
1871    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
1872    let n = screw.loop_samples;
1873    let total = PIECES * n;
1874    // (ψ, lower, upper) round the whole ring, each base angle the one nearest
1875    // the last.
1876    let mut round: Vec<(f64, f64, f64)> = Vec::with_capacity(total + 1);
1877    let mut near = {
1878        let (a, b, _) = harmonic(|v| g(0.0, v));
1879        b.atan2(a)
1880    };
1881    for i in 0..=total {
1882        let psi = TAU * i as f64 / total as f64;
1883        let (a, b, c) = harmonic(|v| g(psi, v));
1884        let r = a.hypot(b);
1885        if !(c.abs() < r * (1.0 - 1e-9)) {
1886            return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
1887        }
1888        let base = near + (b.atan2(a) - near + PI).rem_euclid(TAU) - PI;
1889        if i > 0 && (base - near).abs() > 0.5 {
1890            return Err(refuse("ring_grazing", "the ring's grazing curves turn too fast".into()));
1891        }
1892        near = base;
1893        let spread = (-c / r).acos();
1894        round.push((psi, base - spread, base + spread));
1895    }
1896    if ((round[total].1 - round[0].1) / TAU).round() == 0.0 {
1897        return Ok(None);
1898    }
1899    let samples: Vec<Vec<(f64, f64, f64)>> = (0..PIECES).map(|k| round[k * n..=(k + 1) * n].to_vec()).collect();
1900    let seam_psi = |k: usize| TAU * k as f64 / PIECES as f64;
1901    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1902    let mut points: Vec<Vec3> = Vec::new();
1903    let mut curves: Vec<ToolCurve> = Vec::new();
1904    // Points: at each seam, on each branch (the last piece ends on seam 0,
1905    // a whole number of turns round the tube on).
1906    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, branch)
1907    for (seam, piece) in samples.iter().enumerate() {
1908        let (psi, lower, upper) = piece[0];
1909        for (branch, v) in [(0, lower), (1, upper)] {
1910            points.push(point(psi, v));
1911            corner.insert((seam, branch), points.len() - 1);
1912        }
1913    }
1914    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (piece, branch)
1915    for (piece, list) in samples.iter().enumerate() {
1916        for branch in 0..2 {
1917            let mut xyz: Vec<Vec3> = list.iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
1918            let (start, end) = (corner[&(piece, branch)], corner[&((piece + 1) % PIECES, branch)]);
1919            xyz[0] = points[start];
1920            xyz[n] = points[end];
1921            curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
1922            branch_curve.insert((piece, branch), curves.len() - 1);
1923        }
1924    }
1925    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
1926        let start = point(psi, v0);
1927        let axis = radial(psi).cross(w);
1928        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
1929        frag(surface.iso_curve_v(0.0), "tube_arc")
1930    };
1931    // Seam arcs of each band: band 0 (front) from lower to upper, band 1
1932    // (back) from upper to lower + 2π.
1933    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
1934    for seam in 0..PIECES {
1935        let (psi, lower, upper) = samples[seam][0];
1936        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
1937        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
1938        seam_arc.insert((seam, 0), curves.len() - 1);
1939        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
1940        seam_arc.insert((seam, 1), curves.len() - 1);
1941    }
1942    let mut caps = Vec::new();
1943    for piece in 0..PIECES {
1944        let (psi_a, psi_b) = (seam_psi(piece), seam_psi(piece + 1));
1945        for band in 0..2 {
1946            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
1947            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
1948            // As in the two-halves split: a margin each side for end trims.
1949            let low = samples[piece].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
1950            let high = samples[piece].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
1951            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
1952            let (v_low, v_high) = (low - margin, high + margin);
1953            let theta_v = v_high - v_low;
1954            if theta_v >= TAU {
1955                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
1956            }
1957            let generatrix = tube_arc(psi_a, v_low, v_high)?;
1958            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
1959            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1960            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
1961            let uv_of = |psi: f64, v: f64| {
1962                Vec3::new(
1963                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
1964                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
1965                    0.0,
1966                )
1967            };
1968            let angles_of = |x: Vec3| -> (f64, f64) {
1969                let r = x.sub(origin);
1970                let psi = r.dot(u2).atan2(r.dot(u1));
1971                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
1972                let q = x.sub(tube_centre(psi));
1973                let v = q.dot(w).atan2(q.dot(radial(psi)));
1974                let mid = 0.5 * (v_low + v_high);
1975                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
1976            };
1977            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
1978                let [d0, d1] = frag(curve.domain(), "domain")?;
1979                let ts: Vec<f64> = pcurve_stations(d0, d1);
1980                let mut uv = Vec::with_capacity(ts.len());
1981                for &t in &ts {
1982                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1983                    uv.push(uv_of(psi, v));
1984                }
1985                // Broken at the band's span joints (`BREP_SWEEP_PCURVE_JOINTS`).
1986                if pcurve_joints_on() {
1987                    let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
1988                    let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
1989                        let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1990                        let p = uv_of(psi, v);
1991                        Ok([p.x, p.y])
1992                    };
1993                    if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
1994                        return Ok(fitted);
1995                    }
1996                }
1997                frag(fit_pcurve(&uv, &ts), "ring_pcurve")
1998            };
1999            let lower_edge = branch_curve[&(piece, lo_branch)];
2000            let upper_edge = branch_curve[&(piece, hi_branch)];
2001            let right = seam_arc[&((piece + 1) % PIECES, band)];
2002            let left = seam_arc[&(piece, band)];
2003            let coedges = vec![
2004                (lower_edge, true, inverse_pcurve(&curves[lower_edge].curve)?),
2005                (right, true, inverse_pcurve(&curves[right].curve)?),
2006                (upper_edge, false, frag(inverse_pcurve(&curves[upper_edge].curve)?.reversed(), "reversed")?),
2007                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
2008            ];
2009            let mid = &samples[piece][n / 2];
2010            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
2011            caps.push(Cap { surface, front, coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre: [rho_c, z_c], start: v_low, sweep: theta_v, spans: spans_v } }) });
2012        }
2013    }
2014    Ok(Some(Split {
2015        points,
2016        curves,
2017        caps,
2018        slides: Vec::new(),
2019        slide_sides: Vec::new(),
2020        scale: rho_c + radius,
2021        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
2022    }))
2023}
2024
2025/// A ring (torus: the circle of `radius` about `centre` in (ρ, z), off the
2026/// axis), split by its two grazing curves. For each angle ψ about the ring's
2027/// axis the grazing value along the tube's circle is A cos v + B sin v + C, so
2028/// each curve is a graph v(ψ) round the ring; the front band lies between
2029/// them. Each band is built in two halves (ψ in [0, π] and [π, 2π]) so no face
2030/// closes on itself.
2031#[allow(clippy::too_many_arguments)]
2032fn split_torus(
2033    screw: &Screw,
2034    origin: Vec3,
2035    w: Vec3,
2036    u1: Vec3,
2037    u2: Vec3,
2038    centre: [f64; 2],
2039    radius: f64,
2040    meridian: &[OutlinePiece],
2041) -> Result<Split, KernelRefusal> {
2042    if ring_winding_on() {
2043        if let Some(split) = split_torus_wound(screw, origin, w, u1, u2, centre, radius, meridian)? {
2044            return Ok(split);
2045        }
2046    }
2047    let (rho_c, z_c) = (centre[0], centre[1]);
2048    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
2049    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
2050    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
2051    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
2052    let reference = {
2053        let (a, b, _) = harmonic(|v| g(0.0, v));
2054        b.atan2(a)
2055    };
2056    // The lower and upper grazing angles v at ψ, unwrapped; the front between.
2057    let branches = |psi: f64| -> Option<(f64, f64)> {
2058        let (a, b, c) = harmonic(|v| g(psi, v));
2059        let r = a.hypot(b);
2060        if !(c.abs() < r * (1.0 - 1e-9)) {
2061            return None;
2062        }
2063        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
2064        let spread = (-c / r).acos();
2065        Some((base - spread, base + spread))
2066    };
2067    let n = screw.loop_samples;
2068    let halves = [(0.0, PI), (PI, TAU)];
2069    let mut samples: Vec<Vec<(f64, f64, f64)>> = Vec::new(); // per half: (ψ, lower, upper)
2070    for &(a, b) in &halves {
2071        let mut list = Vec::with_capacity(n + 1);
2072        let mut previous: Option<(f64, f64)> = None;
2073        for i in 0..=n {
2074            let psi = a + (b - a) * i as f64 / n as f64;
2075            let Some(pair) = branches(psi) else {
2076                return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
2077            };
2078            if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
2079                return Err(refuse("ring_grazing", "the ring's grazing curves turn too fast".into()));
2080            }
2081            previous = Some(pair);
2082            list.push((psi, pair.0, pair.1));
2083        }
2084        samples.push(list);
2085    }
2086    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
2087    let mut points: Vec<Vec3> = Vec::new();
2088    let mut curves: Vec<ToolCurve> = Vec::new();
2089    // Points: at ψ = 0 and π, on each branch.
2090    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam 0 | 1, branch)
2091    for seam in 0..2 {
2092        let (psi, (lower, upper)) = if seam == 0 { (0.0, (samples[0][0].1, samples[0][0].2)) } else { (PI, (samples[1][0].1, samples[1][0].2)) };
2093        for (branch, v) in [(0, lower), (1, upper)] {
2094            points.push(point(psi, v));
2095            corner.insert((seam, branch), points.len() - 1);
2096        }
2097    }
2098    let seam_of_end = |half: usize, at_end: bool| -> usize { if at_end { 1 - half } else { half } };
2099    // K: each branch over each half.
2100    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (half, branch)
2101    for half in 0..2 {
2102        for branch in 0..2 {
2103            let mut xyz: Vec<Vec3> = samples[half].iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
2104            let (start, end) = (corner[&(seam_of_end(half, false), branch)], corner[&(seam_of_end(half, true), branch)]);
2105            xyz[0] = points[start];
2106            xyz[n] = points[end];
2107            curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
2108            branch_curve.insert((half, branch), curves.len() - 1);
2109        }
2110    }
2111    // Seam arcs of each band at ψ = 0 and π: band 0 (front) from lower to
2112    // upper, band 1 (back) from upper to lower + 2π.
2113    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
2114        let start = point(psi, v0);
2115        let axis = radial(psi).cross(w);
2116        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
2117        frag(surface.iso_curve_v(0.0), "tube_arc")
2118    };
2119    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
2120    for seam in 0..2 {
2121        let psi = if seam == 0 { 0.0 } else { PI };
2122        let (lower, upper) = (samples[seam][0].1, samples[seam][0].2);
2123        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
2124        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
2125        seam_arc.insert((seam, 0), curves.len() - 1);
2126        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
2127        seam_arc.insert((seam, 1), curves.len() - 1);
2128    }
2129    let mut caps = Vec::new();
2130    for half in 0..2 {
2131        let (psi_a, psi_b) = halves[half];
2132        for band in 0..2 {
2133            // The band's lower and upper edges (v), as branches.
2134            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
2135            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
2136            // A margin each side: an end cap may be carried a little across its
2137            // grazing curve (see `end_trim`), as far as the tube leaves room.
2138            let low = samples[half].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
2139            let high = samples[half].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
2140            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
2141            let (v_low, v_high) = (low - margin, high + margin);
2142            let theta_v = v_high - v_low;
2143            if theta_v >= TAU {
2144                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
2145            }
2146            let generatrix = tube_arc(psi_a, v_low, v_high)?;
2147            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
2148            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
2149            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
2150            let uv_of = |psi: f64, v: f64| {
2151                Vec3::new(
2152                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
2153                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
2154                    0.0,
2155                )
2156            };
2157            // (ψ, v) of a point, unwrapped near the patch.
2158            let angles_of = |x: Vec3| -> (f64, f64) {
2159                let r = x.sub(origin);
2160                let psi = r.dot(u2).atan2(r.dot(u1));
2161                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
2162                let q = x.sub(tube_centre(psi));
2163                let v = q.dot(w).atan2(q.dot(radial(psi)));
2164                let mid = 0.5 * (v_low + v_high);
2165                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
2166            };
2167            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
2168                let [d0, d1] = frag(curve.domain(), "domain")?;
2169                let ts: Vec<f64> = pcurve_stations(d0, d1);
2170                let mut uv = Vec::with_capacity(ts.len());
2171                for &t in &ts {
2172                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
2173                    uv.push(uv_of(psi, v));
2174                }
2175                // Broken at the band's span joints (`BREP_SWEEP_PCURVE_JOINTS`).
2176                if pcurve_joints_on() {
2177                    let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
2178                    let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
2179                        let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
2180                        let p = uv_of(psi, v);
2181                        Ok([p.x, p.y])
2182                    };
2183                    if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
2184                        return Ok(fitted);
2185                    }
2186                }
2187                frag(fit_pcurve(&uv, &ts), "ring_pcurve")
2188            };
2189            let branch_pcurve = |b: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> { inverse_pcurve(&curves[branch_curve[&(half, b)]].curve) };
2190            let lower_edge = branch_curve[&(half, lo_branch)];
2191            let upper_edge = branch_curve[&(half, hi_branch)];
2192            let right = seam_arc[&(seam_of_end(half, true), band)];
2193            let left = seam_arc[&(seam_of_end(half, false), band)];
2194            let coedges = vec![
2195                (lower_edge, true, branch_pcurve(lo_branch, 0.0)?),
2196                (right, true, inverse_pcurve(&curves[right].curve)?),
2197                (upper_edge, false, frag(branch_pcurve(hi_branch, hi_turn)?.reversed(), "reversed")?),
2198                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
2199            ];
2200            let mid = &samples[half][n / 2];
2201            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
2202            caps.push(Cap { surface, front, coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre: [rho_c, z_c], start: v_low, sweep: theta_v, spans: spans_v } }) });
2203        }
2204    }
2205    Ok(Split {
2206        points,
2207        curves,
2208        caps,
2209        slides: Vec::new(),
2210        slide_sides: Vec::new(),
2211        scale: rho_c + radius,
2212        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
2213    })
2214}
2215
2216/// Builder of a closed shell with shared vertices and edges.
2217struct Shell {
2218    vertices: Vec<VertexRecord>,
2219    edges: Vec<EdgeRecord>,
2220    faces: Vec<FaceRecord>,
2221    next: u64,
2222    /// Loops beyond each face's first (holes).
2223    holes: usize,
2224}
2225
2226impl Shell {
2227    fn new() -> Self {
2228        Self { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 1, holes: 0 }
2229    }
2230
2231    fn id(&mut self) -> u64 {
2232        self.next += 1;
2233        self.next
2234    }
2235
2236    fn vertex(&mut self, point: Vec3) -> u64 {
2237        let id = self.id();
2238        self.vertices.push(VertexRecord { id, point });
2239        id
2240    }
2241
2242    fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64, degenerate: bool) -> Result<u64, KernelRefusal> {
2243        let domain = frag(curve.domain(), "edge_domain")?;
2244        let id = self.id();
2245        self.edges.push(EdgeRecord { id, curve, t0: domain[0], t1: domain[1], start_vertex_id: start, end_vertex_id: end, degenerate, name: None });
2246        Ok(id)
2247    }
2248
2249    /// A face from its surface and its loop: (edge, traversed forward?, pcurve
2250    /// in the traversal direction).
2251    fn face(&mut self, surface: NurbsSurface, coedges: Vec<(u64, bool, NurbsCurve)>) -> u64 {
2252        let mut records = Vec::with_capacity(coedges.len());
2253        for (edge, forward, pcurve) in coedges {
2254            let id = self.id();
2255            records.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2256        }
2257        let loop_id = self.id();
2258        let id = self.id();
2259        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: vec![LoopRecord { id: loop_id, coedges: records }], name: None });
2260        id
2261    }
2262
2263    /// A face from its surface and its loops, the outer one first.
2264    fn face_loops(&mut self, surface: NurbsSurface, loops: Vec<Vec<(u64, bool, NurbsCurve)>>) -> u64 {
2265        let mut records = Vec::with_capacity(loops.len());
2266        for coedges in loops {
2267            let mut list = Vec::with_capacity(coedges.len());
2268            for (edge, forward, pcurve) in coedges {
2269                let id = self.id();
2270                list.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2271            }
2272            let id = self.id();
2273            records.push(LoopRecord { id, coedges: list });
2274        }
2275        self.holes += records.len().saturating_sub(1);
2276        let id = self.id();
2277        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: records, name: None });
2278        id
2279    }
2280
2281    fn solid(mut self) -> BrepSolid {
2282        let shell = self.id();
2283        let id = self.id();
2284        // One shell: V − E + F = 2 − 2g (every face one loop; a pole's
2285        // degenerate edge is not counted, as the validator counts).
2286        let edges = self.edges.iter().filter(|e| !e.degenerate).count() as i64;
2287        // A face with holes counts once for each loop beyond its first less.
2288        let euler = self.vertices.len() as i64 - edges + self.faces.len() as i64 - self.holes as i64;
2289        let genus = (2 - euler) / 2;
2290        BrepSolid {
2291            mass_properties_cache: Default::default(),
2292            id,
2293            vertices: self.vertices,
2294            edges: self.edges,
2295            shells: vec![ShellRecord { id: shell, faces: self.faces }],
2296            genus,
2297            kind: Default::default(),
2298            cells: Default::default(),
2299        }
2300    }
2301}
2302
2303/// The whole sweep of `tool` along `motion` (a single screw, turn or slide),
2304/// its two end positions included.
2305pub fn sweep_solid(tool: &SolidTool, motion: &SolidMotion) -> Result<BrepSolid, KernelRefusal> {
2306    sweep_with(&Screw::from_motion(motion)?, tool)
2307}
2308
2309fn sweep_with(screw: &Screw, tool: &SolidTool) -> Result<BrepSolid, KernelRefusal> {
2310    let screw = *screw;
2311    if let SolidTool::Revolved { meridian, .. } = tool {
2312        refuse_elliptic(meridian)?;
2313    }
2314    if let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool {
2315        if let Some(body) = ball_across_axis(&screw, *axis_origin, *axis_direction, meridian)? {
2316            return Ok(body);
2317        }
2318        // (A tool whose radial direction lies along its axis is left to the
2319        // refusal below.)
2320        let radial_holds = match (tool, axis_direction.normalized()) {
2321            (SolidTool::Revolved { radial, .. }, Ok(w)) => radial.sub(w.scale(radial.dot(w))).normalized().is_ok(),
2322            _ => false,
2323        };
2324        if radial_holds && ball_screw::ball_screw_on() {
2325            if let Some(body) = ball_screw::ball_screwed_past_fold(&screw, *axis_origin, *axis_direction, meridian)? {
2326                return Ok(body);
2327            }
2328        }
2329    }
2330    if let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool {
2331        if ring_fold::ring_fold_on() {
2332            if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() {
2333                if ((end - start).abs() - TAU).abs() < 1e-12 {
2334                    let w = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
2335                    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
2336                    if let Some(body) = ring_fold::ring_slid_past_fold(&screw, *axis_origin, w, u1, w.cross(u1), *centre, *radius)? {
2337                        return Ok(body);
2338                    }
2339                }
2340            }
2341        }
2342        if let Some(body) = flat_ring(&screw, *axis_origin, *axis_direction, *radial, meridian)? {
2343            return Ok(body);
2344        }
2345        if let Some(body) = rod_across_axis(&screw, *axis_origin, *axis_direction, meridian)? {
2346            return Ok(body);
2347        }
2348    }
2349    if let SolidTool::Polyhedron { vertices, faces } = tool {
2350        let whole = screw.omega != 0.0 && screw.c == 0.0 && screw.c2 == 0.0 && screw.frame.is_none() && screw.turns.is_none() && screw.omega.abs() * (screw.t1 - screw.t0) >= TAU * (1.0 - 1e-12);
2351        if whole {
2352            return whole_turn_shadow(&screw, vertices, faces);
2353        }
2354    }
2355    let split = match tool {
2356        SolidTool::Polyhedron { vertices, faces } => split_polyhedron(&screw, vertices, faces)?,
2357        SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } => {
2358            split_revolved(&screw, *axis_origin, *axis_direction, *radial, meridian)?
2359        }
2360    };
2361    let grazing = split.grazing()?;
2362    // A tool slid along its own axis has no grazing curve: its sliding sides
2363    // join its back at the start to its front at the end.
2364    if grazing.is_empty() && split.slide_sides.is_empty() {
2365        return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
2366    }
2367    let times = row_times(&screw);
2368    let last = times.len() - 1;
2369    let mut shell = Shell::new();
2370    // Vertices and edges at the row times (0 and `last` are the end positions),
2371    // made on demand.
2372    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
2373    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
2374    let mut at_time = |shell: &mut Shell, j: usize, p: usize| -> u64 {
2375        *vertex_at.entry((j, p)).or_insert_with(|| shell.vertex(screw.apply(times[j], split.points[p])))
2376    };
2377    let mut time_edge = |shell: &mut Shell, j: usize, c: usize, vertex: &mut dyn FnMut(&mut Shell, usize, usize) -> u64| -> Result<u64, KernelRefusal> {
2378        if let Some(&edge) = edge_at.get(&(j, c)) {
2379            return Ok(edge);
2380        }
2381        let curve = &split.curves[c];
2382        let (a, b) = (vertex(shell, j, curve.start), vertex(shell, j, curve.end));
2383        let edge = shell.edge(screw.move_curve(times[j], &curve.curve)?, a, b, curve.degenerate)?;
2384        edge_at.insert((j, c), edge);
2385        Ok(edge)
2386    };
2387    // Caps: the back at t0, the front at t1.
2388    for cap in &split.caps {
2389        let j = if cap.front { last } else { 0 };
2390        let surface = screw.move_surface(times[j], &cap.surface)?;
2391        let mut coedges = Vec::with_capacity(cap.coedges.len());
2392        for (c, forward, pcurve) in &cap.coedges {
2393            let edge = time_edge(&mut shell, j, *c, &mut at_time)?;
2394            coedges.push((edge, *forward, pcurve.clone()));
2395        }
2396        shell.face(surface, coedges);
2397    }
2398    // Walls, a row at a time. The back cap at t0 runs K's curve with the back
2399    // on its left, so the wall beside it runs the other way: u along the curve
2400    // that way, v from the row's start to its end, the loop (u0,0) (u1,0)
2401    // (u1,1) (u0,1).
2402    // The paths of K's corners, a row at a time: (row, point) -> edge.
2403    let mut orbit_at: HashMap<(usize, usize), u64> = HashMap::new();
2404    for row in 0..last {
2405        let (ta, tb) = (times[row], times[row + 1]);
2406        let segments = carry_segments(&screw, ta, tb);
2407        let knots_v = carry_knots(segments);
2408        let mut orbits: HashMap<usize, u64> = HashMap::new();
2409        for &(c, _) in &grazing {
2410            for r in [split.curves[c].start, split.curves[c].end] {
2411                if orbits.contains_key(&r) {
2412                    continue;
2413                }
2414                let (v0, v1) = (at_time(&mut shell, row, r), at_time(&mut shell, row + 1, r));
2415                let edge = shell.edge(carry_curve(&screw, split.points[r], ta, tb, segments)?, v0, v1, false)?;
2416                orbits.insert(r, edge);
2417                orbit_at.insert((row, r), edge);
2418            }
2419        }
2420        for &(c, back_forward) in &grazing {
2421            let tool_curve = &split.curves[c];
2422            let along = if back_forward { frag(tool_curve.curve.reversed(), "reversed")? } else { tool_curve.curve.clone() };
2423            let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
2424            let mut rows = Vec::with_capacity(along.control_points.len());
2425            for p in &along.control_points {
2426                let x = frag(p.point(), "control_point")?;
2427                rows.push(carry_points(&screw, x, ta, tb, segments).into_iter().map(|q| Vec4::from_point(q, p.w)).collect::<Vec<_>>());
2428            }
2429            let surface = frag(NurbsSurface::new(along.degree, 5, along.knots.clone(), knots_v.clone(), rows), "wall")?;
2430            let [u0, u1] = frag(along.domain(), "domain")?;
2431            let bottom = time_edge(&mut shell, row, c, &mut at_time)?;
2432            let top = time_edge(&mut shell, row + 1, c, &mut at_time)?;
2433            let coedges = vec![
2434                (bottom, !back_forward, uv_line([u0, 0.0], [u1, 0.0])?),
2435                (orbits[&to], true, uv_line([u1, 0.0], [u1, 1.0])?),
2436                (top, back_forward, uv_line([u1, 1.0], [u0, 1.0])?),
2437                (orbits[&from], false, uv_line([u0, 1.0], [u0, 0.0])?),
2438            ];
2439            shell.face(surface, coedges);
2440        }
2441    }
2442    // Sliding ends: each rim arc where its neighbour's cap sits (back at t0,
2443    // front at t1), joined by the paths of the points where that changes.
2444    // Faces the tool slides within: the one-pass probe stands further off them.
2445    let mut sliding: std::collections::HashSet<u64> = std::collections::HashSet::new();
2446    let side_of: HashMap<usize, bool> = split.caps.iter().flat_map(|cap| cap.coedges.iter().map(move |&(c, _, _)| (c, cap.front))).collect();
2447    for slide in &split.slides {
2448        let centre = screw.apply(times[0], slide.centre);
2449        let u = screw.apply(times[0], slide.centre.add(slide.u)).sub(centre);
2450        let v = screw.apply(times[0], slide.centre.add(slide.v)).sub(centre);
2451        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2452            match side_of.get(&c) {
2453                Some(true) => Ok(last),
2454                Some(false) => Ok(0),
2455                None => Err(refuse("revolved_grazing", "a sliding end has no face beside its rim".into())),
2456            }
2457        };
2458        let mut coedges = Vec::new();
2459        let mut corners: Vec<Vec3> = Vec::new();
2460        let push = |coedges: &mut Vec<(u64, bool, NurbsCurve)>, corners: &mut Vec<Vec3>, edge: u64, forward: bool, curve: &NurbsCurve| -> Result<(), KernelRefusal> {
2461            let [d0, d1] = frag(curve.domain(), "domain")?;
2462            for k in 0..=8 {
2463                corners.push(frag(curve.evaluate(d0 + (d1 - d0) * k as f64 / 8.0), "slide")?);
2464            }
2465            coedges.push((edge, forward, plane_pcurve(centre, u, v, curve, forward)?));
2466            Ok(())
2467        };
2468        for (index, &(c, forward)) in slide.rim.iter().enumerate() {
2469            let j = row_of(c)?;
2470            let edge = time_edge(&mut shell, j, c, &mut at_time)?;
2471            push(&mut coedges, &mut corners, edge, forward, &screw.move_curve(times[j], &split.curves[c].curve)?)?;
2472            // On to the next arc's time along the path of the point between them.
2473            let (next, _) = slide.rim[(index + 1) % slide.rim.len()];
2474            let next_j = row_of(next)?;
2475            if next_j == j {
2476                continue;
2477            }
2478            let point = if forward { split.curves[c].end } else { split.curves[c].start };
2479            let rows: Vec<usize> = if next_j > j { (j..next_j).collect() } else { (next_j..j).rev().collect() };
2480            for row in rows {
2481                let Some(&orbit) = orbit_at.get(&(row, point)) else {
2482                    return Err(refuse("revolved_grazing", "a sliding end's rim changes side where no grazing curve meets it".into()));
2483                };
2484                let (ta, tb) = (times[row], times[row + 1]);
2485                let curve = carry_curve(&screw, split.points[point], ta, tb, carry_segments(&screw, ta, tb))?;
2486                push(&mut coedges, &mut corners, orbit, next_j > j, &curve)?;
2487            }
2488        }
2489        sliding.insert(shell.face(plane_patch(centre, u, v, &corners)?, coedges));
2490    }
2491    // Sliding cylinders: from the start rim where its neighbour sits to the
2492    // end rim where its neighbour sits, in halves seamed along generators.
2493    for side in &split.slide_sides {
2494        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2495            match side_of.get(&c) {
2496                Some(true) => Ok(last),
2497                Some(false) => Ok(0),
2498                None => Err(refuse("revolved_grazing", "a sliding side has no face beside its rim".into())),
2499            }
2500        };
2501        let origin = screw.apply(times[0], side.origin);
2502        let w = screw.apply(times[0], side.origin.add(side.w)).sub(origin);
2503        let rows: Vec<[usize; 2]> = side.patches.iter().map(|patch| Ok([row_of(patch.2)?, row_of(patch.3)?])).collect::<Result<_, KernelRefusal>>()?;
2504        if rows.iter().any(|r| *r != rows[0]) {
2505            return Err(refuse("revolved_grazing", "a sliding side's rim changes side along it".into()));
2506        }
2507        let [jb, ja] = rows[0];
2508        // Seams: the generator at each patch's start angle, rim point to rim point.
2509        let mut seams = Vec::with_capacity(side.patches.len());
2510        for patch in &side.patches {
2511            let (a, b) = (at_time(&mut shell, jb, patch.4[0]), at_time(&mut shell, ja, patch.4[1]));
2512            let line = frag(make_line(screw.apply(times[jb], split.points[patch.4[0]]), screw.apply(times[ja], split.points[patch.4[1]])), "seam")?;
2513            seams.push((shell.edge(line.clone(), a, b, false)?, line));
2514        }
2515        for (k, patch) in side.patches.iter().enumerate() {
2516            let surface = frag(make_revolution(origin, w, &seams[k].1, patch.1), "slide_side")?;
2517            let lower = time_edge(&mut shell, jb, patch.2, &mut at_time)?;
2518            let upper = time_edge(&mut shell, ja, patch.3, &mut at_time)?;
2519            let next = (k + 1) % side.patches.len();
2520            let face = shell.face(
2521                surface,
2522                vec![
2523                    (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
2524                    (seams[next].0, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
2525                    (upper, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
2526                    (seams[k].0, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
2527                ],
2528            );
2529            sliding.insert(face);
2530        }
2531    }
2532    let body = shell.solid();
2533    let issues = body.validate();
2534    if !issues.is_empty() {
2535        return Err(refuse("assembly", format!("the assembled sweep is not valid: {:?}", issues.first())));
2536    }
2537    // A ball under one screw is proved one pass from its centre's helix
2538    // (`BREP_SWEEP_BALL_ONE_PASS`, default on): nothing for the walk to find.
2539    if !crate::solid_sweep_one_pass::ball_screw_one_pass(&screw, tool) {
2540        check_single_pass(&screw, &split, &body, &sliding)?;
2541    }
2542    Ok(body)
2543}
2544
2545/// A rod (a cylinder with flat ends) TURNED about a line that crosses its
2546/// axis squarely between its ends, if `meridian` is one and the motion such.
2547///
2548/// Arm by arm: the rod is its arm one way from the turn's axis and its arm
2549/// the other way, and sweeps what they sweep. At a height z (half-width
2550/// w = √(r² − z²)) an arm of length L is the rectangle 0 ≤ x ≤ L, |y| ≤ w,
2551/// which a circle about the turn's axis of radius ρ ≤ L meets in one arc
2552/// holding the arm's own direction, and beyond, out to √(L² + w²), in two
2553/// arcs ±[a, b] with a ≤ acos(L / √(L² + r²)). Turned by more than 2a, the
2554/// two arcs sweep the same angles as the arc [−b, b] they leave a gap in:
2555/// the arm with the gap filled, its points beyond its end within
2556/// √(L² + r²) of the crossing point (a cap of that ball). The filled arm
2557/// meets every circle in one arc holding its direction, so it sweeps itself
2558/// where it starts and where it stops and, between, its section by the half
2559/// plane at its direction turned. So the sweep is the union of the filled rod
2560/// (one solid of revolution about the rod's axis) at both ends of the turn
2561/// and the two arms' sections turned.
2562fn rod_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2563    if screw.frame.is_some() || screw.turns.is_some() || screw.omega == 0.0 || screw.c != 0.0 || screw.c2 != 0.0 {
2564        return Ok(None);
2565    }
2566    let Ok(w) = axis.normalized() else { return Ok(None) };
2567    // A rectangle against the axis: radius r from z0 to z1.
2568    let mut corners: Vec<[f64; 2]> = Vec::new();
2569    for piece in meridian {
2570        let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
2571        corners.push(*from);
2572        corners.push(*to);
2573    }
2574    if meridian.len() != 4 {
2575        return Ok(None);
2576    }
2577    let r = corners.iter().map(|c| c[0]).fold(0.0f64, f64::max);
2578    let (z0, z1) = corners.iter().map(|c| c[1]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), z| (lo.min(z), hi.max(z)));
2579    let scale = r.max(z0.abs()).max(z1.abs());
2580    let on = |a: f64, b: f64| (a - b).abs() <= 1e-12 * scale;
2581    if !(r > 0.0 && z1 > z0) || !corners.iter().all(|c| (on(c[0], 0.0) || on(c[0], r)) && (on(c[1], z0) || on(c[1], z1))) {
2582        return Ok(None);
2583    }
2584    // The turn's axis squarely across the rod's, between its ends.
2585    if w.dot(screw.e).abs() > 1e-12 {
2586        return Ok(None);
2587    }
2588    let offset = screw.a.sub(origin);
2589    let along = offset.dot(w);
2590    let foot = origin.add(w.scale(along));
2591    let apart = screw.a.sub(foot);
2592    if apart.sub(screw.e.scale(apart.dot(screw.e))).length() > 1e-12 * (scale + offset.length()) {
2593        return Ok(None);
2594    }
2595    if !(along > z0 + 1e-9 * scale && along < z1 - 1e-9 * scale) {
2596        return Ok(None);
2597    }
2598    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
2599    let arms = [z1 - along, along - z0];
2600    let gap = arms.iter().map(|l| (l / l.hypot(r)).acos()).fold(0.0f64, f64::max);
2601    if !(theta > 2.0 * gap * (1.0 + 1e-9) && theta < TAU * (1.0 - 1e-9)) {
2602        return Err(refuse("rod_across", "a rod turned about a line through it is swept only for a turn wider than its ends' gaps and short of a whole turn".into()));
2603    }
2604    let arc = |centre: Vec3, from: Vec3, normal: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
2605        let surface = frag(make_revolution(centre, normal, &frag(make_line(from, from.add(normal)), "line")?, angle), "rod_across")?;
2606        frag(surface.iso_curve_v(0.0), "rod_across")
2607    };
2608    let line = |a: Vec3, b: Vec3| frag(make_line(a, b), "rod_across");
2609    // At one time: the crossing point, the rod's direction and the turn's.
2610    let filled_at = |t: f64| -> Result<BrepSolid, KernelRefusal> {
2611        let o = screw.apply(t, foot);
2612        let x = screw.apply(t, foot.add(w)).sub(o);
2613        let up = screw.e;
2614        let at = |rho: f64, s: f64| o.add(up.scale(rho)).add(x.scale(s));
2615        let n = up.cross(x);
2616        let (far_plus, far_minus) = (arms[0].hypot(r), arms[1].hypot(r));
2617        let profile = [
2618            arc(o, at(0.0, -far_minus), n, r.atan2(arms[1]))?,
2619            line(at(r, -arms[1]), at(r, arms[0]))?,
2620            arc(o, at(r, arms[0]), n, r.atan2(arms[0]))?,
2621            line(at(0.0, far_plus), at(0.0, -far_minus))?,
2622        ];
2623        frag(crate::revolve_profile_brep(&profile, o, x, TAU), "rod_across")
2624    };
2625    let o = screw.apply(screw.t0, foot);
2626    let x = screw.apply(screw.t0, foot.add(w)).sub(o);
2627    let turn_axis = screw.e.scale(screw.omega.signum());
2628    let section = |direction: Vec3, length: f64| -> Result<BrepSolid, KernelRefusal> {
2629        let at = |rho: f64, z: f64| o.add(direction.scale(rho)).add(screw.e.scale(z));
2630        let half = (r / length.hypot(r)).asin();
2631        let profile = [
2632            line(at(0.0, -r), at(length, -r))?,
2633            arc(o, at(length, -r), direction.cross(screw.e), 2.0 * half)?,
2634            line(at(length, r), at(0.0, r))?,
2635            line(at(0.0, r), at(0.0, -r))?,
2636        ];
2637        frag(crate::revolve_profile_brep(&profile, o, turn_axis, theta), "rod_across")
2638    };
2639    let parts = [filled_at(screw.t0)?, filled_at(screw.t1)?, section(x, arms[0])?, section(x.scale(-1.0), arms[1])?];
2640    crate::boolean_operation_nary(&parts, crate::BooleanOperation::Union).map(Some)
2641}
2642
2643/// `BREP_SWEEP_RING_LENS_SEWN` (on by default; `=0` restores the booleans): a
2644/// ring slid flat short of its
2645/// hole's width is the filled ring's sweep less the lens its hole leaves open
2646/// at both ends. That lens is built here and sewn into the sweep's top and
2647/// bottom faces in place of the two booleans (the lens intersect and the
2648/// subtract): its caps are the two holes' top and bottom discs in common,
2649/// whose outlines become inner loops of the sweep's flat faces, and its walls
2650/// are the two holes' own tube surfaces, meeting in the slide's bisector
2651/// plane along `y(ψ) = √(ρ(ψ)² − D²/4)`, `ρ = R − r cos ψ`, `z = r sin ψ`
2652/// (the tube's section by that plane, interpolated through exact points and
2653/// read back against them). A lens that pinches at the tube's middle (`D ≥
2654/// 2 (R − r)`) or anything that does not validate is left to the booleans.
2655pub(crate) fn ring_lens_sewn_on() -> bool {
2656    crate::switch!("BREP_SWEEP_RING_LENS_SEWN", true)
2657}
2658
2659/// `BREP_SWEEP_RING_LENS_SEWN_CHECK` (default off): both built, the booleans'
2660/// body kept; the sewn one's volume and area compared with it
2661/// ([`ring_lens_check_take`]).
2662fn ring_lens_sewn_check_on() -> bool {
2663    crate::switch!("BREP_SWEEP_RING_LENS_SEWN_CHECK", false)
2664}
2665
2666thread_local! {
2667    static RING_LENS_CHECK: std::cell::Cell<(u64, u64, f64)> = const { std::cell::Cell::new((0, 0, 0.0)) };
2668}
2669
2670/// (bodies compared, sewn bodies missing or differing past `1e-7` relative
2671/// in volume or area, the worst relative difference) on this thread since the
2672/// last call. The bar is the booleans' own error, the bench's tier: the sewn
2673/// body reads the closed form to `1e-10` where the booleans' body reads it
2674/// `2.9e-9` off (tube 2 round 6, slid 6) and `3.8e-8` off (tube 1 round 5,
2675/// slid 3).
2676pub fn ring_lens_check_take() -> (u64, u64, f64) {
2677    RING_LENS_CHECK.with(|cell| cell.replace((0, 0, 0.0)))
2678}
2679
2680fn ring_lens_check_record(cut: &BrepSolid, sewn: Option<&BrepSolid>) {
2681    let worst = match (crate::solid_mass_properties(cut), sewn.map(crate::solid_mass_properties)) {
2682        (Ok(a), Some(Ok(b))) => ((a.volume - b.volume) / a.volume).abs().max(((a.surface_area - b.surface_area) / a.surface_area).abs()),
2683        _ => f64::INFINITY,
2684    };
2685    RING_LENS_CHECK.with(|cell| {
2686        let (n, bad, w) = cell.get();
2687        cell.set((n + 1, bad + u64::from(!(worst <= 1e-7)), w.max(worst)));
2688    });
2689}
2690
2691/// The filled ring's sweep `whole` (a slide of the ring's centre from `c0` to
2692/// `c1`, square to its axis `w`, its tube `tube` round the circle of radius
2693/// `big`) less the lens both holes share, built directly. `None` where it
2694/// does not apply or does not validate.
2695fn sewn_lens(whole: &BrepSolid, c0: Vec3, c1: Vec3, w: Vec3, big: f64, tube: f64) -> Option<BrepSolid> {
2696    let slide = c1.sub(c0);
2697    let d = slide.length();
2698    let scale = (big + tube + d).max(1e-300);
2699    if !(slide.dot(w).abs() <= 1e-12 * scale && d > 1e-9 * scale && d < 2.0 * (big - tube) * (1.0 - 1e-9)) {
2700        return None;
2701    }
2702    let ed = slide.scale(1.0 / d);
2703    let ey = w.cross(ed);
2704    let mid = c0.add(ed.scale(0.5 * d));
2705    let half = 0.5 * d;
2706    let alpha = (half / big).acos();
2707    let y_top = (big * big - half * half).sqrt();
2708    let corner = |side: f64, z: f64| mid.add(ey.scale(side * y_top)).add(w.scale(z));
2709    let (t_plus, t_minus, b_plus, b_minus) = (corner(1.0, tube), corner(-1.0, tube), corner(1.0, -tube), corner(-1.0, -tube));
2710    // The flat faces the caps sit in.
2711    let shell = whole.shells.first()?;
2712    let flat_at = |z: f64| -> Option<usize> {
2713        shell.faces.iter().position(|f| {
2714            f.loops.len() == 1
2715                && f.surface.degree_u == 1
2716                && f.surface.degree_v == 1
2717                && f.surface.control_points.iter().flatten().all(|c| c.point().map(|p| (p.sub(c0).dot(w) - z).abs() <= 1e-12 * scale).unwrap_or(false))
2718        })
2719    };
2720    let (top, bottom) = (flat_at(tube)?, flat_at(-tube)?);
2721    // Edges. Arcs: A on the circle about c0 (the lens's side away from c0's
2722    // far rim: angles −α..α from ed), B about c1 (π−α..π+α).
2723    let arc = |centre: Vec3, from: f64, to: f64| crate::make_arc(centre, ed, ey, big, from, to).ok();
2724    let a_top = arc(c0.add(w.scale(tube)), -alpha, alpha)?; // t_minus -> t_plus
2725    let b_top = arc(c1.add(w.scale(tube)), PI - alpha, PI + alpha)?; // t_plus -> t_minus
2726    let a_bot = arc(c0.add(w.scale(-tube)), -alpha, alpha)?; // b_minus -> b_plus
2727    let b_bot = arc(c1.add(w.scale(-tube)), PI - alpha, PI + alpha)?; // b_plus -> b_minus
2728    // The walls' carriers: each hole's inner tube half turned a whole turn
2729    // about its axis, its generatrix drawn opposite the lens (the turn's seam
2730    // away from the wall).
2731    let wall_surface = |centre: Vec3, away: Vec3| -> Option<NurbsSurface> {
2732        let n = w.cross(away);
2733        let at = |rho: f64, z: f64| centre.add(away.scale(rho)).add(w.scale(z));
2734        let from = at(big, -tube);
2735        let half_round = crate::make_revolution(at(big, 0.0), n, &crate::make_line(from, from.add(n)).ok()?, PI).ok()?.iso_curve_v(0.0).ok()?;
2736        crate::make_revolution(centre, w, &half_round, TAU).ok()
2737    };
2738    let (wall_a, wall_b) = (wall_surface(c0, ed.scale(-1.0))?, wall_surface(c1, ed)?);
2739    // Seams, bottom to top, through exact points of the bisector section, with
2740    // their pcurves on both walls interpolated through the same points' feet
2741    // at the same parameters; all three read back at the mid-samples.
2742    // (Each seam in two halves, split at the tube's waist ψ = 0: the walls'
2743    // half-round generatrix is two quarter arcs, its parameter speed jumps
2744    // there, and a pcurve through it would kink.)
2745    let seam = |side: f64, from: f64, to: f64| -> Option<(NurbsCurve, NurbsCurve, NurbsCurve)> {
2746        let at = |psi: f64| {
2747            let rho = big - tube * psi.cos();
2748            mid.add(ey.scale(side * (rho * rho - half * half).max(0.0).sqrt())).add(w.scale(tube * psi.sin()))
2749        };
2750        let feet = |surface: &NurbsSurface, points: &[Vec3]| -> Option<Vec<Vec3>> {
2751            let mut out: Vec<Vec3> = Vec::with_capacity(points.len());
2752            for point in points {
2753                // From the last foot; where that lands off the point (the tube
2754                // turning fast near its top and bottom), the global reading.
2755                let seeded = out.last().and_then(|last| crate::project_point_to_surface_seeded(surface, *point, last.x, last.y).ok());
2756                let q = match seeded {
2757                    Some(q) if q.distance <= 1e-7 * scale => q,
2758                    _ => crate::project_point_to_surface(surface, *point).ok()?,
2759                };
2760                // The projector stops near 1e-9; the point is on the carrier
2761                // exactly, so Gauss-Newton on |S(u, v) − p|² takes the foot to
2762                // rounding.
2763                let (mut u, mut v) = (q.u, q.v);
2764                for _ in 0..4 {
2765                    let d = surface.derivatives(u, v, 1).ok()?;
2766                    let (f, su, sv) = (d[0][0].sub(*point), d[1][0], d[0][1]);
2767                    let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv));
2768                    let (g0, g1) = (su.dot(f), sv.dot(f));
2769                    let det = a * c - b * b;
2770                    if !(det > 0.0) {
2771                        return None;
2772                    }
2773                    u -= (c * g0 - b * g1) / det;
2774                    v -= (a * g1 - b * g0) / det;
2775                }
2776                if !(surface.evaluate(u, v).ok()?.sub(*point).length() <= 1e-11 * scale) {
2777                    return None;
2778                }
2779                out.push(Vec3::new(u, v, 0.0));
2780            }
2781            Some(out)
2782        };
2783        let mut n = 16usize;
2784        loop {
2785            let psis: Vec<f64> = (0..=n).map(|k| from + (to - from) * k as f64 / n as f64).collect();
2786            let points: Vec<Vec3> = psis.iter().map(|&psi| at(psi)).collect();
2787            let params: Vec<f64> = psis.iter().map(|psi| (psi - from) / (to - from)).collect();
2788            let curve = crate::interpolate_curve(&points, 3, &params).ok()?;
2789            let on_a = crate::interpolate_curve(&feet(&wall_a, &points)?, 3, &params).ok()?;
2790            let on_b = crate::interpolate_curve(&feet(&wall_b, &points)?, 3, &params).ok()?;
2791            let mut worst = 0.0f64;
2792            for k in 0..n {
2793                let psi = 0.5 * (psis[k] + psis[k + 1]);
2794                let t = (psi - from) / (to - from);
2795                let p = curve.evaluate(t).ok()?;
2796                worst = worst.max(p.sub(at(psi)).length());
2797                for (surface, pcurve) in [(&wall_a, &on_a), (&wall_b, &on_b)] {
2798                    let uv = pcurve.evaluate(t).ok()?;
2799                    worst = worst.max(surface.evaluate(uv.x, uv.y).ok()?.sub(p).length());
2800                }
2801            }
2802            if worst <= 1e-10 * scale {
2803                return Some((curve, on_a, on_b));
2804            }
2805            if n >= 4096 {
2806                return None;
2807            }
2808            n *= 2;
2809        }
2810    };
2811    let (lower_plus, upper_plus) = (seam(1.0, -0.5 * PI, 0.0)?, seam(1.0, 0.0, 0.5 * PI)?);
2812    let (lower_minus, upper_minus) = (seam(-1.0, -0.5 * PI, 0.0)?, seam(-1.0, 0.0, 0.5 * PI)?);
2813    let waist = |side: f64| mid.add(ey.scale(side * ((big - tube).powi(2) - half * half).sqrt()));
2814    let (m_plus, m_minus) = (waist(1.0), waist(-1.0));
2815    // Ids past every existing one.
2816    let mut next = whole.vertices.iter().map(|v| v.id).chain(whole.edges.iter().map(|e| e.id)).chain(shell.faces.iter().flat_map(|f| std::iter::once(f.id).chain(f.loops.iter().flat_map(|l| std::iter::once(l.id).chain(l.coedges.iter().map(|c| c.id)))))).max().unwrap_or(0) + 1;
2817    let mut id = || {
2818        next += 1;
2819        next
2820    };
2821    let mut body = whole.clone();
2822    let vertex = |body: &mut BrepSolid, id: u64, point: Vec3| body.vertices.push(VertexRecord { id, point });
2823    let (vt_plus, vt_minus, vb_plus, vb_minus, vm_plus, vm_minus) = (id(), id(), id(), id(), id(), id());
2824    vertex(&mut body, vm_plus, m_plus);
2825    vertex(&mut body, vm_minus, m_minus);
2826    vertex(&mut body, vt_plus, t_plus);
2827    vertex(&mut body, vt_minus, t_minus);
2828    vertex(&mut body, vb_plus, b_plus);
2829    vertex(&mut body, vb_minus, b_minus);
2830    let mut edge = |body: &mut BrepSolid, curve: NurbsCurve, start: u64, end: u64| -> Option<u64> {
2831        let [t0, t1] = curve.domain().ok()?;
2832        let e = id();
2833        body.edges.push(EdgeRecord { id: e, curve, t0, t1, start_vertex_id: start, end_vertex_id: end, degenerate: false, name: None });
2834        Some(e)
2835    };
2836    // The arcs' ends must be the corners they are named for.
2837    for (curve, a, b) in [(&a_top, t_minus, t_plus), (&b_top, t_plus, t_minus), (&a_bot, b_minus, b_plus), (&b_bot, b_plus, b_minus), (&lower_plus.0, b_plus, m_plus), (&upper_plus.0, m_plus, t_plus), (&lower_minus.0, b_minus, m_minus), (&upper_minus.0, m_minus, t_minus)] {
2838        let [t0, t1] = curve.domain().ok()?;
2839        if curve.evaluate(t0).ok()?.sub(a).length() > 1e-9 * scale || curve.evaluate(t1).ok()?.sub(b).length() > 1e-9 * scale {
2840            return None;
2841        }
2842    }
2843    // The seams' pcurves, built with them: (edge, wall, pcurve along the edge).
2844    let mut given: Vec<(u64, usize, NurbsCurve)> = Vec::new();
2845    let e_a_top = edge(&mut body, a_top, vt_minus, vt_plus)?;
2846    let e_b_top = edge(&mut body, b_top, vt_plus, vt_minus)?;
2847    let e_a_bot = edge(&mut body, a_bot, vb_minus, vb_plus)?;
2848    let e_b_bot = edge(&mut body, b_bot, vb_plus, vb_minus)?;
2849    let mut seam_edge = |body: &mut BrepSolid, piece: (NurbsCurve, NurbsCurve, NurbsCurve), start: u64, end: u64, given: &mut Vec<(u64, usize, NurbsCurve)>| -> Option<u64> {
2850        let (curve, on_a, on_b) = piece;
2851        let e = edge(body, curve, start, end)?;
2852        given.extend([(e, 1, on_a), (e, 2, on_b)]);
2853        Some(e)
2854    };
2855    let e_lp = seam_edge(&mut body, lower_plus, vb_plus, vm_plus, &mut given)?;
2856    let e_up = seam_edge(&mut body, upper_plus, vm_plus, vt_plus, &mut given)?;
2857    let e_lm = seam_edge(&mut body, lower_minus, vb_minus, vm_minus, &mut given)?;
2858    let e_um = seam_edge(&mut body, upper_minus, vm_minus, vt_minus, &mut given)?;
2859    let curve_of = |body: &BrepSolid, e: u64| body.edges.iter().find(|x| x.id == e).map(|x| x.curve.clone());
2860    // A coedge of edge `e` on `surface`, forward or reversed, with its pcurve
2861    // fitted along the coedge.
2862    let coedge = |body: &BrepSolid, id: u64, surface: &NurbsSurface, e: u64, forward: bool, given: &[(u64, usize, NurbsCurve)], wall: usize| -> Option<CoedgeRecord> {
2863        if let Some((_, _, pcurve)) = given.iter().find(|(edge, on, _)| *edge == e && *on == wall) {
2864            let pcurve = if forward { pcurve.clone() } else { pcurve.reversed().ok()? };
2865            return Some(CoedgeRecord { id, edge_id: e, forward, pcurve });
2866        }
2867        let fit = crate::fit_pcurve_on_surface(surface, &curve_of(body, e)?).ok()?;
2868        if !(fit.report.residual <= 1e-7 * scale) {
2869            return None;
2870        }
2871        let pcurve = if forward { fit.curve } else { fit.curve.reversed().ok()? };
2872        Some(CoedgeRecord { id, edge_id: e, forward, pcurve })
2873    };
2874    // The loop's signed area in its face's parameters.
2875    let uv_area = |coedges: &[CoedgeRecord]| -> f64 {
2876        let mut area = 0.0;
2877        for c in coedges {
2878            let Ok([p0, p1]) = c.pcurve.domain() else { return f64::NAN };
2879            let samples = 64;
2880            let mut last = match c.pcurve.evaluate(p0) { Ok(p) => p, Err(_) => return f64::NAN };
2881            for k in 1..=samples {
2882                let Ok(p) = c.pcurve.evaluate(p0 + (p1 - p0) * k as f64 / samples as f64) else { return f64::NAN };
2883                area += last.x * p.y - p.x * last.y;
2884                last = p;
2885            }
2886        }
2887        0.5 * area
2888    };
2889    // Caps: the top's hole runs clockwise seen from outside (from +w), the
2890    // bottom's clockwise seen from −w.
2891    for (face_index, loop_edges) in [(top, [(e_a_top, false), (e_b_top, false)]), (bottom, [(e_a_bot, true), (e_b_bot, true)])] {
2892        let surface = body.shells[0].faces[face_index].surface.clone();
2893        let mut coedges = Vec::new();
2894        for (e, forward) in loop_edges {
2895            let c = id();
2896            coedges.push(coedge(&body, c, &surface, e, forward, &given, 0)?);
2897        }
2898        // An inner loop runs opposite its face's outer loop in the parameters.
2899        let outer = uv_area(&body.shells[0].faces[face_index].loops[0].coedges);
2900        let inner = uv_area(&coedges);
2901        if !(outer.is_finite() && inner.is_finite() && outer * inner < 0.0) {
2902            return None;
2903        }
2904        let loop_id = id();
2905        body.shells[0].faces[face_index].loops.push(LoopRecord { id: loop_id, coedges });
2906    }
2907    // Walls: A uses the arcs the caps reversed and B likewise, the seams once each way.
2908    for (wall, surface, centre, loop_edges) in [
2909        (1usize, wall_a, c0, vec![(e_a_top, true), (e_up, false), (e_lp, false), (e_a_bot, false), (e_lm, true), (e_um, true)]),
2910        (2usize, wall_b, c1, vec![(e_b_top, true), (e_um, false), (e_lm, false), (e_b_bot, false), (e_lp, true), (e_up, true)]),
2911    ] {
2912        let mut coedges = Vec::new();
2913        for (e, forward) in loop_edges {
2914            let c = id();
2915            coedges.push(coedge(&body, c, &surface, e, forward, &given, wall)?);
2916        }
2917        let area = uv_area(&coedges);
2918        if !(area.is_finite() && area != 0.0) {
2919            return None;
2920        }
2921        // Counter-clockwise in the parameters: the loop's outward is the
2922        // surface's normal side; it must face into the lens (towards the
2923        // hole's own axis).
2924        let same_sense = area > 0.0;
2925        let face_id = id();
2926        let loop_id = id();
2927        let face = FaceRecord { id: face_id, surface, same_sense, loops: vec![LoopRecord { id: loop_id, coedges }], name: None };
2928        // Sense check at the wall's middle: towards the hole's axis.
2929        let middle = mid.add(ed.scale(if centre.sub(c0).length() == 0.0 { big - tube - half } else { -(big - tube - half) }));
2930        let q = crate::project_point_to_surface(&face.surface, middle).ok()?;
2931        let n = face.surface.normal(q.u, q.v).ok()?;
2932        let n = if face.same_sense { n } else { n.scale(-1.0) };
2933        let toward_axis = centre.sub(middle);
2934        let toward_axis = toward_axis.sub(w.scale(toward_axis.dot(w)));
2935        if !(n.dot(toward_axis) > 0.0) {
2936            return None;
2937        }
2938        body.shells[0].faces.push(face);
2939    }
2940    // The lens runs through from the top face to the bottom: one handle more.
2941    body.genus = whole.genus + 1;
2942    body.mass_properties_cache = Default::default();
2943    if body.validate().iter().any(|issue| issue.severity == "error") {
2944        return None;
2945    }
2946    Some(body)
2947}
2948
2949/// A ring (or another tool with a hole about its axis walled straight
2950/// through) lying flat to its motion (a turn about an axis parallel to the
2951/// tool's, a slide square to it), if `meridian` is one and the motion such.
2952///
2953/// Every point then moves in its own plane square to the ring's axis, where
2954/// the ring's section is an annulus. The tube passes over where the hole was,
2955/// so the sweep does not pass each point once; but an annulus sweeps what its
2956/// filled disc sweeps as soon as it travels far enough that no point stays in
2957/// the hole from start to end (the hole at the start and at the end share
2958/// nothing: travel beyond the hole's greatest width, the tube's centre
2959/// circle). So the ring sweeps what the FILLED ring sweeps: a tool with a
2960/// half-round rim and flat faces, which is swept whole. A whole turn sweeps
2961/// the solid of revolution of that tool's shadow about the turn's axis.
2962fn flat_ring(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2963    if screw.frame.is_some() || screw.turns.is_some() || screw.c2 != 0.0 {
2964        return Ok(None);
2965    }
2966    let Ok(w) = axis.normalized() else { return Ok(None) };
2967    let flat = if screw.omega != 0.0 { screw.e.cross(w).length() <= 1e-12 && screw.c == 0.0 } else { screw.e.dot(w).abs() <= 1e-12 };
2968    if !flat {
2969        return Ok(None);
2970    }
2971    // The holed tool: a torus (`torus`: its tube), or straight-sided pieces
2972    // whose hole is one upright wall from the tool's top to its bottom.
2973    // `big`: half the hole's greatest width. `filled_meridian`: the tool
2974    // with its hole closed, flat across at its top and bottom.
2975    let (big, level, torus, filled_meridian): (f64, f64, Option<f64>, Vec<OutlinePiece>) = match meridian {
2976        [OutlinePiece::Arc { centre, radius, start, end }] => {
2977            let (big, tube, level) = (centre[0], *radius, centre[1]);
2978            if ((end - start).abs() - TAU).abs() >= 1e-12 || big <= tube {
2979                return Ok(None);
2980            }
2981            (
2982                big,
2983                level,
2984                Some(tube),
2985                vec![
2986                    OutlinePiece::Line { from: [0.0, level - tube], to: [big, level - tube] },
2987                    OutlinePiece::Arc { centre: [big, level], radius: tube, start: -0.5 * PI, end: 0.5 * PI },
2988                    OutlinePiece::Line { from: [big, level + tube], to: [0.0, level + tube] },
2989                    OutlinePiece::Line { from: [0.0, level + tube], to: [0.0, level - tube] },
2990                ],
2991            )
2992        }
2993        pieces => {
2994            let mut ends: Vec<([f64; 2], [f64; 2])> = Vec::with_capacity(pieces.len());
2995            for piece in pieces {
2996                let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
2997                ends.push((*from, *to));
2998            }
2999            let scale = ends.iter().flat_map(|(a, b)| [a[0].abs(), a[1].abs(), b[0].abs(), b[1].abs()]).fold(0.0f64, f64::max).max(1e-300);
3000            let inner = ends.iter().flat_map(|(a, b)| [a[0], b[0]]).fold(f64::INFINITY, f64::min);
3001            let (low, high) = ends.iter().flat_map(|(a, b)| [a[1], b[1]]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), z| (lo.min(z), hi.max(z)));
3002            if ends.len() < 3 || inner <= 1e-9 * scale {
3003                return Ok(None);
3004            }
3005            let walls: Vec<usize> = (0..ends.len())
3006                .filter(|&k| {
3007                    let (a, b) = ends[k];
3008                    (a[0] - inner).abs() <= 1e-12 * scale && (b[0] - inner).abs() <= 1e-12 * scale && (a[1].min(b[1]) - low).abs() <= 1e-12 * scale && (a[1].max(b[1]) - high).abs() <= 1e-12 * scale
3009                })
3010                .collect();
3011            let [wall] = walls.as_slice() else { return Ok(None) };
3012            let (from, to) = ends[*wall];
3013            // From the wall's end round the outside back to its start, then
3014            // across to the axis and along it.
3015            let mut filled = vec![OutlinePiece::Line { from: [0.0, to[1]], to }];
3016            for k in 1..pieces.len() {
3017                filled.push(pieces[(wall + k) % pieces.len()].clone());
3018            }
3019            filled.push(OutlinePiece::Line { from, to: [0.0, from[1]] });
3020            filled.push(OutlinePiece::Line { from: [0.0, from[1]], to: [0.0, to[1]] });
3021            (inner, 0.5 * (low + high), None, filled)
3022        }
3023    };
3024    let centre0 = origin.add(w.scale(level));
3025    let filled = SolidTool::Revolved { axis_origin: origin, axis_direction: w, radial, meridian: filled_meridian };
3026    let short = || refuse("ring_flat", "a ring lying flat to its motion travels less than its hole is wide: the hole is not swept shut".into());
3027    if screw.omega == 0.0 {
3028        if screw.c.abs() * (screw.t1 - screw.t0) <= 2.0 * big * (1.0 + 1e-9) {
3029            let Some(tube) = torus else { return Err(short()) };
3030            // Short of its hole: what stays open, all the way through, is the
3031            // lens the hole shares where the ring starts and where it stops.
3032            // The hole at one place: inside the ring's inner half, between
3033            // its top and bottom planes.
3034            let hole = |t: f64| -> Result<BrepSolid, KernelRefusal> {
3035                let o = screw.apply(t, centre0);
3036                let u = frag(radial.sub(w.scale(radial.dot(w))).normalized(), "ring_flat")?;
3037                let at = |rho: f64, z: f64| o.add(u.scale(rho)).add(w.scale(z));
3038                let n = w.cross(u);
3039                let from = at(big, -tube);
3040                let inner = frag(frag(make_revolution(at(big, 0.0), n, &frag(make_line(from, from.add(n)), "line")?, PI), "ring_flat")?.iso_curve_v(0.0), "ring_flat")?;
3041                let profile = [
3042                    frag(make_line(at(0.0, -tube), at(big, -tube)), "ring_flat")?,
3043                    inner,
3044                    frag(make_line(at(big, tube), at(0.0, tube)), "ring_flat")?,
3045                    frag(make_line(at(0.0, tube), at(0.0, -tube)), "ring_flat")?,
3046                ];
3047                frag(crate::revolve_profile_brep(&profile, o, w, TAU), "ring_flat")
3048            };
3049            let (sewn_on, sewn_check) = (ring_lens_sewn_on(), ring_lens_sewn_check_on());
3050            if sewn_on || sewn_check {
3051                let whole = sweep_with(screw, &filled)?;
3052                let c0 = screw.apply(screw.t0, centre0);
3053                let c1 = screw.apply(screw.t1, centre0);
3054                let sewn = sewn_lens(&whole, c0, c1, w, big, tube);
3055                if sewn_check {
3056                    let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
3057                    let cut = crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract)?;
3058                    ring_lens_check_record(&cut, sewn.as_ref());
3059                    return Ok(Some(cut));
3060                }
3061                if let Some(body) = sewn {
3062                    return Ok(Some(body));
3063                }
3064            }
3065            let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
3066            let whole = sweep_with(screw, &filled)?;
3067            return crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract).map(Some);
3068        }
3069        return sweep_with(screw, &filled).map(Some);
3070    }
3071    // A turn: the ring's centre runs a circle of radius `reach` about the axis.
3072    let start_centre = screw.apply(screw.t0, centre0);
3073    let from_axis = start_centre.sub(screw.a);
3074    let across = from_axis.sub(screw.e.scale(from_axis.dot(screw.e)));
3075    let reach = across.length();
3076    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
3077    if theta >= TAU * (1.0 - 1e-12) {
3078        let Some(tube) = torus else {
3079            return Err(refuse("ring_flat", "a whole turn of a holed tool in its own plane is swept for a ring only".into()));
3080        };
3081        if reach <= (big + tube) * (1.0 + 1e-9) {
3082            return Err(refuse("ring_flat", "a ring turned a whole turn in its own plane reaches the turn's axis".into()));
3083        }
3084        let out = frag(across.normalized(), "ring_flat")?;
3085        let foot = start_centre.sub(across);
3086        let at = |rho: f64, z: f64| foot.add(out.scale(rho)).add(screw.e.scale(z));
3087        let half_round = |centre: Vec3, from: Vec3| -> Result<NurbsCurve, KernelRefusal> {
3088            let n = out.cross(screw.e);
3089            let surface = frag(make_revolution(centre, n, &frag(make_line(from, from.add(n)), "line")?, PI), "ring_flat")?;
3090            frag(surface.iso_curve_v(0.0), "ring_flat")
3091        };
3092        let profile = [
3093            frag(make_line(at(reach - big, -tube), at(reach + big, -tube)), "ring_flat")?,
3094            half_round(at(reach + big, 0.0), at(reach + big, -tube))?,
3095            frag(make_line(at(reach + big, tube), at(reach - big, tube)), "ring_flat")?,
3096            half_round(at(reach - big, 0.0), at(reach - big, tube))?,
3097        ];
3098        return frag(crate::revolve_profile_brep(&profile, foot, screw.e, TAU), "ring_flat").map(Some);
3099    }
3100    let covered = if theta >= PI { big < reach } else { reach * (0.5 * theta).sin() > big * (1.0 + 1e-9) };
3101    if !covered {
3102        return Err(short());
3103    }
3104    sweep_with(screw, &filled).map(Some)
3105}
3106
3107/// The sweep of `tool` along `motion`, where it lies in `clip` (the caller
3108/// cuts a workpiece inside that region). A TURN about the clip's own axis
3109/// whose two end positions stay outside the clip's wedge covers the wedge
3110/// wholly with the tool's shadow in (ρ, z): that shadow, turned over the wedge,
3111/// is the sweep there (a convex polyhedron's shadow is bounded by conic arcs
3112/// from its edges and straight lines from its faces, so every surface is
3113/// exact); a turn about that axis whose ends reach the wedge is refused. A
3114/// screw or turn about the region's axis whose tool reaches far past the
3115/// region's radius sweeps only the tool's part that can reach it (see
3116/// `trim_to_clip`). Any other motion gets the whole sweep ([`sweep_solid`]).
3117pub fn sweep_solid_clipped(tool: &SolidTool, motion: &SolidMotion, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
3118    let screw = Screw::from_motion(motion)?;
3119    if let (SolidTool::Polyhedron { vertices, faces }, Some(wedge)) = (tool, clip.angle) {
3120        let axis = clip.axis_direction.normalized().map_err(|_| input("clip_axis", "the clip's axis has no direction".into()))?;
3121        let same_axis = screw.c == 0.0 && screw.c2 == 0.0
3122            && screw.e.cross(axis).length() < 1e-12
3123            && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
3124        if same_axis {
3125            return turn_shadow(&screw, vertices, faces, clip, axis, wedge);
3126        }
3127    }
3128    if let SolidTool::Polyhedron { vertices, faces } = tool {
3129        if let Some((vertices, faces)) = trim_to_clip(&screw, vertices, faces, clip)? {
3130            return sweep_solid(&SolidTool::Polyhedron { vertices, faces }, motion);
3131        }
3132    }
3133    sweep_solid(tool, motion)
3134}
3135
3136/// The sweep of `tool` along a turn whose rise grows as it turns, where it lies
3137/// in `clip` (as [`sweep_solid_clipped`]). Its front and back are those at
3138/// the middle of the motion; a tool whose faces change side along it is refused.
3139pub fn sweep_solid_rising(tool: &SolidTool, motion: &RisingTurn, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
3140    let screw = Screw::from_rising(motion)?;
3141    let SolidTool::Polyhedron { vertices, faces } = tool else {
3142        return Err(refuse("rising_tool", "a growing rise sweeps a polyhedron only".into()));
3143    };
3144    let (vertices, faces) = trim_to_clip(&screw, vertices, faces, clip)?.unwrap_or_else(|| (vertices.clone(), faces.clone()));
3145    sweep_with(&screw, &SolidTool::Polyhedron { vertices, faces })
3146}
3147
3148/// The sweep of `tool` along `motion` as parts whose union it is (a caller cuts
3149/// a workpiece by all of them). One part where the whole sweep passes once. A
3150/// convex polyhedron whose sweep folds over itself (a face facing away from a
3151/// screw's or turn's axis grazes along a line inside it, and the faces beyond
3152/// that line are swept over again) is split by the plane through the axis and
3153/// that line: each half grazes that face only along its cut edge, and is swept
3154/// whole. The halves' walls share cylinders about the axis.
3155pub fn sweep_solid_parts(tool: &SolidTool, motion: &SolidMotion) -> Result<Vec<BrepSolid>, KernelRefusal> {
3156    let folded = match sweep_solid(tool, motion) {
3157        Ok(body) => return Ok(vec![body]),
3158        Err(error) if refused_as(&error) == Some("folds") => error,
3159        Err(error) => return Err(error),
3160    };
3161    let SolidTool::Polyhedron { vertices, faces } = tool else { return Err(folded) };
3162    let screw = Screw::from_motion(motion)?;
3163    if screw.omega == 0.0 {
3164        return Err(folded);
3165    }
3166    let centroid = vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |a, &p| a.add(p)).scale(1.0 / vertices.len() as f64);
3167    let mut planes: Vec<(Vec3, f64)> = Vec::new();
3168    for face in faces {
3169        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
3170        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
3171        if n.dot(p.sub(centroid)) < 0.0 {
3172            n = n.scale(-1.0);
3173        }
3174        planes.push((n, n.dot(p)));
3175    }
3176    // A face square to the axis' plane through it (its normal square to the
3177    // axis) graze along the line through its foot from the axis; it folds if
3178    // it faces away from the axis and that line crosses it.
3179    for (n, d) in planes.clone() {
3180        if n.dot(screw.e).abs() > 1e-12 {
3181            continue;
3182        }
3183        let foot = screw.a.add(n.scale(d - n.dot(screw.a)));
3184        let radial = foot.sub(screw.a).sub(screw.e.scale(foot.sub(screw.a).dot(screw.e)));
3185        if radial.dot(n) <= 0.0 {
3186            continue; // faces the axis: its grazing line is the sweep's inner wall
3187        }
3188        let cut = match screw.e.cross(radial).normalized() {
3189            Ok(m) => m,
3190            Err(_) => continue,
3191        };
3192        let offset = cut.dot(screw.a);
3193        let mut parts = Vec::with_capacity(2);
3194        for sense in [1.0, -1.0] {
3195            let mut half = planes.clone();
3196            half.push((cut.scale(sense), offset * sense));
3197            let (corners, loops) = polyhedron_of_planes(&half)?;
3198            if corners.len() < 4 || loops.len() < 4 {
3199                parts.clear();
3200                break;
3201            }
3202            match sweep_solid(&SolidTool::Polyhedron { vertices: corners, faces: loops }, motion) {
3203                Ok(body) => parts.push(body),
3204                Err(_) => {
3205                    parts.clear();
3206                    break;
3207                }
3208            }
3209        }
3210        if parts.len() == 2 {
3211            return Ok(parts);
3212        }
3213    }
3214    Err(folded)
3215}
3216
3217/// A screw or turn about the clip's axis maps the clip's cylinder (radius
3218/// ≤ R) onto itself, so inside it the sweep of the tool is the sweep of any
3219/// part of the tool holding the tool's part inside the cylinder. A tool
3220/// reaching far past it (a bar pointing at the axis) is replaced by its part
3221/// inside the prism over the shadow's piece of a slightly larger disc, with
3222/// that disc's arc replaced by the two tangents at its ends: those faces graze
3223/// only along their own end edges, where the far ends of a long tool would
3224/// fold the sweep over itself. None when the tool needs no trim.
3225fn trim_to_clip(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip) -> Result<Option<(Vec<Vec3>, Vec<Vec<usize>>)>, KernelRefusal> {
3226    let Ok(axis) = clip.axis_direction.normalized() else { return Ok(None) };
3227    let same_axis = screw.omega != 0.0
3228        && screw.e.cross(axis).length() < 1e-12
3229        && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
3230    if !same_axis || !clip.radius[1].is_finite() {
3231        return Ok(None);
3232    }
3233    let ez = axis;
3234    let ex = Vec3::new(1.0, 0.0, 0.0).sub(ez.scale(ez.x)).normalized().or_else(|_| Vec3::new(0.0, 1.0, 0.0).sub(ez.scale(ez.y)).normalized()).map_err(|e| input("clip_axis", e))?;
3235    let ey = ez.cross(ex);
3236    let flat = |p: Vec3| {
3237        let r = p.sub(clip.axis_origin);
3238        [r.dot(ex), r.dot(ey)]
3239    };
3240    let radius = clip.radius[1] * 1.02;
3241    let shadow: Vec<[f64; 2]> = vertices.iter().map(|&p| flat(p)).collect();
3242    if shadow.iter().all(|q| q[0].hypot(q[1]) <= radius) {
3243        return Ok(None);
3244    }
3245    // The shadow's convex hull, counter-clockwise.
3246    let mut points = shadow.clone();
3247    points.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
3248    let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
3249    let mut hull: Vec<[f64; 2]> = Vec::new();
3250    for pass in 0..2 {
3251        let start = hull.len();
3252        let ordered: Vec<[f64; 2]> = if pass == 0 { points.clone() } else { points.iter().rev().copied().collect() };
3253        for p in ordered {
3254            while hull.len() >= start + 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
3255                hull.pop();
3256            }
3257            hull.push(p);
3258        }
3259        hull.pop();
3260    }
3261    // Where the hull's boundary leaves and re-enters the disc.
3262    let m = hull.len();
3263    let inside = |q: [f64; 2]| q[0].hypot(q[1]) <= radius;
3264    // Leave a tool that does not reach the disc, or wraps the axis.
3265    let mut nearest = f64::INFINITY;
3266    let mut wraps = true;
3267    for k in 0..m {
3268        let (a, b) = (hull[k], hull[(k + 1) % m]);
3269        let d = [b[0] - a[0], b[1] - a[1]];
3270        let t = (-(a[0] * d[0] + a[1] * d[1]) / (d[0] * d[0] + d[1] * d[1])).clamp(0.0, 1.0);
3271        nearest = nearest.min((a[0] + d[0] * t).hypot(a[1] + d[1] * t));
3272        if cross(a, b, [0.0, 0.0]) < 0.0 {
3273            wraps = false;
3274        }
3275    }
3276    if wraps || nearest >= radius || (0..m).all(|k| inside(hull[k])) {
3277        return Ok(None);
3278    }
3279    let mut leave: Vec<f64> = Vec::new();
3280    let mut enter: Vec<f64> = Vec::new();
3281    for k in 0..m {
3282        let (a, b) = (hull[k], hull[(k + 1) % m]);
3283        let d = [b[0] - a[0], b[1] - a[1]];
3284        let (qa, qb, qc) = (d[0] * d[0] + d[1] * d[1], 2.0 * (a[0] * d[0] + a[1] * d[1]), a[0] * a[0] + a[1] * a[1] - radius * radius);
3285        let disc = qb * qb - 4.0 * qa * qc;
3286        if disc <= 0.0 {
3287            continue;
3288        }
3289        for t in [(-qb - disc.sqrt()) / (2.0 * qa), (-qb + disc.sqrt()) / (2.0 * qa)] {
3290            if t > 0.0 && t < 1.0 {
3291                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
3292                let outward = 2.0 * (q[0] * d[0] + q[1] * d[1]) > 0.0;
3293                (if outward { &mut leave } else { &mut enter }).push(q[1].atan2(q[0]));
3294            }
3295        }
3296    }
3297    let ([a], [b]) = (leave.as_slice(), enter.as_slice()) else {
3298        return Err(refuse("clip_trim", "the tool's shadow leaves the clip's disc more than once".into()));
3299    };
3300    let width = (b - a).rem_euclid(TAU);
3301    if width >= 0.9 * PI {
3302        return Err(refuse("clip_trim", "the tool's shadow spans too much of the clip's circle to be trimmed".into()));
3303    }
3304    // Planes of the tool, and the two tangents (outward normals in the plane).
3305    let mut planes: Vec<(Vec3, f64)> = Vec::new();
3306    let centroid = vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &p| s.add(p)).scale(1.0 / vertices.len() as f64);
3307    for face in faces {
3308        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
3309        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
3310        if n.dot(p.sub(centroid)) < 0.0 {
3311            n = n.scale(-1.0);
3312        }
3313        planes.push((n, n.dot(p)));
3314    }
3315    for angle in [*a, *b] {
3316        let n = ex.scale(angle.cos()).add(ey.scale(angle.sin()));
3317        planes.push((n, n.dot(clip.axis_origin) + radius));
3318    }
3319    Ok(Some(polyhedron_of_planes(&planes)?))
3320}
3321
3322/// The convex polyhedron {n · p ≤ d for every plane}: its corners (where three
3323/// planes meet inside all) and a face per plane that bounds it.
3324pub fn polyhedron_of_planes(planes: &[(Vec3, f64)]) -> Result<(Vec<Vec3>, Vec<Vec<usize>>), KernelRefusal> {
3325    let k = planes.len();
3326    let mut corners: Vec<Vec3> = Vec::new();
3327    let scale = planes.iter().map(|p| p.1.abs()).fold(1.0f64, f64::max);
3328    for i in 0..k {
3329        for j in i + 1..k {
3330            for l in j + 1..k {
3331                let (a, b, c) = (planes[i].0, planes[j].0, planes[l].0);
3332                let det = a.dot(b.cross(c));
3333                if det.abs() < 1e-12 {
3334                    continue;
3335                }
3336                let p = b.cross(c).scale(planes[i].1).add(c.cross(a).scale(planes[j].1)).add(a.cross(b).scale(planes[l].1)).scale(1.0 / det);
3337                if planes.iter().all(|(n, d)| n.dot(p) - d <= 1e-9 * scale) && !corners.iter().any(|q| q.sub(p).length() <= 1e-9 * scale) {
3338                    corners.push(p);
3339                }
3340            }
3341        }
3342    }
3343    let mut faces = Vec::new();
3344    for (n, d) in planes {
3345        let on: Vec<usize> = (0..corners.len()).filter(|&c| (n.dot(corners[c]) - d).abs() <= 1e-9 * scale).collect();
3346        if on.len() < 3 {
3347            continue;
3348        }
3349        let middle = on.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &c| s.add(corners[c])).scale(1.0 / on.len() as f64);
3350        let u = frag(corners[on[0]].sub(middle).normalized(), "face_axis")?;
3351        let v = n.cross(u);
3352        let mut ordered = on.clone();
3353        ordered.sort_by(|&p, &q| {
3354            let (rp, rq) = (corners[p].sub(middle), corners[q].sub(middle));
3355            rp.dot(v).atan2(rp.dot(u)).total_cmp(&rq.dot(v).atan2(rq.dot(u)))
3356        });
3357        faces.push(ordered);
3358    }
3359    Ok((corners, faces))
3360}
3361
3362fn turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip, axis: Vec3, wedge: [f64; 2]) -> Result<BrepSolid, KernelRefusal> {
3363    let ez = axis;
3364    let ex = clip.reference.sub(ez.scale(clip.reference.dot(ez))).normalized().map_err(|_| input("clip_reference", "the clip's reference lies along its axis".into()))?;
3365    let ey = ez.cross(ex);
3366    // Turning by ω t about e = ±ez moves angles about ez by ±ω t.
3367    let rate = screw.omega * screw.e.dot(ez).signum();
3368    let local = |p: Vec3| {
3369        let r = p.sub(clip.axis_origin);
3370        [r.dot(ex), r.dot(ey), r.dot(ez)]
3371    };
3372    let corners: Vec<[f64; 3]> = vertices.iter().map(|&p| local(p)).collect();
3373    // The tool's angular extent about the axis (its corners'; the tool must
3374    // keep off the axis, so its shadow on the plane misses the origin).
3375    let mid = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
3376    let mid_angle = mid[1].atan2(mid[0]);
3377    let angles: Vec<f64> = corners.iter().map(|c| mid_angle + (c[1].atan2(c[0]) - mid_angle + PI).rem_euclid(TAU) - PI).collect();
3378    let (low, high) = (angles.iter().copied().fold(f64::INFINITY, f64::min), angles.iter().copied().fold(f64::NEG_INFINITY, f64::max));
3379    if high - low >= PI {
3380        return Err(refuse("turn_shadow", "the tool reaches round the turn's axis".into()));
3381    }
3382    let (start, end) = (rate * screw.t0, rate * screw.t1);
3383    let (first, last) = if rate > 0.0 { (start, end) } else { (end, start) };
3384    let reference = 0.5 * (wedge[0] + wedge[1]);
3385    let near = |a: f64| reference + (a - reference + PI).rem_euclid(TAU) - PI;
3386    // Before the wedge at one end, after it at the other (angles taken near the wedge).
3387    let clear = near(high + first) < wedge[0] - 1e-9 && near(low + last) > wedge[1] + 1e-9 && (last - first) < TAU;
3388    if !clear {
3389        return Err(refuse("turn_shadow", "the turned tool's ends reach the clip's wedge; its sweep there is not its turned shadow".into()));
3390    }
3391    let profile = polyhedron_shadow(&corners, faces, false)?;
3392    // The profile in the half-plane at the wedge's start angle.
3393    let (c0, s0) = (wedge[0].cos(), wedge[0].sin());
3394    let world = |rho: f64, z: f64| clip.axis_origin.add(ez.scale(z)).add(ex.scale(rho * c0)).add(ey.scale(rho * s0));
3395    let mut curves = Vec::with_capacity(profile.len());
3396    for piece in &profile {
3397        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
3398        let curve = if points.len() == 2 {
3399            frag(make_line(frag(points[0].point(), "point")?, frag(points[1].point(), "point")?), "line")?
3400        } else {
3401            frag(NurbsCurve::new(2, vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points), "conic")?
3402        };
3403        curves.push(curve);
3404    }
3405    frag(crate::revolve_profile_brep(&curves, clip.axis_origin, ez, wedge[1] - wedge[0]), "turn_shadow")
3406}
3407
3408/// A convex polyhedron turned a whole turn (no advance): the solid of
3409/// revolution of its shadow {(ρ, z)} about the turn's axis, which may pass
3410/// through it. Its corners' paths bound it only where an edge is farthest
3411/// from the axis; an edge skew to the axis turns a hyperboloid.
3412fn whole_turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
3413    let ez = screw.e;
3414    let ex = frag(ez.perpendicular(), "turn_shadow")?;
3415    let ex = frag(ex.sub(ez.scale(ex.dot(ez))).normalized(), "turn_shadow")?;
3416    let ey = ez.cross(ex);
3417    let corners: Vec<[f64; 3]> = vertices
3418        .iter()
3419        .map(|&p| {
3420            let r = screw.apply(screw.t0, p).sub(screw.a);
3421            [r.dot(ex), r.dot(ey), r.dot(ez)]
3422        })
3423        .collect();
3424    let profile = polyhedron_shadow(&corners, faces, true)?;
3425    // A point of the outline on the axis to round-off is on it.
3426    let reach = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(0.0f64, f64::max);
3427    let world = |rho: f64, z: f64| screw.a.add(ez.scale(z)).add(ex.scale(if rho.abs() <= 1e-10 * reach { 0.0 } else { rho }));
3428    let mut curves = Vec::with_capacity(profile.len());
3429    // The outline's stretch along the axis, as one edge (it comes a piece per
3430    // corner height).
3431    let on_axis = |piece: &ShadowPiece| piece.iter().all(|&(rho, _, _)| rho.abs() <= 1e-10 * reach);
3432    let mut along: Option<(f64, f64)> = None;
3433    for piece in &profile {
3434        if on_axis(piece) {
3435            let (za, zb) = (piece[0].1, piece[piece.len() - 1].1);
3436            along = Some(match along {
3437                Some((from, _)) => (from, zb),
3438                None => (za, zb),
3439            });
3440            continue;
3441        }
3442        if let Some((from, to)) = along.take() {
3443            curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3444        }
3445        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
3446        let (first, last) = (frag(points[0].point(), "point")?, frag(points[points.len() - 1].point(), "point")?);
3447        if first.sub(last).length() <= 1e-12 * (1.0 + first.length()) {
3448            continue;
3449        }
3450        let curve = if points.len() == 2 { frag(make_line(first, last), "line")? } else { frag(NurbsCurve::new(2, vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points), "conic")? };
3451        curves.push(curve);
3452    }
3453    if let Some((from, to)) = along.take() {
3454        curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3455    }
3456    frag(crate::revolve_profile_brep(&curves, screw.a, ez, TAU), "turn_shadow")
3457}
3458
3459/// One piece of the shadow's outline: a segment (two points) or a rational
3460/// quadratic arc (three, the middle with its weight), as (ρ, z, weight).
3461type ShadowPiece = Vec<(f64, f64, f64)>;
3462
3463/// The shadow {(ρ, z)} of a convex polyhedron (corners in the axis frame):
3464/// at each z its section is a convex polygon, the ρ it reaches an interval
3465/// from the section's nearest point to its farthest corner. The farthest is
3466/// always on an edge (ρ² = quadratic in z: a conic arc); the nearest is on a
3467/// face (ρ linear in z: a segment) or an edge.
3468///
3469/// `through`: the axis may pass through the tool (its nearest ρ is then 0 and
3470/// the outline runs along the axis there); refused otherwise.
3471fn polyhedron_shadow(corners: &[[f64; 3]], faces: &[Vec<usize>], through: bool) -> Result<Vec<ShadowPiece>, KernelRefusal> {
3472    let zs: Vec<f64> = corners.iter().map(|c| c[2]).collect();
3473    let (z_low, z_high) = (zs.iter().copied().fold(f64::INFINITY, f64::min), zs.iter().copied().fold(f64::NEG_INFINITY, f64::max));
3474    let scale = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(1.0f64, f64::max);
3475    // The hull's edges (from the faces' loops) and the faces beside each.
3476    let mut edge_faces: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
3477    for (f, face) in faces.iter().enumerate() {
3478        for k in 0..face.len() {
3479            let (i, j) = (face[k], face[(k + 1) % face.len()]);
3480            edge_faces.entry((i.min(j), i.max(j))).or_default().push(f);
3481        }
3482    }
3483    let mut edges: Vec<(usize, usize)> = edge_faces.keys().copied().collect();
3484    edges.sort_unstable();
3485    // Each face's plane in the axis frame: n · p = d.
3486    let planes: Vec<([f64; 3], f64)> = faces
3487        .iter()
3488        .map(|face| {
3489            let (a, b, c) = (corners[face[0]], corners[face[1]], corners[face[2]]);
3490            let (u, v) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]);
3491            let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
3492            (n, n[0] * a[0] + n[1] * a[1] + n[2] * a[2])
3493        })
3494        .collect();
3495    #[derive(Clone, Copy, PartialEq, Debug)]
3496    enum Source {
3497        /// The crossing of edge k.
3498        Edge(usize),
3499        /// The nearest point of face f's section line.
3500        Face(usize),
3501        /// The axis itself, where it passes through the tool.
3502        Axis,
3503    }
3504    let edge_at = |k: usize, z: f64| -> [f64; 2] {
3505        let (a, b) = (corners[edges[k].0], corners[edges[k].1]);
3506        let t = (z - a[2]) / (b[2] - a[2]);
3507        [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
3508    };
3509    let crossing = |z: f64| -> Vec<usize> {
3510        (0..edges.len()).filter(|&k| (corners[edges[k].0][2] - z) * (corners[edges[k].1][2] - z) < 0.0).collect()
3511    };
3512    let farthest = |z: f64| -> (Source, f64) {
3513        let mut best = (Source::Edge(0), f64::NEG_INFINITY);
3514        for k in crossing(z) {
3515            let p = edge_at(k, z);
3516            let r = p[0].hypot(p[1]);
3517            if r > best.1 {
3518                best = (Source::Edge(k), r);
3519            }
3520        }
3521        best
3522    };
3523    // The section polygon: edge crossings ordered by angle about their mean.
3524    let nearest = |z: f64| -> Result<(Source, f64), KernelRefusal> {
3525        let list = crossing(z);
3526        let points: Vec<[f64; 2]> = list.iter().map(|&k| edge_at(k, z)).collect();
3527        let m = points.len();
3528        if m < 3 {
3529            return Err(refuse("turn_shadow", "a section of the tool is not a polygon".into()));
3530        }
3531        let centre = points.iter().fold([0.0, 0.0], |s, p| [s[0] + p[0] / m as f64, s[1] + p[1] / m as f64]);
3532        let mut order: Vec<usize> = (0..m).collect();
3533        order.sort_by(|&a, &b| {
3534            let (pa, pb) = (points[a], points[b]);
3535            (pa[1] - centre[1]).atan2(pa[0] - centre[0]).total_cmp(&(pb[1] - centre[1]).atan2(pb[0] - centre[0]))
3536        });
3537        let mut inside = true;
3538        let mut best = (Source::Edge(0), f64::INFINITY);
3539        for k in 0..m {
3540            let (ia, ib) = (order[k], order[(k + 1) % m]);
3541            let (a, b) = (points[ia], points[ib]);
3542            let d = [b[0] - a[0], b[1] - a[1]];
3543            if d[0] * (0.0 - a[1]) - d[1] * (0.0 - a[0]) < 0.0 {
3544                inside = false;
3545            }
3546            let length2 = d[0] * d[0] + d[1] * d[1];
3547            let t = -(a[0] * d[0] + a[1] * d[1]) / length2;
3548            let (source, r) = if t > 0.0 && t < 1.0 {
3549                let (ea, eb) = (edges[list[ia]], edges[list[ib]]);
3550                let shared = edge_faces[&ea].iter().find(|f| edge_faces[&eb].contains(f)).copied();
3551                let Some(face) = shared else {
3552                    return Err(refuse("turn_shadow", "a section side does not lie on one face".into()));
3553                };
3554                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
3555                (Source::Face(face), q[0].hypot(q[1]))
3556            } else {
3557                let q = if t <= 0.0 { a } else { b };
3558                (Source::Edge(list[if t <= 0.0 { ia } else { ib }]), q[0].hypot(q[1]))
3559            };
3560            if r < best.1 {
3561                best = (source, r);
3562            }
3563        }
3564        if inside {
3565            if !through {
3566                return Err(refuse("turn_shadow", "the turn's axis passes through the tool".into()));
3567            }
3568            return Ok((Source::Axis, 0.0));
3569        }
3570        Ok(best)
3571    };
3572    // ρ of a source at z, from its own geometry (smooth across the piece).
3573    let value = |source: Source, z: f64| -> f64 {
3574        match source {
3575            Source::Edge(k) => {
3576                let p = edge_at(k, z);
3577                p[0].hypot(p[1])
3578            }
3579            Source::Face(f) => {
3580                let (n, d) = planes[f];
3581                (d - n[2] * z).abs() / n[0].hypot(n[1])
3582            }
3583            Source::Axis => 0.0,
3584        }
3585    };
3586    // Breaks: corner heights, and where the farthest or nearest source changes.
3587    let mut heights: Vec<f64> = zs.clone();
3588    heights.sort_by(|a, b| a.total_cmp(b));
3589    heights.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * scale);
3590    let mut pieces_far: Vec<(f64, f64, Source)> = Vec::new();
3591    let mut pieces_near: Vec<(f64, f64, Source)> = Vec::new();
3592    for window in heights.windows(2) {
3593        let (za, zb) = (window[0], window[1]);
3594        let samples = 400;
3595        let inner = |k: usize| za + (zb - za) * (k as f64 + 0.5) / samples as f64;
3596        for near in [false, true] {
3597            let source_at = |z: f64| -> Result<Source, KernelRefusal> { Ok(if near { nearest(z)?.0 } else { farthest(z).0 }) };
3598            let mut runs: Vec<(f64, Source)> = vec![(za, source_at(inner(0))?)];
3599            for k in 1..samples {
3600                let (z0, z1) = (inner(k - 1), inner(k));
3601                let (s0, s1) = (source_at(z0)?, source_at(z1)?);
3602                // Two sources tied over the stretch (edges equally far from
3603                // the axis) are one piece of the outline.
3604                let tied = [z0, 0.5 * (z0 + z1), z1].iter().all(|&z| (value(s0, z) - value(s1, z)).abs() <= 1e-12 * scale);
3605                if s0 == s1 || tied {
3606                    continue;
3607                }
3608                // Where the source changes, by bisection (a side handing over
3609                // to its corner touches it, so their values do not cross).
3610                let (mut lo, mut hi) = (z0, z1);
3611                for _ in 0..200 {
3612                    let midz = 0.5 * (lo + hi);
3613                    if source_at(midz)? == s0 { lo = midz } else { hi = midz }
3614                }
3615                runs.push((0.5 * (lo + hi), s1));
3616            }
3617            let list = if near { &mut pieces_near } else { &mut pieces_far };
3618            for k in 0..runs.len() {
3619                let z_end = if k + 1 < runs.len() { runs[k + 1].0 } else { zb };
3620                list.push((runs[k].0, z_end, runs[k].1));
3621            }
3622        }
3623    }
3624    // Exact pieces: a pair's ρ(z) is a conic arc, a side's a segment.
3625    let piece = |source: Source, za: f64, zb: f64| -> Vec<ShadowPiece> {
3626        let (ra, rb) = (value(source, za), value(source, zb));
3627        if matches!(source, Source::Face(..) | Source::Axis) {
3628            return vec![vec![(ra, za, 1.0), (rb, zb, 1.0)]];
3629        }
3630        // ρ² = α z² + β z + γ; split so each arc turns little.
3631        let rho = |z: f64| value(source, z);
3632        // Differences kept inside the piece (an edge through the axis has a
3633        // corner in ρ at its end there).
3634        let (z_min, z_max) = (za.min(zb), za.max(zb));
3635        let slope = |z: f64| {
3636            let h = 1e-6 * (zb - za).abs().max(1e-300);
3637            let (zp, zm) = ((z + h).min(z_max), (z - h).max(z_min));
3638            (rho(zp) - rho(zm)) / (zp - zm)
3639        };
3640        let parts = 4;
3641        let mut out = Vec::new();
3642        for k in 0..parts {
3643            let (z0, z1) = (za + (zb - za) * k as f64 / parts as f64, za + (zb - za) * (k + 1) as f64 / parts as f64);
3644            let (a, b) = ((rho(z0), z0), (rho(z1), z1));
3645            // Straight (an edge meeting the axis): a segment.
3646            let bend = [0.25, 0.5, 0.75].iter().map(|&t| (rho(z0 + (z1 - z0) * t) - (a.0 + (b.0 - a.0) * t)).abs()).fold(0.0f64, f64::max);
3647            if bend <= 1e-12 * scale {
3648                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3649                continue;
3650            }
3651            let (ta, tb) = ((slope(z0), 1.0), (slope(z1), 1.0));
3652            // Tangent lines' intersection.
3653            let det = ta.0 * (-tb.1) - ta.1 * (-tb.0);
3654            if det.abs() < 1e-12 {
3655                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3656                continue;
3657            }
3658            let rhs = (b.0 - a.0, b.1 - a.1);
3659            let s = (rhs.0 * (-tb.1) - rhs.1 * (-tb.0)) / det;
3660            let c = (a.0 + ta.0 * s, a.1 + ta.1 * s);
3661            // Shoulder: the conic's point on the line from the chord's middle to c.
3662            let m = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
3663            let on = |u: f64| {
3664                let p = (m.0 + (c.0 - m.0) * u, m.1 + (c.1 - m.1) * u);
3665                p.0 - rho(p.1)
3666            };
3667            let (mut lo, mut hi) = (0.0, 1.0);
3668            let sign_lo = on(lo);
3669            for _ in 0..200 {
3670                let mid = 0.5 * (lo + hi);
3671                if (on(mid) > 0.0) == (sign_lo > 0.0) { lo = mid } else { hi = mid }
3672            }
3673            let u = 0.5 * (lo + hi);
3674            let weight = u / (1.0 - u);
3675            out.push(vec![(a.0, a.1, 1.0), (c.0, c.1, weight), (b.0, b.1, 1.0)]);
3676        }
3677        out
3678    };
3679    // Outline: up the near side, across the top, down the far side, across the bottom.
3680    let mut outline: Vec<ShadowPiece> = Vec::new();
3681    for &(za, zb, source) in &pieces_near {
3682        outline.extend(piece(source, za, zb));
3683    }
3684    let (near_top, far_top) = (value(pieces_near.last().expect("near").2, z_high), value(pieces_far.last().expect("far").2, z_high));
3685    if far_top - near_top > 1e-12 * scale {
3686        outline.push(vec![(near_top, z_high, 1.0), (far_top, z_high, 1.0)]);
3687    }
3688    for &(za, zb, source) in pieces_far.iter().rev() {
3689        for mut arc in piece(source, za, zb).into_iter().rev() {
3690            arc.reverse();
3691            outline.push(arc);
3692        }
3693    }
3694    let (near_bottom, far_bottom) = (value(pieces_near[0].2, z_low), value(pieces_far[0].2, z_low));
3695    if far_bottom - near_bottom > 1e-12 * scale {
3696        outline.push(vec![(far_bottom, z_low, 1.0), (near_bottom, z_low, 1.0)]);
3697    }
3698    // Snap consecutive ends together.
3699    for k in 0..outline.len() {
3700        let next = (k + 1) % outline.len();
3701        let end = *outline[k].last().expect("piece");
3702        outline[next][0] = (end.0, end.1, 1.0);
3703    }
3704    Ok(outline)
3705}
3706
3707/// A ball TURNED about an axis that passes through it. Its grazing circle (in
3708/// the plane of the axis and the centre) crosses the axis at two poles N and S;
3709/// the part beyond the axis turns inside the sweep, and near the axis the ends
3710/// overlap. So the sweep has three faces: the wall, the outer arc of that
3711/// circle turned (a spindle torus's outer part, pinched at N and S); the
3712/// ball's back at the start less the ball at the end; and its front at the end
3713/// less the ball at the start. The two caps meet along the far arc, from S to
3714/// N, of the circle where the two spheres meet. None when the motion or tool
3715/// is not of that kind.
3716fn ball_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
3717    let [OutlinePiece::Arc { centre, radius, start, end }, OutlinePiece::Line { .. }] = meridian else { return Ok(None) };
3718    let (centre, r) = (*centre, *radius);
3719    if centre[0].abs() > 1e-12 * r || ((end - start).abs() - PI).abs() > 1e-12 || screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 {
3720        return Ok(None);
3721    }
3722    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
3723    let centre_tool = origin.add(w.scale(centre[1]));
3724    let turned = screw.omega * (screw.t1 - screw.t0);
3725    if turned.abs() >= TAU - 1e-9 {
3726        return Ok(None);
3727    }
3728    let e = screw.e.scale(screw.omega.signum()); // the sense the ball turns about
3729    let c0 = screw.apply(screw.t0, centre_tool);
3730    let c1 = screw.apply(screw.t1, centre_tool);
3731    let foot = |c: Vec3| screw.a.add(e.scale(c.sub(screw.a).dot(e)));
3732    let rho = c0.sub(foot(c0)).length();
3733    if rho >= r * (1.0 - 1e-9) || rho <= 1e-9 * r {
3734        return Ok(None);
3735    }
3736    let h0 = frag(c0.sub(foot(c0)).normalized(), "radial")?;
3737    let height = (r * r - rho * rho).sqrt();
3738    let (north, south) = (foot(c0).add(e.scale(height)), foot(c0).sub(e.scale(height)));
3739    // An arc from `from` turned about `axis` through `centre` by `angle`.
3740    let arc = |about: Vec3, k: Vec3, from: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
3741        let surface = frag(make_revolution(about, k, &frag(make_line(from, from.add(k)), "line")?, angle), "arc")?;
3742        frag(surface.iso_curve_v(0.0), "arc")
3743    };
3744    // The outer arc of the grazing circle, S -> N through c0 + r h0: in the
3745    // (h0, e) plane about c0, from angle -α to α through 0, α = atan2(height, -ρ).
3746    let alpha = height.atan2(-rho);
3747    let outer = arc(c0, h0.cross(e), south, 2.0 * alpha)?;
3748    let wall = frag(make_revolution(screw.a, e, &outer, turned.abs()), "wall")?;
3749    let outer_end = frag(wall.iso_curve_u(1.0), "wall_end")?;
3750    // The far arc where the spheres meet, S -> N beyond the axis.
3751    let mid = c0.add(c1).scale(0.5);
3752    let towards = frag(mid.sub(foot(mid)).normalized(), "bisector")?;
3753    let rho_mid = mid.sub(foot(mid)).length();
3754    let beta = height.atan2(rho_mid); // S and N seen from mid, off the far direction
3755    // From S at angle β − π (in the (towards, e) plane about mid) down through
3756    // π to N at π − β: the decreasing sense, about e × towards.
3757    let meet = arc(mid, e.cross(towards), south, 2.0 * beta)?;
3758    {
3759        // The arc must pass beyond the axis (its middle on the far side).
3760        let [d0, d1] = frag(meet.domain(), "domain")?;
3761        let middle = frag(meet.evaluate(0.5 * (d0 + d1)), "middle")?;
3762        if middle.sub(foot(middle)).dot(towards) > 0.0 {
3763            return Err(refuse("ball_across_axis", "the spheres' common circle runs the wrong way round".into()));
3764        }
3765    }
3766    // A trimmed sphere cap: a chart whose poles and seam lie where the cap is not.
3767    let cap = |c: Vec3, inward: Vec3, side: Vec3, other: Vec3| -> Result<(NurbsSurface, Box<dyn Fn(Vec3) -> Vec3>), KernelRefusal> {
3768        // South pole just off the far end of the grazing circle, on the removed
3769        // side (inside the other end's ball); the seam crosses the grazing
3770        // circle beyond the axis only.
3771        let toward_south = frag(inward.add(side.scale(-0.3)).normalized(), "pole")?;
3772        let polar = toward_south.scale(-1.0);
3773        let seam = frag(side.sub(polar.scale(side.dot(polar))).normalized(), "seam")?;
3774        for k in 0..=64 {
3775            // The seam's part on the cap's side of the grazing circle must lie
3776            // inside the other ball (where the cap is not).
3777            let a = PI * k as f64 / 64.0;
3778            let q = c.add(polar.scale(-r * a.cos())).add(seam.scale(r * a.sin()));
3779            if q.sub(c).dot(side) < 0.0 && q.sub(other).length() >= r * (1.0 - 1e-9) {
3780                return Err(refuse("ball_across_axis", "no seam place for a cap".into()));
3781            }
3782        }
3783        let south_pole = c.sub(polar.scale(r));
3784        if south_pole.sub(other).length() >= r * (1.0 - 1e-6) {
3785            return Err(refuse("ball_across_axis", "no pole place for a cap".into()));
3786        }
3787        let generatrix = arc(c, polar.scale(-1.0).cross(seam), south_pole, PI)?;
3788        let surface = frag(make_revolution(c, polar, &generatrix, TAU), "cap")?;
3789        let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
3790        let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
3791        let around = polar.cross(seam);
3792        let inverse = move |x: Vec3| -> Vec3 {
3793            let d = x.sub(c).scale(1.0 / r);
3794            let latitude = d.dot(polar).clamp(-1.0, 1.0).asin();
3795            let longitude = d.dot(around).atan2(d.dot(seam)).rem_euclid(TAU);
3796            Vec3::new(
3797                crate::circle_angle_to_parameter(spans_u, TAU, longitude),
3798                crate::circle_angle_to_parameter(spans_v, PI, latitude + 0.5 * PI),
3799                0.0,
3800            )
3801        };
3802        Ok((surface, Box::new(inverse)))
3803    };
3804    let moving0 = e.cross(h0);
3805    let h1 = frag(c1.sub(foot(c1)).normalized(), "radial")?;
3806    let moving1 = e.cross(h1);
3807    // The back cap at the start (its removed part near c0 − r h0 on the back);
3808    // the front cap at the end.
3809    let (back, back_inverse) = cap(c0, h0.scale(-1.0), moving0.scale(1.0), c1)?;
3810    let (front, front_inverse) = cap(c1, h1.scale(-1.0), moving1.scale(-1.0), c0)?;
3811    let (back_joints, front_joints) = (surface_joints(&back), surface_joints(&front));
3812    let pcurve = |inverse: &dyn Fn(Vec3) -> Vec3, curve: &NurbsCurve, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
3813        let [d0, d1] = frag(curve.domain(), "domain")?;
3814        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
3815        let uv: Vec<Vec3> = ts.iter().map(|&t| curve.evaluate(t).map(|x| inverse(x))).collect::<Result<_, _>>().map_err(|e| refuse("pcurve", e))?;
3816        if pcurve_joints_on() {
3817            // The two caps share their structure (one make_revolution each).
3818            let (ju, jv) = (&back_joints.0, &back_joints.1);
3819            debug_assert_eq!(back_joints, front_joints);
3820            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
3821                let p = inverse(frag(curve.evaluate(t), "point")?);
3822                Ok([p.x, p.y])
3823            };
3824            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, ju, jv, curve)? {
3825                return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
3826            }
3827        }
3828        let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "cap_pcurve")?;
3829        if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
3830    };
3831    let mut shell = Shell::new();
3832    let (vn, vs) = (shell.vertex(north), shell.vertex(south));
3833    let k0 = shell.edge(outer.clone(), vs, vn, false)?;
3834    let k1 = shell.edge(outer_end.clone(), vs, vn, false)?;
3835    let c = shell.edge(meet.clone(), vs, vn, false)?;
3836    let ds = shell.edge(frag(make_line(south, south), "point")?, vs, vs, true)?;
3837    let dn = shell.edge(frag(make_line(north, north), "point")?, vn, vn, true)?;
3838    // Wall: u turns, v runs S -> N; outward needs v the other way round the
3839    // circle's normal, so test and pick the loop's sense.
3840    let wall_outward = {
3841        let p = frag(wall.evaluate(0.5, 0.5), "probe")?;
3842        let su = frag(wall.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(wall.evaluate(0.5 - 1e-6, 0.5), "probe")?);
3843        let sv = frag(wall.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(wall.evaluate(0.5, 0.5 - 1e-6), "probe")?);
3844        su.cross(sv).dot(p.sub(foot(p))) > 0.0
3845    };
3846    let [g0, g1] = frag(outer.domain(), "domain")?;
3847    let wall_loop = vec![
3848        (ds, true, uv_line([0.0, g0], [1.0, g0])?),
3849        (k1, true, uv_line([1.0, g0], [1.0, g1])?),
3850        (dn, true, uv_line([1.0, g1], [0.0, g1])?),
3851        (k0, false, uv_line([0.0, g1], [0.0, g0])?),
3852    ];
3853    let reversed = |list: Vec<(u64, bool, NurbsCurve)>| -> Result<Vec<(u64, bool, NurbsCurve)>, KernelRefusal> {
3854        list.into_iter().rev().map(|(e, f, p)| Ok((e, !f, frag(p.reversed(), "reversed")?))).collect()
3855    };
3856    shell.face(wall.clone(), if wall_outward { wall_loop } else { reversed(wall_loop)? });
3857    // Caps: loop (grazing arc S -> N, then the meeting arc N -> S), sense by
3858    // the signed area of its parameters (the charts' u × v points outward).
3859    for (surface, inverse, k_edge, k_curve) in [(back, &back_inverse, k0, &outer), (front, &front_inverse, k1, &outer_end)] {
3860        let mut lp = vec![(k_edge, true, pcurve(inverse.as_ref(), k_curve, true)?), (c, false, pcurve(inverse.as_ref(), &meet, false)?)];
3861        let mut area = 0.0;
3862        for (_, _, pc) in &lp {
3863            let [d0, d1] = frag(pc.domain(), "domain")?;
3864            for j in 0..64 {
3865                let (a, b) = (frag(pc.evaluate(d0 + (d1 - d0) * j as f64 / 64.0), "uv")?, frag(pc.evaluate(d0 + (d1 - d0) * (j + 1) as f64 / 64.0), "uv")?);
3866                area += a.x * b.y - b.x * a.y;
3867            }
3868        }
3869        if area < 0.0 {
3870            lp = reversed(lp)?;
3871        }
3872        shell.face(surface, lp);
3873    }
3874    let body = shell.solid();
3875    let issues = body.validate();
3876    if !issues.is_empty() {
3877        return Err(refuse("assembly", format!("the turned ball's sweep is not valid: {:?}", issues.first())));
3878    }
3879    let probe = Split { points: Vec::new(), curves: Vec::new(), caps: Vec::new(), slides: Vec::new(), slide_sides: Vec::new(), scale: r + rho, shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() } };
3880    check_single_pass(screw, &probe, &body, &std::collections::HashSet::new())?;
3881    Ok(Some(body))
3882}
3883
3884/// A frame riding a cubic Bézier curve (`control`, in a plane square to
3885/// `up`): its origin on the curve, its first axis along the curve's tangent,
3886/// `up` fixed. The tool is given in the frame at the curve's start and carried
3887/// by it over the whole curve.
3888#[derive(Clone, Copy, Debug)]
3889pub struct FrameCurve {
3890    pub control: [Vec3; 4],
3891    pub up: Vec3,
3892}
3893
3894/// The whole sweep of a solid of revolution carried by a frame along a
3895/// curve. In the riding frame the velocity field is the speed along the
3896/// tangent plus the turn about `up`, so the grazing loop moves on the tool with
3897/// the curve's curvature. It is split at sample times (its structure must not
3898/// change), each piece sampled exactly, and the walls lofted through those
3899/// samples (quintic both ways; the samples' count doubles until the wall is
3900/// within `LOFT_TARGET` of the exact loop at the times between). Caps are the tool's
3901/// back at the start and front at the end.
3902pub fn sweep_solid_along(tool: &SolidTool, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
3903    // An upright solid of revolution on a planar curve is translated by it:
3904    // its sweep is built from the planar distance to the curve, folds and
3905    // crossings included (`BREP_SWEEP_UPRIGHT_SLOT`, default off).
3906    if crate::solid_sweep_upright::upright_slot_on() {
3907        if let Some(slot) = crate::solid_sweep_upright::upright_slot(tool, path) {
3908            return slot.solid();
3909        }
3910    }
3911    // A ring on a planar curve, from its slices (`BREP_SWEEP_PLANAR_RING`).
3912    if let Some(ring) = crate::solid_sweep_planar_ring::planar_ring_on().then(|| crate::solid_sweep_planar_ring::planar_ring_sweep(tool, path)).flatten() {
3913        return ring;
3914    }
3915    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
3916    let base = path.control[0];
3917    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
3918        return Err(input("plane", "the curve is not in a plane square to up".into()));
3919    }
3920    let tangent = path.control[1].sub(base);
3921    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
3922    let start_tangent = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
3923    let frame = Frame { control: path.control, up, start_tangent };
3924    let (mut speed, mut rate, mut extent) = (0.0f64, 0.0f64, 0.0f64);
3925    let mut previous = 0.0;
3926    for k in 0..=512 {
3927        let t = k as f64 / 512.0;
3928        let first = frame.first(t);
3929        if first.length() <= 1e-12 {
3930            return Err(input("tangent", "the curve stops (zero tangent)".into()));
3931        }
3932        speed = speed.max(first.length());
3933        rate = rate.max(frame.angle_rate(t).abs());
3934        extent = extent.max(frame.point(t).sub(base).length());
3935        let angle = frame.angle(t);
3936        if (angle - previous).abs() > 0.5 {
3937            return Err(refuse("frame_turns", "the frame turns half way round".into()));
3938        }
3939        previous = angle;
3940    }
3941    let screw = Screw { a: base, e: up, omega: rate, c: speed, c2: 0.0, t0: 0.0, t1: 1.0, frame: Some(frame), turns: None, frozen: None,
3942        loop_samples: LOFT_SAMPLES, extent };
3943    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
3944        return Err(refuse("along_tool", "a frame along a curve carries a solid of revolution only".into()));
3945    };
3946    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
3947    // The splits name their pieces by angle about the tool's axis from its
3948    // radial direction: a grazing angle passing that reference renames them,
3949    // so try a few references.
3950    let mut last = None;
3951    for k in 0..8 {
3952        let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
3953        match lofted(&screw, *axis_origin, axis, reference, meridian) {
3954            Err(error) if refused_as(&error) == Some("loft_structure") => last = Some(error),
3955            other => return other,
3956        }
3957    }
3958    Err(last.expect("tried"))
3959}
3960
3961/// The whole sweep of a prism carried by a frame along a planar curve (its
3962/// axis along the frame's up): the prism `outline` (a convex polygon in the
3963/// start frame: first coordinate along the start tangent, second along
3964/// up × tangent) between `from` and `to` along up. The motion is planar, so the
3965/// sweep is the plane region the moving outline covers, extruded. That region
3966/// is found exactly: its boundary lies on the outline's corner paths, the paths
3967/// of each edge's grazing point (where the edge's normal is square to the
3968/// velocity), and the outline's edges at the two ends; these are split where
3969/// they meet, and a piece is kept where one side of it is covered and the other
3970/// not (folds, where a corner digs past a side, come out right).
3971pub fn sweep_prism_along(outline: &[[f64; 2]], from: f64, to: f64, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
3972    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
3973    let base = path.control[0];
3974    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
3975        return Err(input("plane", "the curve is not in a plane square to up".into()));
3976    }
3977    let tangent = path.control[1].sub(base);
3978    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
3979    let e1 = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
3980    let e2 = up.cross(e1);
3981    let frame = Frame { control: path.control, up, start_tangent: e1 };
3982    // The frame in plane coordinates: origin c(s), turned by φ(s).
3983    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
3984    let pose = |s: f64| (flat(frame.point(s)), frame.angle(s));
3985    let rates = |s: f64| {
3986        let first = frame.first(s);
3987        ([first.dot(e1), first.dot(e2)], frame.angle_rate(s))
3988    };
3989    prism_region_sweep(outline, from, to, base, e1, e2, up, &pose, &rates, false)
3990}
3991
3992/// The whole sweep of a prism (the convex polygon `outline` in the plane
3993/// through `base` spanned by `e1`, `e2`, between `from` and `to` along `up`)
3994/// under a planar rigid motion: at s ∈ [0, 1] a point q of the plane (in the
3995/// tool's own coordinates) is at origin(s) + R(angle(s)) q, `pose` giving
3996/// (origin, angle) and `rates` their derivatives in s. The sweep is the plane
3997/// region the moving outline covers, extruded. That region is found exactly:
3998/// its boundary lies on the outline's corner paths, the paths of each edge's
3999/// grazing point (where the edge's normal is square to the velocity), and,
4000/// unless the motion is `closed` (it ends where it starts), the outline's
4001/// edges at the two ends; these are split where they meet or cross
4002/// themselves, and a piece is kept where one side of it is covered and the
4003/// other not. The region may have holes.
4004#[allow(clippy::too_many_arguments)]
4005pub fn prism_region_sweep(
4006    outline: &[[f64; 2]],
4007    from: f64,
4008    to: f64,
4009    base: Vec3,
4010    e1: Vec3,
4011    e2: Vec3,
4012    up: Vec3,
4013    pose: &dyn Fn(f64) -> ([f64; 2], f64),
4014    rates: &dyn Fn(f64) -> ([f64; 2], f64),
4015    closed: bool,
4016) -> Result<BrepSolid, KernelRefusal> {
4017    if outline.len() < 3 || !(to > from) {
4018        return Err(input("prism", "a prism needs three corners and a positive height".into()));
4019    }
4020    // Counter-clockwise, convex.
4021    let n = outline.len();
4022    let mut corners = outline.to_vec();
4023    let area: f64 = (0..n).map(|k| corners[k][0] * corners[(k + 1) % n][1] - corners[(k + 1) % n][0] * corners[k][1]).sum();
4024    if area < 0.0 {
4025        corners.reverse();
4026    }
4027    for k in 0..n {
4028        let (a, b, c) = (corners[k], corners[(k + 1) % n], corners[(k + 2) % n]);
4029        if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) <= 0.0 {
4030            return Err(input("prism", "the outline is not convex".into()));
4031        }
4032    }
4033    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
4034    let place = |s: f64, q: [f64; 2]| -> [f64; 2] {
4035        let (o, angle) = pose(s);
4036        let (sn, cs) = angle.sin_cos();
4037        [o[0] + cs * q[0] - sn * q[1], o[1] + sn * q[0] + cs * q[1]]
4038    };
4039    let local = |s: f64, p: [f64; 2]| -> [f64; 2] {
4040        let (o, angle) = pose(s);
4041        let (sn, cs) = angle.sin_cos();
4042        let d = [p[0] - o[0], p[1] - o[1]];
4043        [cs * d[0] + sn * d[1], -sn * d[0] + cs * d[1]]
4044    };
4045    // Edges: outward normals and offsets in the start frame.
4046    let edges: Vec<([f64; 2], f64)> = (0..n)
4047        .map(|k| {
4048            let (a, b) = (corners[k], corners[(k + 1) % n]);
4049            let d = [b[0] - a[0], b[1] - a[1]];
4050            let length = d[0].hypot(d[1]);
4051            let normal = [d[1] / length, -d[0] / length];
4052            (normal, normal[0] * a[0] + normal[1] * a[1])
4053        })
4054        .collect();
4055    let inside = |q: [f64; 2]| edges.iter().map(|(nn, d)| nn[0] * q[0] + nn[1] * q[1] - d).fold(f64::NEG_INFINITY, f64::max);
4056    // Is p covered at some time? The least signed distance over the motion.
4057    let depth = |p: [f64; 2]| -> f64 {
4058        let samples = 2000;
4059        let f = |s: f64| inside(local(s, p));
4060        let mut best = (f64::INFINITY, 0usize);
4061        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
4062        for (k, &v) in values.iter().enumerate() {
4063            if v < best.0 {
4064                best = (v, k);
4065            }
4066        }
4067        // Refine every local minimum near the least.
4068        let mut least = best.0;
4069        for k in 0..=samples {
4070            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
4071            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
4072            if values[k] <= left && values[k] <= right && values[k] < best.0 + 1e-3 * scale {
4073                let (mut lo, mut hi) = (((k as f64) - 1.0).max(0.0) / samples as f64, ((k as f64) + 1.0).min(samples as f64) / samples as f64);
4074                for _ in 0..80 {
4075                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4076                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
4077                }
4078                least = least.min(f(0.5 * (lo + hi)));
4079            }
4080        }
4081        least
4082    };
4083    // Candidate boundary paths, each a map [0, 1] -> plane.
4084    #[derive(Clone, Copy)]
4085    enum Path {
4086        Corner(usize),
4087        /// Edge k's grazing point over the times [s0, s1].
4088        Graze(usize, f64, f64),
4089        /// Edge k at the start (false) or end (true).
4090        End(usize, bool),
4091    }
4092    // Where along edge k's line (0 at its start corner, 1 at its end) the
4093    // grazing point is at s, on the edge or beyond it.
4094    let graze_at = |k: usize, s: f64| -> Option<f64> {
4095        // Along edge k at x (in the tool's coordinates) the velocity's part
4096        // along the edge's normal n is w·n + φ' (ẑ × x)·n, w the origin's
4097        // velocity read in the tool's frame.
4098        let (a, b) = (corners[k], corners[(k + 1) % n]);
4099        let (nn, _) = edges[k];
4100        let (velocity, rate) = rates(s);
4101        let (sn, cs) = pose(s).1.sin_cos();
4102        let w = [cs * velocity[0] + sn * velocity[1], -sn * velocity[0] + cs * velocity[1]];
4103        let along = w[0] * nn[0] + w[1] * nn[1];
4104        let rot = |x: [f64; 2]| -x[1] * nn[0] + x[0] * nn[1]; // (ẑ × x)·n
4105        // An edge the origin moves along grazes where (ẑ × x)·n = 0 whatever
4106        // the turning rate (also where it is zero, at an inflection).
4107        let (ga, gb) = if along.abs() < 1e-15 * w[0].hypot(w[1]) { (rot(a), rot(b)) } else { (along + rate * rot(a), along + rate * rot(b)) };
4108        if ga == gb {
4109            return None;
4110        }
4111        Some(ga / (ga - gb))
4112    };
4113    let graze_point = |k: usize, s: f64| -> Option<f64> { graze_at(k, s).filter(|&u| u > 0.0 && u < 1.0) };
4114    let mut paths: Vec<Path> = (0..n).map(Path::Corner).collect();
4115    // Where a grazing point enters or leaves its edge it is at a corner:
4116    // (that corner, the time), a place its path is split at.
4117    let mut junctions: Vec<(usize, f64)> = Vec::new();
4118    for k in 0..n {
4119        // Where along the motion edge k has a grazing point inside it, each
4120        // run's ends found where the point passes a corner.
4121        let steps = 2000;
4122        let mut run: Option<f64> = None;
4123        let mut passes = |inside: f64, outside: f64| -> f64 {
4124            let (mut a, mut b) = (inside, outside);
4125            for _ in 0..80 {
4126                let mid = 0.5 * (a + b);
4127                if graze_point(k, mid).is_some() { a = mid } else { b = mid }
4128            }
4129            let corner = if graze_at(k, a).is_some_and(|u| u < 0.5) { k } else { (k + 1) % n };
4130            junctions.push((corner, a));
4131            a
4132        };
4133        for j in 0..=steps {
4134            let s = j as f64 / steps as f64;
4135            let on = graze_point(k, s).is_some();
4136            match (on, run) {
4137                (true, None) => run = Some(if j == 0 { s } else { passes(s, s - 1.0 / steps as f64) }),
4138                (false, Some(s0)) => {
4139                    paths.push(Path::Graze(k, s0, passes(s - 1.0 / steps as f64, s)));
4140                    run = None;
4141                }
4142                _ => {}
4143            }
4144        }
4145        if let Some(s0) = run {
4146            paths.push(Path::Graze(k, s0, 1.0));
4147        }
4148        if !closed {
4149            paths.push(Path::End(k, false));
4150            paths.push(Path::End(k, true));
4151        }
4152    }
4153    let eval = |path: Path, t: f64| -> [f64; 2] {
4154        match path {
4155            Path::Corner(k) => place(t, corners[k]),
4156            Path::Graze(k, s0, s1) => {
4157                let s = s0 + (s1 - s0) * t;
4158                let u = graze_at(k, s).map_or(0.5, |u| u.clamp(0.0, 1.0));
4159                let (a, b) = (corners[k], corners[(k + 1) % n]);
4160                place(s, [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u])
4161            }
4162            Path::End(k, at_end) => {
4163                let (a, b) = (corners[k], corners[(k + 1) % n]);
4164                place(if at_end { 1.0 } else { 0.0 }, [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t])
4165            }
4166        }
4167    };
4168    let count = paths.len();
4169    region_from_paths(
4170        count,
4171        &|index: usize, t: f64| eval(paths[index], t),
4172        &|index: usize| matches!(paths[index], Path::End(..)),
4173        &|_: usize| closed,
4174        &junctions,
4175        &depth,
4176        scale,
4177        (base, e1, e2, up),
4178        (from, to),
4179    )
4180}
4181
4182/// Everything a tube (the ball of `radius` swept along the curve
4183/// `centreline(s)`, s ∈ [0, 1], its ends included) passes through as it slides
4184/// by `slide`, inside the slab `slab[0] ≤ (x − slab_origin)·n ≤ slab[1]` (`n` =
4185/// `slab_normal` normalised), which the tube must cross wholly: before the
4186/// slab at the start, past it at the end (checked at 8001 points of the
4187/// centreline, with a margin of the longest step between them). The
4188/// returned prism along the slide agrees with the sweep inside the slab; the
4189/// caller cuts a workpiece that lies within it.
4190///
4191/// The centreline must be resolved by its samples (as every path of the plane
4192/// region arrangement is): smooth, its height changing between two of the
4193/// 8001 checking samples by no more than the step between them, so that the
4194/// samples bound it. A curve that wanders between samples is outside this
4195/// contract.
4196///
4197/// Why a prism: a point x of the slab is in the sweep iff the line through x
4198/// along the slide meets the tube. If it does, `n·` grows along the line, so
4199/// its topmost point y of the starting tube lies before x, and y + slide (a
4200/// point of the final tube) past it: x − y is a multiple of the slide in
4201/// [0, 1). So the sweep in the slab is the slab's part of the prism over the
4202/// tube's shadow along the slide: in the plane square to it the union of the
4203/// discs of `radius` about the shadow γ of the centreline. That region is
4204/// bounded by γ's two offset curves (each disc's grazing points, γ ± radius
4205/// along its normal) and the end discs' circles, built exactly by the plane
4206/// region arrangement of [`sweep_prism_along`].
4207pub fn sweep_tube_slid_across(
4208    centreline: &dyn Fn(f64) -> Vec3,
4209    radius: f64,
4210    slide: Vec3,
4211    slab_origin: Vec3,
4212    slab_normal: Vec3,
4213    slab: [f64; 2],
4214) -> Result<BrepSolid, KernelRefusal> {
4215    if !(radius.is_finite() && radius > 0.0) {
4216        return Err(input("tube_radius", "the tube's radius must be positive".into()));
4217    }
4218    let up = slide.normalized().map_err(|_| input("slide", "the slide has no length".into()))?;
4219    let normal = slab_normal.normalized().map_err(|_| input("slab", "the slab's normal has no direction".into()))?;
4220    if !(slab[1] > slab[0]) || up.dot(normal).abs() < 1e-9 {
4221        return Err(input("slab", "the slab must have thickness and the slide must cross it".into()));
4222    }
4223    // Orient so the slide runs up the slab's normal.
4224    let (normal, slab) = if up.dot(normal) > 0.0 { (normal, slab) } else { (normal.scale(-1.0), [-slab[1], -slab[0]]) };
4225    let points: Vec<Vec3> = (0..=8000).map(|k| centreline(k as f64 / 8000.0)).collect();
4226    if points.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) {
4227        return Err(input("centreline", "the centreline has a point that is not finite".into()));
4228    }
4229    let step = points.windows(2).map(|w| w[1].sub(w[0]).length()).fold(0.0f64, f64::max);
4230    let heights: Vec<f64> = points.iter().map(|q| q.sub(slab_origin).dot(normal)).collect();
4231    let (low, high) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &h| (a.min(h), b.max(h)));
4232    let rise = slide.dot(normal);
4233    if !(high + radius + step < slab[0] && low - radius - step + rise > slab[1]) {
4234        return Err(refuse("tube_slab", "the tube does not pass wholly through the slab (it starts or ends within reach of it)".into()));
4235    }
4236    let e1 = {
4237        let seed = if up.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
4238        seed.sub(up.scale(seed.dot(up))).normalized().map_err(|_| input("slide", "no frame".into()))?
4239    };
4240    let e2 = up.cross(e1);
4241    // The plane's origin on the centreline itself, so that every tolerance
4242    // reads the tube's own size, wherever it lies.
4243    let base = points[0];
4244    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
4245    let centre = |s: f64| -> [f64; 2] { flat(centreline(s)) };
4246    let velocity = |s: f64| -> [f64; 2] {
4247        let h = 1e-7;
4248        let (a, b) = ((s - h).max(0.0), (s + h).min(1.0));
4249        let (p, q) = (centre(a), centre(b));
4250        [(q[0] - p[0]) / (b - a), (q[1] - p[1]) / (b - a)]
4251    };
4252    // The shadow must keep moving (a disc standing still has no grazing points).
4253    for k in 0..=2000 {
4254        let w = velocity(k as f64 / 2000.0);
4255        if w[0].hypot(w[1]) < 1e-9 * (1.0 + radius) {
4256            return Err(refuse("tube_shadow", "the tube's shadow along the slide stops (its centreline runs along the slide)".into()));
4257        }
4258    }
4259    // Tolerances read the tube's radius (a probe beside a boundary must stay
4260    // within the tube), never more than its extent; a tube longer than 1e6
4261    // radii is beyond what the coordinates resolve at that size.
4262    let extent = (0..=64).map(|k| { let c = centre(k as f64 / 64.0); c[0].hypot(c[1]) }).fold(radius, f64::max);
4263    if extent > 1e6 * radius {
4264        return Err(refuse("tube_shadow", "the tube is too long for its radius (over a million radii)".into()));
4265    }
4266    let scale = extent.min(1e3 * radius);
4267    // Paths: the two offset curves, then the two end circles.
4268    let eval = |index: usize, t: f64| -> [f64; 2] {
4269        match index {
4270            0 | 1 => {
4271                let c = centre(t);
4272                let w = velocity(t);
4273                let length = w[0].hypot(w[1]);
4274                let side = if index == 0 { 1.0 } else { -1.0 };
4275                [c[0] - side * radius * w[1] / length, c[1] + side * radius * w[0] / length]
4276            }
4277            _ => {
4278                let c = centre(if index == 2 { 0.0 } else { 1.0 });
4279                let angle = TAU * t;
4280                [c[0] + radius * angle.cos(), c[1] + radius * angle.sin()]
4281            }
4282        }
4283    };
4284    // Inside: nearer than `radius` to the shadow at some time.
4285    let depth = |p: [f64; 2]| -> f64 {
4286        let samples = 4000;
4287        let f = |s: f64| { let c = centre(s); (p[0] - c[0]).hypot(p[1] - c[1]) - radius };
4288        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
4289        let mut least = values.iter().cloned().fold(f64::INFINITY, f64::min);
4290        for k in 0..=samples {
4291            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
4292            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
4293            if values[k] <= left && values[k] <= right && values[k] < least + 1e-3 * scale {
4294                let (mut lo, mut hi) = (((k as f64) - 1.0).max(0.0) / samples as f64, ((k as f64) + 1.0).min(samples as f64) / samples as f64);
4295                for _ in 0..80 {
4296                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4297                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
4298                }
4299                least = least.min(f(0.5 * (lo + hi)));
4300            }
4301        }
4302        least
4303    };
4304    // The prism spans the slab's crossing of every line through the region:
4305    // from below the starting tube to past the final one, along the slide.
4306    let (a0, a1) = points.iter().map(|q| q.sub(base).dot(up)).fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), h| (a.min(h), b.max(h)));
4307    let margin = radius + step + 1e-3 * scale;
4308    // Each offset curve ends on its end circle, tangent to it there (both run
4309    // along the velocity), which no crossing test finds: split the circles at
4310    // those points (the angles of ±the normal there).
4311    let mut touches: Vec<(usize, f64)> = Vec::new();
4312    for (circle, s) in [(2usize, 0.0f64), (3, 1.0)] {
4313        let w = velocity(s);
4314        for side in [1.0f64, -1.0] {
4315            let angle = (side * w[0]).atan2(-side * w[1]);
4316            touches.push((circle, angle.rem_euclid(TAU) / TAU));
4317        }
4318    }
4319    region_from_paths(
4320        4,
4321        &eval,
4322        &|_| false,
4323        &|index| index >= 2,
4324        &touches,
4325        &depth,
4326        scale,
4327        (base, e1, e2, up),
4328        (a0 - margin, a1 + slide.length() + margin),
4329    )
4330}
4331
4332/// The crossing search's box culling in [`region_from_paths`]
4333/// (`BREP_SWEEP_REGION_CROSS_BOXES`, default on; `=0` visits every segment
4334/// pair, the same crossings found more slowly: square-on-a-planet-carrier
4335/// tests 74.4M pairs without it, 0.75M with it, for the same 74 Newton runs).
4336fn region_cross_boxes_on() -> bool {
4337    crate::switch!("BREP_SWEEP_REGION_CROSS_BOXES", true)
4338}
4339
4340/// The plane region bounded by pieces of the candidate `count` paths (each
4341/// `eval(index, t)`, t ∈ [0, 1]), extruded along `up` from `heights.0` to
4342/// `heights.1`: the paths are split where they cross each other or
4343/// themselves (and at `extra_cuts`), a piece is kept where `depth` (negative
4344/// inside the region) reads one side covered and the other not, and the kept
4345/// pieces chain into one outer loop and its holes. `straight_path(index)`: the
4346/// path is a segment (built as a line); `closed_path(index)`: its two ends
4347/// meet (neighbours for the self-crossing test).
4348#[allow(clippy::too_many_arguments)]
4349fn region_from_paths(
4350    count: usize,
4351    eval: &dyn Fn(usize, f64) -> [f64; 2],
4352    straight_path: &dyn Fn(usize) -> bool,
4353    closed_path: &dyn Fn(usize) -> bool,
4354    extra_cuts: &[(usize, f64)],
4355    depth: &dyn Fn([f64; 2]) -> f64,
4356    scale: f64,
4357    frame: (Vec3, Vec3, Vec3, Vec3),
4358    heights: (f64, f64),
4359) -> Result<BrepSolid, KernelRefusal> {
4360    let (base, e1, e2, up) = frame;
4361    let (from, to) = heights;
4362    // Split parameters: mutual crossings (polyline, then Newton), and each
4363    // path's ends lying on another.
4364    let m = 400;
4365    let polylines: Vec<Vec<[f64; 2]>> = (0..count).map(|p| (0..=m).map(|i| eval(p, i as f64 / m as f64)).collect()).collect();
4366    let mut cuts: Vec<Vec<f64>> = vec![vec![0.0, 1.0]; count];
4367    let tol = 1e-10 * scale;
4368    // Under `BREP_SWEEP_REGION_CROSS_BOXES` the segment pairs are visited
4369    // chunk by chunk (16 segments each), a chunk pair only where their boxes,
4370    // grown by 1e-6 of the scale and by the pair test's own reach past a
4371    // segment's ends, overlap: a crossing the test takes lies in both boxes,
4372    // and none is missed. The cuts are
4373    // sorted after, so the order they are found in does not matter.
4374    const CHUNK: usize = 16;
4375    let boxed = region_cross_boxes_on();
4376    let chunks = (m + CHUNK - 1) / CHUNK;
4377    let grow = 1e-6 * scale;
4378    let boxes: Vec<Vec<[f64; 4]>> = polylines
4379        .iter()
4380        .filter(|_| boxed)
4381        .map(|line| {
4382            (0..chunks)
4383                .map(|c| {
4384                    let (lo, hi) = (c * CHUNK, ((c + 1) * CHUNK).min(m));
4385                    let b = line[lo..=hi].iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);
4386                    // The pair test takes a crossing up to 1e-9 of a segment's
4387                    // length past its end: grow by twice that of the chunk's
4388                    // longest segment, so every crossing it takes lies in both
4389                    // segments' boxes.
4390                    let longest = line[lo..=hi].windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).fold(0.0f64, f64::max);
4391                    let g = grow + 2e-9 * longest;
4392                    [b[0] - g, b[1] - g, b[2] + g, b[3] + g]
4393                })
4394                .collect()
4395        })
4396        .collect();
4397    let overlap = |a: &[f64; 4], b: &[f64; 4]| a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3];
4398    for a in 0..count {
4399        for b in a..count {
4400            // One segment pair: a crossing of the polylines, polished by Newton on the exact paths.
4401            let mut test = |i: usize, j: usize| {
4402                    // A path against itself: only where it crosses over
4403                    // (stretches apart along it; a closed path's ends are
4404                    // neighbours too).
4405                    if a == b && (j < i + 3 || (closed_path(a) && i < 3 && j + 3 > m)) {
4406                        return;
4407                    }
4408                    let (p0, p1, q0, q1) = (polylines[a][i], polylines[a][i + 1], polylines[b][j], polylines[b][j + 1]);
4409                    let d1 = [p1[0] - p0[0], p1[1] - p0[1]];
4410                    let d2 = [q1[0] - q0[0], q1[1] - q0[1]];
4411                    let det = d1[0] * d2[1] - d1[1] * d2[0];
4412                    if det.abs() < 1e-300 {
4413                        return;
4414                    }
4415                    let r = [q0[0] - p0[0], q0[1] - p0[1]];
4416                    let (x, y) = ((r[0] * d2[1] - r[1] * d2[0]) / det, (r[0] * d1[1] - r[1] * d1[0]) / det);
4417                    if !(-1e-9..=1.0 + 1e-9).contains(&x) || !(-1e-9..=1.0 + 1e-9).contains(&y) {
4418                        return;
4419                    }
4420                    // Newton on the exact paths.
4421                    let (mut ta, mut tb) = ((i as f64 + x) / m as f64, (j as f64 + y) / m as f64);
4422                    for _ in 0..50 {
4423                        let (pa, pb) = (eval(a, ta), eval(b, tb));
4424                        let h = 1e-7;
4425                        let da = { let q = eval(a, (ta + h).min(1.0)); let p = eval(a, (ta - h).max(0.0)); let w = (ta + h).min(1.0) - (ta - h).max(0.0); [(q[0] - p[0]) / w, (q[1] - p[1]) / w] };
4426                        let db = { let q = eval(b, (tb + h).min(1.0)); let p = eval(b, (tb - h).max(0.0)); let w = (tb + h).min(1.0) - (tb - h).max(0.0); [(q[0] - p[0]) / w, (q[1] - p[1]) / w] };
4427                        let f = [pa[0] - pb[0], pa[1] - pb[1]];
4428                        let det = -da[0] * db[1] + da[1] * db[0];
4429                        if det.abs() < 1e-300 {
4430                            break;
4431                        }
4432                        let dta = (-f[0] * db[1] + f[1] * db[0]) / det;
4433                        let dtb = (da[0] * f[1] - da[1] * f[0]) / det;
4434                        ta = (ta - dta).clamp(0.0, 1.0);
4435                        tb = (tb - dtb).clamp(0.0, 1.0);
4436                        if dta.abs() + dtb.abs() < 1e-15 {
4437                            break;
4438                        }
4439                    }
4440                    let (pa, pb) = (eval(a, ta), eval(b, tb));
4441                    if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < tol && !(a == b && (ta - tb).abs() < 1.0 / m as f64) {
4442                        cuts[a].push(ta);
4443                        cuts[b].push(tb);
4444                    }
4445            };
4446            if boxed {
4447                // Only the segment pairs of chunks whose boxes overlap.
4448                for ca in 0..chunks {
4449                    for cb in 0..chunks {
4450                        if !overlap(&boxes[a][ca], &boxes[b][cb]) {
4451                            continue;
4452                        }
4453                        for i in ca * CHUNK..((ca + 1) * CHUNK).min(m) {
4454                            for j in cb * CHUNK..((cb + 1) * CHUNK).min(m) {
4455                                test(i, j);
4456                            }
4457                        }
4458                    }
4459                }
4460            } else {
4461                for i in 0..m {
4462                    for j in 0..m {
4463                        test(i, j);
4464                    }
4465                }
4466            }
4467        }
4468    }
4469    // Extra splits the caller names (a corner's path where a grazing point passes it).
4470    for &(path, t) in extra_cuts {
4471        cuts[path].push(t);
4472    }
4473    for c in &mut cuts {
4474        c.sort_by(|x, y| x.total_cmp(y));
4475        c.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
4476    }
4477    // Pieces on the boundary: covered on exactly one side.
4478    struct Piece {
4479        path: usize,
4480        t0: f64,
4481        t1: f64,
4482    }
4483    let eps = 1e-7 * scale;
4484    let mut pieces: Vec<Piece> = Vec::new();
4485    for (index, c) in cuts.iter().enumerate() {
4486        for w in c.windows(2) {
4487            let (t0, t1) = (w[0], w[1]);
4488            if t1 - t0 < 1e-9 {
4489                continue;
4490            }
4491            let (pa, pb) = (eval(index, t0), eval(index, t1));
4492            if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < 1e-9 * scale {
4493                continue;
4494            }
4495            let tm = 0.5 * (t0 + t1);
4496            let (p, q) = (eval(index, tm), eval(index, (tm + 1e-6).min(1.0)));
4497            let d = [q[0] - p[0], q[1] - p[1]];
4498            let length = d[0].hypot(d[1]);
4499            if length == 0.0 {
4500                continue;
4501            }
4502            let left = [p[0] - d[1] / length * eps, p[1] + d[0] / length * eps];
4503            let right = [p[0] + d[1] / length * eps, p[1] - d[0] / length * eps];
4504            let (l, r) = (depth(left) < -1e-12 * scale, depth(right) < -1e-12 * scale);
4505            match (l, r) {
4506                (true, false) => pieces.push(Piece { path: index, t0, t1 }),
4507                (false, true) => pieces.push(Piece { path: index, t0: t1, t1: t0 }),
4508                _ => {}
4509            }
4510        }
4511    }
4512    // Chain into loops, the region on their left (the outer one runs
4513    // counter-clockwise, a hole's clockwise).
4514    if pieces.is_empty() {
4515        return Err(refuse("prism_along", "no boundary found".into()));
4516    }
4517    let mut used = vec![false; pieces.len()];
4518    let mut loops: Vec<Vec<usize>> = Vec::new();
4519    while let Some(first) = (0..pieces.len()).find(|&k| !used[k]) {
4520        let mut order = vec![first];
4521        used[first] = true;
4522        loop {
4523            let last = &pieces[*order.last().expect("order")];
4524            let end = eval(last.path, last.t1);
4525            let start = eval(pieces[order[0]].path, pieces[order[0]].t0);
4526            if (end[0] - start[0]).hypot(end[1] - start[1]) < 1e-8 * scale {
4527                break;
4528            }
4529            let next = (0..pieces.len()).filter(|&k| !used[k]).min_by(|&x, &y| {
4530                let (px, py) = (eval(pieces[x].path, pieces[x].t0), eval(pieces[y].path, pieces[y].t0));
4531                (px[0] - end[0]).hypot(px[1] - end[1]).total_cmp(&(py[0] - end[0]).hypot(py[1] - end[1]))
4532            });
4533            let Some(next) = next else {
4534                return Err(refuse("prism_along", "the boundary does not close".into()));
4535            };
4536            let p = eval(pieces[next].path, pieces[next].t0);
4537            if (p[0] - end[0]).hypot(p[1] - end[1]) > 1e-8 * scale {
4538                return Err(refuse("prism_along", format!("the boundary does not close (gap {:e})", (p[0] - end[0]).hypot(p[1] - end[1]))));
4539            }
4540            used[next] = true;
4541            order.push(next);
4542        }
4543        loops.push(order);
4544    }
4545    // The outer loop first: the one of greatest area.
4546    let area_of = |order: &Vec<usize>| -> f64 {
4547        let mut points: Vec<[f64; 2]> = Vec::new();
4548        for &k in order {
4549            let piece = &pieces[k];
4550            for i in 0..32 {
4551                points.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 32.0));
4552            }
4553        }
4554        (0..points.len()).map(|i| { let (a, b) = (points[i], points[(i + 1) % points.len()]); a[0] * b[1] - b[0] * a[1] }).sum::<f64>() * 0.5
4555    };
4556    let areas: Vec<f64> = loops.iter().map(area_of).collect();
4557    let outer = (0..loops.len()).max_by(|&x, &y| areas[x].abs().total_cmp(&areas[y].abs())).expect("loops");
4558    if areas[outer] <= 0.0 || (0..loops.len()).any(|k| k != outer && areas[k] >= 0.0) {
4559        return Err(refuse("prism_along", "the swept region is not one region with holes".into()));
4560    }
4561    loops.swap(0, outer);
4562    // Plane curves of the loops, then the extrusion.
4563    let world = |q: [f64; 2], h: f64| base.add(e1.scale(q[0])).add(e2.scale(q[1])).add(up.scale(h));
4564    let mut shell = Shell::new();
4565    let mut top_loops = Vec::with_capacity(loops.len());
4566    let mut bottom_loops = Vec::with_capacity(loops.len());
4567    let mut extent: Vec<[f64; 2]> = Vec::new();
4568    for order in &loops {
4569        let mut loop_points: Vec<[f64; 2]> = order.iter().map(|&k| eval(pieces[k].path, pieces[k].t0)).collect();
4570        loop_points.push(loop_points[0]);
4571        let count = order.len();
4572        let (bottom_v, top_v): (Vec<u64>, Vec<u64>) = (0..count).map(|k| (shell.vertex(world(loop_points[k], from)), shell.vertex(world(loop_points[k], to)))).unzip();
4573        let mut bottom_e = Vec::with_capacity(count);
4574        let mut top_e = Vec::with_capacity(count);
4575        let mut curves2d = Vec::with_capacity(count);
4576        for (slot, &k) in order.iter().enumerate() {
4577            let piece = &pieces[k];
4578            let straight = straight_path(piece.path);
4579            let next = (slot + 1) % count;
4580            for i in 0..=16 {
4581                extent.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 16.0));
4582            }
4583            let curve_at = |h: f64| -> Result<NurbsCurve, KernelRefusal> {
4584                if straight {
4585                    return frag(make_line(world(loop_points[slot], h), world(loop_points[next], h)), "line");
4586                }
4587                let samples = 192;
4588                let ts: Vec<f64> = (0..=samples).map(|i| i as f64 / samples as f64).collect();
4589                let mut points: Vec<Vec3> = ts.iter().map(|&t| world(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * t), h)).collect();
4590                points[0] = world(loop_points[slot], h);
4591                points[samples] = world(loop_points[next], h);
4592                frag(crate::interpolate_curve(&points, 5, &ts), "plane_path")
4593            };
4594            let (cb, ct) = (curve_at(from)?, curve_at(to)?);
4595            bottom_e.push(shell.edge(cb.clone(), bottom_v[slot], bottom_v[next], false)?);
4596            top_e.push(shell.edge(ct.clone(), top_v[slot], top_v[next], false)?);
4597            curves2d.push((cb, ct));
4598        }
4599        let verticals: Vec<u64> = (0..count).map(|k| shell.edge(make_line(world(loop_points[k], from), world(loop_points[k], to)).expect("line"), bottom_v[k], top_v[k], false)).collect::<Result<_, _>>()?;
4600        // Top (outward up) and bottom (outward down) loops.
4601        let mut coedges = Vec::with_capacity(count);
4602        for k in 0..count {
4603            coedges.push((top_e[k], true, plane_pcurve(world([0.0, 0.0], to), e1, e2, &curves2d[k].1, true)?));
4604        }
4605        top_loops.push(coedges);
4606        let mut coedges = Vec::with_capacity(count);
4607        for k in (0..count).rev() {
4608            coedges.push((bottom_e[k], false, plane_pcurve(world([0.0, 0.0], from), e2, e1, &curves2d[k].0, false)?));
4609        }
4610        bottom_loops.push(coedges);
4611        // Sides: the bottom curve extruded (u along it, v up), outward on its right.
4612        for k in 0..count {
4613            let next = (k + 1) % count;
4614            let (cb, _) = &curves2d[k];
4615            let rows: Vec<Vec<Vec4>> = cb
4616                .control_points
4617                .iter()
4618                .map(|p| {
4619                    let x = p.point().expect("point");
4620                    vec![Vec4::from_point(x, p.w), Vec4::from_point(x.add(up.scale(to - from)), p.w)]
4621                })
4622                .collect();
4623            let surface = frag(NurbsSurface::new(cb.degree, 1, cb.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows), "side")?;
4624            let [u0, u1] = frag(cb.domain(), "domain")?;
4625            let coedges = vec![
4626                (bottom_e[k], true, uv_line([u0, 0.0], [u1, 0.0])?),
4627                (verticals[next], true, uv_line([u1, 0.0], [u1, 1.0])?),
4628                (top_e[k], false, uv_line([u1, 1.0], [u0, 1.0])?),
4629                (verticals[k], false, uv_line([u0, 1.0], [u0, 0.0])?),
4630            ];
4631            shell.face(surface, coedges);
4632        }
4633    }
4634    let top_points: Vec<Vec3> = extent.iter().map(|&q| world(q, to)).collect();
4635    shell.face_loops(plane_patch(world([0.0, 0.0], to), e1, e2, &top_points)?, top_loops);
4636    let bottom_points: Vec<Vec3> = extent.iter().map(|&q| world(q, from)).collect();
4637    shell.face_loops(plane_patch(world([0.0, 0.0], from), e2, e1, &bottom_points)?, bottom_loops);
4638    let body = shell.solid();
4639    let issues = body.validate();
4640    if !issues.is_empty() {
4641        return Err(refuse("assembly", format!("the swept prism is not valid: {:?}", issues.first())));
4642    }
4643    Ok(body)
4644}
4645
4646/// A prism whose section is a convex polygon, carried by turns about axes
4647/// all along its own (a planar motion: a planet on its carrier) that ends
4648/// where it starts: its whole sweep (`prism_region_sweep`), or None when the
4649/// tool or motion is not of that kind. `steps`: each turn's axis point,
4650/// direction and rate, applied in order at every t ∈ [t0, t1].
4651#[allow(clippy::too_many_arguments)]
4652pub fn closed_planar_prism(
4653    origin: Vec3,
4654    normal: Vec3,
4655    x_axis: Vec3,
4656    outline: &[OutlinePiece],
4657    from: f64,
4658    to: f64,
4659    steps: &[(Vec3, Vec3, f64, f64)],
4660    t0: f64,
4661    t1: f64,
4662) -> Result<Option<BrepSolid>, KernelRefusal> {
4663    let Ok(up) = normal.normalized() else { return Ok(None) };
4664    let Ok(e1) = x_axis.sub(up.scale(x_axis.dot(up))).normalized() else { return Ok(None) };
4665    let e2 = up.cross(e1);
4666    // A polygon of straight sides, in order.
4667    let mut corners: Vec<[f64; 2]> = Vec::with_capacity(outline.len());
4668    for (k, piece) in outline.iter().enumerate() {
4669        let OutlinePiece::Line { from: a, to: b } = piece else { return Ok(None) };
4670        let OutlinePiece::Line { from: next, .. } = &outline[(k + 1) % outline.len()] else { return Ok(None) };
4671        if (b[0] - next[0]).hypot(b[1] - next[1]) > 1e-9 * (1.0 + b[0].hypot(b[1])) {
4672            return Ok(None);
4673        }
4674        corners.push(*a);
4675    }
4676    if corners.len() < 3 || steps.is_empty() || !(t1 > t0) {
4677        return Ok(None);
4678    }
4679    // Convex (either way round), or it is another engine's.
4680    let turn_of = |k: usize| {
4681        let (a, b, c) = (corners[k], corners[(k + 1) % corners.len()], corners[(k + 2) % corners.len()]);
4682        (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
4683    };
4684    let first_turn = turn_of(0);
4685    if first_turn == 0.0 || (1..corners.len()).any(|k| turn_of(k) * first_turn <= 0.0) {
4686        return Ok(None);
4687    }
4688    // Turns only, about axes along the prism's own: (centre in the plane, rate about +up).
4689    let mut turns: Vec<([f64; 2], f64)> = Vec::with_capacity(steps.len());
4690    for &(point, direction, turn, advance) in steps {
4691        let Ok(axis) = direction.normalized() else { return Ok(None) };
4692        if advance != 0.0 || axis.cross(up).length() > 1e-12 {
4693            return Ok(None);
4694        }
4695        let r = point.sub(origin);
4696        turns.push(([r.dot(e1), r.dot(e2)], turn * axis.dot(up).signum()));
4697    }
4698    let moved = |t: f64, q: [f64; 2]| -> [f64; 2] {
4699        let mut x = q;
4700        for &(c, rate) in &turns {
4701            let (sn, cs) = (rate * t).sin_cos();
4702            let d = [x[0] - c[0], x[1] - c[1]];
4703            x = [c[0] + cs * d[0] - sn * d[1], c[1] + sn * d[0] + cs * d[1]];
4704        }
4705        x
4706    };
4707    let total: f64 = turns.iter().map(|t| t.1).sum();
4708    // The turns compose to one rigid motion of the plane: a point q (where
4709    // it stands before any motion) is at moved(t, 0) + R(total t) q.
4710    let pose = |s: f64| -> ([f64; 2], f64) {
4711        let t = t0 + (t1 - t0) * s;
4712        (moved(t, [0.0, 0.0]), total * t)
4713    };
4714    // The turns are defined at every t, so the origin's velocity is a
4715    // centred difference at the motion's ends too.
4716    let rates = |s: f64| -> ([f64; 2], f64) {
4717        let h = 1e-6;
4718        let (pa, pb) = (pose(s - h).0, pose(s + h).0);
4719        ([(pb[0] - pa[0]) / (2.0 * h), (pb[1] - pa[1]) / (2.0 * h)], total * (t1 - t0))
4720    };
4721    // Ends where it starts: the same turn (mod 2π) and place.
4722    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
4723    let closes = corners.iter().all(|&c| {
4724        let (a, b) = (moved(t0, c), moved(t1, c));
4725        (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-9 * scale
4726    });
4727    if !closes {
4728        return Ok(None);
4729    }
4730    prism_region_sweep(&corners, from, to, origin, e1, e2, up, &pose, &rates, true).map(Some)
4731}
4732
4733/// Two turns driven by one parameter t: first by `rates[0]·t` about the
4734/// first axis (point, direction), then by `rates[1]·t` about the second; both
4735/// axes fixed in the world; t from `from` to `to`.
4736#[derive(Clone, Copy, Debug)]
4737pub struct TwoTurns {
4738    pub axes: [(Vec3, Vec3); 2],
4739    pub rates: [f64; 2],
4740    pub from: f64,
4741    pub to: f64,
4742}
4743
4744/// The whole sweep of a solid of revolution tumbled by two turns about skew
4745/// axes. The grazing loop moves on the tool (the instantaneous screw changes
4746/// with t), so the walls are lofted through exact samples. Where the tumble
4747/// passes over a point twice (the one-pass probe), the time is bisected into
4748/// spans each passing once, and the spans' sweeps are joined (consecutive
4749/// spans meet along a grazing loop; distant ones overlap).
4750pub fn sweep_solid_tumbled(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
4751    // A ring whose swept tube K bounds the solid outright, by the tube route
4752    // (BREP_SWEEP_TORUS_TUBE, default off); it declines anything else.
4753    if crate::solid_sweep_tube::torus_tube_on() {
4754        if let Some(tube) = ring_tube(tool, motion) {
4755            if let Ok(solid) = crate::solid_sweep_tube::sweep_torus_tube(&tube) {
4756                return Ok(solid);
4757            }
4758        }
4759    }
4760    let lofted = sweep_solid_tumbled_lofted(tool, motion);
4761    // A ring (a whole circle off its axis) the lofted walls refuse, by the
4762    // trim engine (BREP_SWEEP_RING_TRIM); the lofted refusal stands where it
4763    // refuses too. Rows the walls build are left to them.
4764    let Err(refusal) = lofted else {
4765        return lofted.map(|mut solid| {
4766            if cusp_first_on() {
4767                start_loops_at_cusps(&mut solid);
4768            }
4769            solid
4770        });
4771    };
4772    // A wall whose double curve reaches a corner: the trim route meets that
4773    // double curve's tip, which it does not yet write so a reader integrates
4774    // round it, and refuses after the work; declined before it.
4775    if !crate::solid_sweep_trim::ring_trim_on() || refusal.to_string().contains(DOUBLE_CURVE_CORNER) {
4776        return Err(refusal);
4777    }
4778    let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool else { return Err(refusal) };
4779    let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() else { return Err(refusal) };
4780    if !(((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius) {
4781        return Err(refusal);
4782    }
4783    let (Ok(axis), Ok(d0), Ok(d1)) = (axis_direction.normalized(), motion.axes[0].1.normalized(), motion.axes[1].1.normalized()) else { return Err(refusal) };
4784    let two = crate::solid_sweep_trim::TwoTurnMotion { points: [motion.axes[0].0, motion.axes[1].0], directions: [d0, d1], rates: motion.rates };
4785    let ring_centre = axis_origin.add(axis.scale(centre[1]));
4786    crate::solid_sweep_trim::sweep_ring_tumbled(ring_centre, axis, centre[0], *radius, &two, motion.from, motion.to).or(Err(refusal))
4787}
4788
4789/// `BREP_SWEEP_CUSP_FIRST` (on unless =0): each loop of a tumbled sweep starts
4790/// at its cusp corner, where it has one.
4791fn cusp_first_on() -> bool {
4792    crate::switch!("BREP_SWEEP_CUSP_FIRST", true)
4793}
4794
4795/// Each loop rotated to start at its cusp corner (a zero-angle corner: the
4796/// edge leaving it runs back along the edge arriving, within 0.05 rad), where
4797/// it has one; the sharpest such corner where it has several. Topology and
4798/// geometry are unchanged. A reader that places a loop on its surface by
4799/// inverting the edges' points, each edge seeded from the last one's end,
4800/// mislays a corner where an edge creeps into a cusp (its point all but still
4801/// while its parameters still move): from the cusp it starts clean.
4802pub(crate) fn start_loops_at_cusps(solid: &mut BrepSolid) {
4803    let ends: HashMap<u64, [(Vec3, Vec3); 2]> = solid
4804        .edges
4805        .iter()
4806        .filter_map(|e| {
4807            let span = e.t1 - e.t0;
4808            let at = |t: f64| e.curve.evaluate(t).ok();
4809            let (p0, p1) = (at(e.t0)?, at(e.t1)?);
4810            let (q0, q1) = (at(e.t0 + 1e-2 * span)?, at(e.t1 - 1e-2 * span)?);
4811            // (point, direction into the edge) at its start and at its end
4812            Some((e.id, [(p0, q0.sub(p0)), (p1, q1.sub(p1))]))
4813        })
4814        .collect();
4815    for face in solid.shells.iter_mut().flat_map(|s| s.faces.iter_mut()) {
4816        for l in face.loops.iter_mut() {
4817            let n = l.coedges.len();
4818            if n < 2 {
4819                continue;
4820            }
4821            let mut best: Option<(f64, usize)> = None;
4822            for k in 0..n {
4823                let (before, after) = (&l.coedges[(k + n - 1) % n], &l.coedges[k]);
4824                let (Some(b), Some(a)) = (ends.get(&before.edge_id), ends.get(&after.edge_id)) else { continue };
4825                // into the corner back along the edge arriving, and out along the edge leaving
4826                let back = if before.forward { b[1].1 } else { b[0].1 };
4827                let out = if after.forward { a[0].1 } else { a[1].1 };
4828                let (lb, lo) = (back.length(), out.length());
4829                if !(lb > 0.0 && lo > 0.0) {
4830                    continue;
4831                }
4832                let along = back.dot(out) / (lb * lo);
4833                if along > (0.05f64).cos() && best.map_or(true, |(x, _)| along > x) {
4834                    best = Some((along, k));
4835                }
4836            }
4837            if let Some((_, k)) = best {
4838                l.coedges.rotate_left(k);
4839            }
4840        }
4841    }
4842}
4843
4844/// The tube route's reading of a ring tool (a whole circle off its axis) under two turns.
4845fn ring_tube(tool: &SolidTool, motion: &TwoTurns) -> Option<crate::solid_sweep_tube::Tube> {
4846    let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool else { return None };
4847    let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() else { return None };
4848    if !(((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius && motion.from.is_finite() && motion.to > motion.from) {
4849        return None;
4850    }
4851    let (axis, d0, d1) = (axis_direction.normalized().ok()?, motion.axes[0].1.normalized().ok()?, motion.axes[1].1.normalized().ok()?);
4852    let two = crate::solid_sweep_trim::TwoTurnMotion { points: [motion.axes[0].0, motion.axes[1].0], directions: [d0, d1], rates: motion.rates };
4853    crate::solid_sweep_tube::Tube::new(axis_origin.add(axis.scale(centre[1])), axis, centre[0], *radius, two, motion.from, motion.to)
4854}
4855
4856/// The lofted walls' refusal where a wall's double curve reaches a corner of
4857/// its grazing loop (the tumbled sweep reads it to skip the ring's trim route).
4858#[doc(hidden)]
4859pub const DOUBLE_CURVE_CORNER: &str = "the double curve of a wall reaches a corner of its grazing loop";
4860
4861/// The tumbled sweep by the lofted walls (a polyhedron by the trim engine).
4862fn sweep_solid_tumbled_lofted(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
4863    if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
4864        return Err(input("range", "the motion's range must run forward".into()));
4865    }
4866    let mut points = [Vec3::new(0.0, 0.0, 0.0); 2];
4867    let mut directions = [Vec3::new(0.0, 0.0, 1.0); 2];
4868    for k in 0..2 {
4869        points[k] = motion.axes[k].0;
4870        directions[k] = motion.axes[k].1.normalized().map_err(|_| input("axis", "a turn's axis has no direction".into()))?;
4871    }
4872    let turns = Turns { points, directions, rates: motion.rates };
4873    // A convex polyhedron, by the trim engine (default off).
4874    if let SolidTool::Polyhedron { vertices, faces } = tool {
4875        if crate::solid_sweep_trim::trim_engine_on() {
4876            let two = crate::solid_sweep_trim::TwoTurnMotion { points, directions, rates: motion.rates };
4877            return crate::solid_sweep_trim::sweep_convex_tumbled(vertices, faces, &two, motion.from, motion.to);
4878        }
4879    }
4880    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
4881        return Err(refuse("tumble_tool", "a tumble sweeps a solid of revolution only".into()));
4882    };
4883    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
4884    let base = Screw {
4885        a: points[0],
4886        e: directions[0],
4887        omega: motion.rates[0].abs() + motion.rates[1].abs(),
4888        c: 0.0,
4889        c2: 0.0,
4890        t0: motion.from,
4891        t1: motion.to,
4892        frame: None,
4893        turns: Some(turns),
4894        frozen: None,
4895        loop_samples: LOFT_SAMPLES,
4896        extent: points[1].sub(points[0]).length(),
4897    };
4898    let span = |t0: f64, t1: f64| -> Result<BrepSolid, KernelRefusal> {
4899        let mut screw = base;
4900        screw.t0 = t0;
4901        screw.t1 = t1;
4902        let mut last = None;
4903        // The loop's sampling doubles while the walls' rows miss between
4904        // samples (a thin ring's loop bends sharply before it folds).
4905        'samples: while screw.loop_samples <= 16 * LOFT_SAMPLES {
4906            for k in 0..8 {
4907                let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
4908                match lofted(&screw, *axis_origin, axis, reference, meridian) {
4909                    // A bulge that crosses a seam high up reads on the next
4910                    // wall as a part held away from its end: other seams too.
4911                    Err(error) if matches!(refused_as(&error), Some("loft_structure") | Some("end_trim_corner") | Some("end_trim_deep")) => last = Some(error),
4912                    Err(error) if refused_as(&error) == Some("loft_rows") => {
4913                        last = Some(error);
4914                        screw.loop_samples *= 2;
4915                        continue 'samples;
4916                    }
4917                    other => return other,
4918                }
4919            }
4920            break;
4921        }
4922        Err(last.expect("tried"))
4923    };
4924    // Bisect where the sweep folds over itself.
4925    let mut pending = vec![(motion.from, motion.to, 0usize)];
4926    let mut spans: Vec<(f64, BrepSolid)> = Vec::new();
4927    while let Some((t0, t1, depth)) = pending.pop() {
4928        match span(t0, t1) {
4929            Ok(body) => spans.push((t0, body)),
4930            Err(error) if refused_as(&error) == Some("folds") && depth < 6 => {
4931                let middle = 0.5 * (t0 + t1);
4932                pending.push((middle, t1, depth + 1));
4933                pending.push((t0, middle, depth + 1));
4934            }
4935            Err(error) => return Err(error),
4936        }
4937    }
4938    spans.sort_by(|a, b| a.0.total_cmp(&b.0));
4939    let mut bodies: Vec<BrepSolid> = spans.into_iter().map(|(_, body)| body).collect();
4940    if bodies.len() == 1 {
4941        return Ok(bodies.pop().expect("one"));
4942    }
4943    crate::boolean_operation_nary(&bodies, crate::BooleanOperation::Union)
4944}
4945
4946/// A cap's pcurve for a lofted edge through the cap's exact chart (the edge
4947/// read back into the tool's frame at the cap's time).
4948fn charted_pcurve(chart: &Chart, screw: &Screw, t: f64, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
4949    let [d0, d1] = frag(curve.domain(), "domain")?;
4950    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
4951    let mut uv = Vec::with_capacity(ts.len());
4952    let mut poles = Vec::with_capacity(ts.len());
4953    for &tt in &ts {
4954        let x = screw.invert(t, frag(curve.evaluate(tt), "point")?);
4955        let [u, v] = chart.invert(x);
4956        uv.push(Vec3::new(u, v, 0.0));
4957        poles.push(chart.at_pole(x));
4958    }
4959    // Where the path crosses a span joint of the chart, one quintic through
4960    // it rings between samples (the parameter's second derivative jumps
4961    // there): by the run between joints instead (`BREP_SWEEP_PCURVE_JOINTS`).
4962    if pcurve_joints_on() && !poles.iter().any(|&p| p) {
4963        let (joints_u, joints_v) = chart.joints();
4964        let at = |tt: f64| -> Result<[f64; 2], KernelRefusal> { Ok(chart.invert(screw.invert(t, frag(curve.evaluate(tt), "point")?))) };
4965        if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints_u, &joints_v, curve)? {
4966            return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
4967        }
4968    }
4969    continue_pole_angles(&mut uv, &ts, &poles)?;
4970    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "charted_pcurve")?;
4971    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
4972}
4973
4974/// A surface's joints in each parameter: its interior knots that leave it C1
4975/// or less (a rational circle's spans meet at double knots), where a chart's
4976/// parameter bends.
4977fn surface_joints(surface: &NurbsSurface) -> (Vec<f64>, Vec<f64>) {
4978    let joints = |knots: &[f64], degree: usize| -> Vec<f64> {
4979        let (first, last) = (knots[0], knots[knots.len() - 1]);
4980        let mut out: Vec<f64> = Vec::new();
4981        for (i, &k) in knots.iter().enumerate() {
4982            if k > first && k < last && (i == 0 || knots[i - 1] != k) && knots.iter().filter(|&&x| x == k).count() + 1 >= degree {
4983                out.push(k);
4984            }
4985        }
4986        out
4987    };
4988    (joints(&surface.knots_u, surface.degree_u), joints(&surface.knots_v, surface.degree_v))
4989}
4990
4991thread_local! {
4992    /// Set while a split is read only for its curves and structure (a loft's
4993    /// interior times): its caps' pcurves are then never used.
4994    static PCURVES_SKIPPED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4995}
4996
4997/// The switch for skipping the cap pcurves of a loft's interior splits
4998/// (default on, `=0` fits them all; the body is the same either way).
4999fn loft_splits_lean_on() -> bool {
5000    crate::switch!("BREP_SWEEP_LOFT_SPLITS_LEAN", true)
5001}
5002
5003/// `action` with the split's cap pcurves read at their ends only: a split at
5004/// a loft's interior time is read for its curves, samples and structure, its
5005/// caps' pcurves never (only the end poses' caps are built).
5006fn with_pcurves_skipped<T>(action: impl FnOnce() -> T) -> T {
5007    // Restored on the way out, an unwind too, so a caught panic leaves no
5008    // later sweep on this thread building its end caps' pcurves as lines.
5009    struct Restore(bool);
5010    impl Drop for Restore {
5011        fn drop(&mut self) {
5012            PCURVES_SKIPPED.with(|cell| cell.set(self.0));
5013        }
5014    }
5015    let _restore = Restore(PCURVES_SKIPPED.with(|cell| cell.replace(true)));
5016    action()
5017}
5018
5019/// A grazing curve through its exact samples (quintic); in a split read only
5020/// for its curves' samples and structure ([`with_pcurves_skipped`]: a loft's
5021/// interior times), the line between its ends, never read as a curve.
5022fn fit_tool_curve(points: &[Vec3], params: &[f64]) -> Result<NurbsCurve, String> {
5023    if PCURVES_SKIPPED.with(|cell| cell.get()) && points.len() >= 2 && params.len() == points.len() {
5024        let (a, b) = (params[0], params[params.len() - 1]);
5025        return NurbsCurve::new(1, vec![a, a, b, b], vec![Vec4::from_point(points[0], 1.0), Vec4::from_point(points[points.len() - 1], 1.0)]);
5026    }
5027    crate::interpolate_curve(points, 5, params)
5028}
5029
5030/// A cap pcurve's stations: the whole set, or its two ends where the pcurve
5031/// is never used ([`with_pcurves_skipped`]).
5032fn pcurve_stations(d0: f64, d1: f64) -> Vec<f64> {
5033    if PCURVES_SKIPPED.with(|cell| cell.get()) {
5034        return vec![d0, d1];
5035    }
5036    (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect()
5037}
5038
5039/// The quintic through a cap pcurve's stations; through two (a skipped
5040/// pcurve), the line between its ends.
5041fn fit_pcurve(uv: &[Vec3], ts: &[f64]) -> Result<NurbsCurve, String> {
5042    if ts.len() == 2 {
5043        return NurbsCurve::new(1, vec![ts[0], ts[0], ts[1], ts[1]], uv.iter().map(|&p| Vec4::from_point(p, 1.0)).collect());
5044    }
5045    crate::interpolate_curve(uv, 5, ts)
5046}
5047
5048/// The switch for [`jointed_pcurve`] (default on; `=0` fits one quintic as before).
5049fn pcurve_joints_on() -> bool {
5050    crate::switch!("BREP_SWEEP_PCURVE_JOINTS", true)
5051}
5052
5053/// A cap's pcurve broken where its path crosses a span joint of its chart:
5054/// the edge's parameter at each crossing found by bisection (`at` reads the
5055/// path's chart parameters at an edge parameter), each run between them
5056/// sampled as densely as the whole and interpolated (quintic) on its own, the
5057/// runs joined C0 at the crossings, so each run interpolates a smooth function
5058/// and the trim keeps to its edge at the same parameter, not only at the
5059/// samples. `ts`, `uv`: the whole's samples; `edge`: the curve the path
5060/// reads (its own C1-or-less knots are cut too). None where the path crosses
5061/// no joint (the one quintic is smooth there).
5062fn jointed_pcurve(ts: &[f64], uv: &[Vec3], at: impl Fn(f64) -> Result<[f64; 2], KernelRefusal>, joints_u: &[f64], joints_v: &[f64], edge: &NurbsCurve) -> Result<Option<NurbsCurve>, KernelRefusal> {
5063    if ts.len() < 3 || ts.len() != uv.len() {
5064        return Ok(None);
5065    }
5066    let (d0, d1) = (ts[0], ts[ts.len() - 1]);
5067    // The edge's own joints: an interior knot that leaves it C1 or less (a
5068    // rational arc's spans) kinks its parameter, so the path's too.
5069    let mut cuts: Vec<f64> = Vec::new();
5070    for (index, &k) in edge.knots.iter().enumerate() {
5071        if k > d0 && k < d1 && (index == 0 || edge.knots[index - 1] != k) {
5072            let multiplicity = edge.knots.iter().filter(|&&x| x == k).count();
5073            if multiplicity + 1 >= edge.degree {
5074                cuts.push(k);
5075            }
5076        }
5077    }
5078    for j in 0..ts.len() - 1 {
5079        let (a, b) = (uv[j], uv[j + 1]);
5080        for (coord, joints) in [(0usize, joints_u), (1, joints_v)] {
5081            let (ca, cb) = if coord == 0 { (a.x, b.x) } else { (a.y, b.y) };
5082            for &k in joints {
5083                // A sample on the joint itself is the cut (a path that only
5084                // touches it is cut there too, harmlessly).
5085                if ca == k && j > 0 {
5086                    cuts.push(ts[j]);
5087                    continue;
5088                }
5089                if (ca - k) * (cb - k) < 0.0 {
5090                    // Bisect the edge's parameter for the crossing.
5091                    let (mut lo, mut hi) = (ts[j], ts[j + 1]);
5092                    let side = ca < k;
5093                    for _ in 0..80 {
5094                        let mid = 0.5 * (lo + hi);
5095                        if mid <= lo || mid >= hi {
5096                            break;
5097                        }
5098                        if (at(mid)?[coord] < k) == side { lo = mid } else { hi = mid }
5099                    }
5100                    cuts.push(0.5 * (lo + hi));
5101                }
5102            }
5103        }
5104    }
5105    if cuts.is_empty() {
5106        return Ok(None);
5107    }
5108    // Each run at least a millionth of the whole: a cut nearer an end or
5109    // another than that is dropped (its run would be too short to fit).
5110    let least = 1e-6 * (d1 - d0);
5111    cuts.sort_by(f64::total_cmp);
5112    let mut bounds = vec![d0];
5113    for c in cuts {
5114        if c - bounds[bounds.len() - 1] >= least && d1 - c >= least {
5115            bounds.push(c);
5116        }
5117    }
5118    if bounds.len() == 1 {
5119        return Ok(None);
5120    }
5121    bounds.push(d1);
5122    let samples = ts.len() - 1;
5123    let degree = 5;
5124    let mut knots: Vec<f64> = Vec::new();
5125    let mut poles: Vec<Vec4> = Vec::new();
5126    let runs = bounds.len() - 1;
5127    for (index, run) in bounds.windows(2).enumerate() {
5128        let (a, b) = (run[0], run[1]);
5129        let count = ((samples as f64 * (b - a) / (d1 - d0)).ceil() as usize).max(degree + 1);
5130        let params: Vec<f64> = (0..=count).map(|i| if i == count { b } else { a + (b - a) * i as f64 / count as f64 }).collect();
5131        let points: Vec<Vec3> = params.iter().map(|&tt| at(tt).map(|[u, v]| Vec3::new(u, v, 0.0))).collect::<Result<_, _>>()?;
5132        // A run that does not fit falls back to the one quintic, never a refusal.
5133        let Ok(piece) = crate::interpolate_curve(&points, degree, &params) else { return Ok(None) };
5134        if piece.degree != degree {
5135            return Ok(None);
5136        }
5137        let n = piece.knots.len();
5138        if index == 0 {
5139            knots.extend_from_slice(&piece.knots[..n - (degree + 1)]);
5140            poles.extend_from_slice(&piece.control_points);
5141        } else {
5142            // The joint: its parameter `degree` times (C0), this run's interior
5143            // knots; its first pole is the previous run's last.
5144            knots.extend(std::iter::repeat_n(a, degree));
5145            knots.extend_from_slice(&piece.knots[degree + 1..n - (degree + 1)]);
5146            poles.extend_from_slice(&piece.control_points[1..]);
5147        }
5148        if index + 1 == runs {
5149            knots.extend(std::iter::repeat_n(b, degree + 1));
5150        }
5151    }
5152    Ok(NurbsCurve::new(degree, knots, poles).ok())
5153}
5154
5155/// An edge through its surface's pole (a ball carried square to its own
5156/// axis: every grazing circle runs pole to pole) has no angle there, and the
5157/// inverse returns any. Each sample at a pole (`poles`) takes the first
5158/// parameter its neighbours run to, continued in a line.
5159fn continue_pole_angles(uv: &mut [Vec3], ts: &[f64], poles: &[bool]) -> Result<(), KernelRefusal> {
5160    for j in 0..uv.len() {
5161        if !poles[j] {
5162            continue;
5163        }
5164        let near = if j + 2 < uv.len() && !poles[j + 1] && !poles[j + 2] {
5165            [j + 1, j + 2]
5166        } else if j >= 2 && !poles[j - 1] && !poles[j - 2] {
5167            [j - 1, j - 2]
5168        } else {
5169            return Err(refuse("cap_pole", "a lofted edge stays on its cap's pole".into()));
5170        };
5171        let (a, b) = (uv[near[0]].x, uv[near[1]].x);
5172        uv[j].x = a + (a - b) * (ts[j] - ts[near[0]]) / (ts[near[0]] - ts[near[1]]);
5173    }
5174    Ok(())
5175}
5176
5177/// A cap's pcurve for a lofted edge: its dense image on the cap's surface.
5178fn projected_pcurve(surface: &NurbsSurface, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
5179    let [d0, d1] = frag(curve.domain(), "domain")?;
5180    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
5181    let mut uv = Vec::with_capacity(ts.len());
5182    let mut poles = Vec::with_capacity(ts.len());
5183    let [u0, u1] = frag(surface.domain_u(), "domain")?;
5184    let step = 1e-3 * (u1 - u0);
5185    for &t in &ts {
5186        let x = frag(curve.evaluate(t), "point")?;
5187        let foot = frag(crate::project_point_to_surface(surface, x), "project")?;
5188        if foot.distance > 1e-6 * (1.0 + x.length()) {
5189            return Err(refuse("loft_cap", format!("a lofted edge leaves its cap by {} at {x:?}", foot.distance)));
5190        }
5191        uv.push(Vec3::new(foot.u, foot.v, 0.0));
5192        // A pole of the surface: its points do not move with the first
5193        // parameter there.
5194        let aside = if foot.u + step <= u1 { foot.u + step } else { foot.u - step };
5195        let moved = frag(surface.evaluate(aside, foot.v), "point")?.sub(frag(surface.evaluate(foot.u, foot.v), "point")?).length();
5196        poles.push(moved <= 1e-9 * (1.0 + x.length()));
5197    }
5198    continue_pole_angles(&mut uv, &ts, &poles)?;
5199    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "projected_pcurve")?;
5200    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
5201}
5202
5203type Signature = (Vec<(usize, usize, bool)>, Vec<(bool, Vec<(usize, bool)>)>, Vec<(usize, bool)>);
5204
5205fn signature(split: &Split) -> Result<Signature, KernelRefusal> {
5206    Ok((
5207        split.curves.iter().map(|c| (c.start, c.end, c.degenerate)).collect(),
5208        split.caps.iter().map(|cap| (cap.front, cap.coedges.iter().map(|&(c, f, _)| (c, f)).collect())).collect(),
5209        split.grazing()?,
5210    ))
5211}
5212
5213fn lofted(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<BrepSolid, KernelRefusal> {
5214    let split_at = |t: f64| -> Result<Split, KernelRefusal> {
5215        let mut frozen = *screw;
5216        frozen.frozen = Some(t);
5217        split_revolved(&frozen, origin, axis, radial, meridian)
5218    };
5219    let mut lambdas: Vec<f64> = (0..=LOFT_SAMPLES).map(|i| i as f64 / LOFT_SAMPLES as f64).collect();
5220    // World samples of grazing curve c at time t, in the wall's direction.
5221    let samples_of = |split: &Split, c: usize, back_forward: bool, t: f64| -> Result<Vec<Vec3>, KernelRefusal> {
5222        let Some(list) = &split.curves[c].samples else {
5223            return Err(refuse("loft_samples", "a grazing curve has no exact samples to loft".into()));
5224        };
5225        let mut world: Vec<Vec3> = list.iter().map(|&x| screw.apply(t, x)).collect();
5226        if back_forward {
5227            world.reverse();
5228        }
5229        Ok(world)
5230    };
5231    // Time breaks start even and are refined only in the spans whose middle
5232    // misses, by the quintic's h^6 error: a smooth stretch of the motion keeps
5233    // its long spans (doubling everywhere tripled the wall for one bend).
5234    let mut fractions: Vec<f64> = (0..=15).map(|j| j as f64 / 15.0).collect();
5235    loop {
5236        let count = fractions.len() - 1;
5237        // The walls' second parameter runs 0 -> 1 over the motion.
5238        let times: Vec<f64> = fractions.iter().map(|&f| if f == 1.0 { screw.t1 } else { screw.t0 + (screw.t1 - screw.t0) * f }).collect();
5239        // Only the end poses' caps are built: the interior splits are read
5240        // for their curves and structure, their caps' pcurves skipped
5241        // (`BREP_SWEEP_LOFT_SPLITS_LEAN`).
5242        let lean = loft_splits_lean_on();
5243        let splits: Vec<Split> = times
5244            .iter()
5245            .enumerate()
5246            .map(|(j, &t)| if lean && j != 0 && j != count { with_pcurves_skipped(|| split_at(t)) } else { split_at(t) })
5247            .collect::<Result<_, _>>()?;
5248        if splits.iter().any(|split| !split.slides.is_empty() || !split.slide_sides.is_empty()) {
5249            return Err(refuse("loft_structure", "a flat end that slides within its own plane is not lofted".into()));
5250        }
5251        let shape = signature(&splits[0])?;
5252        for split in &splits[1..] {
5253            if signature(split)? != shape {
5254                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
5255            }
5256        }
5257        let grazing = shape.2.clone();
5258        if grazing.is_empty() {
5259            return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
5260        }
5261        let scale = splits[0].scale + screw.extent;
5262        let target = LOFT_TARGET * scale;
5263        // Walls: per grazing curve, rows along it at each time, then across time.
5264        let mut walls = Vec::with_capacity(grazing.len());
5265        // Every wall's exact samples at every time.
5266        let mut sampled: Vec<Vec<Vec<Vec3>>> = Vec::with_capacity(grazing.len());
5267        for &(c, back_forward) in &grazing {
5268            let mut at_times = Vec::with_capacity(times.len());
5269            for (j, split) in splits.iter().enumerate() {
5270                let points = samples_of(split, c, back_forward, times[j])?;
5271                if points.len() != lambdas.len() {
5272                    if points.len() < 13 || points.len() % 2 == 0 {
5273                        return Err(refuse("loft_samples", "a grazing curve's exact samples cannot be lofted".into()));
5274                    }
5275                    lambdas = (0..points.len()).map(|i| i as f64 / (points.len() - 1) as f64).collect();
5276                }
5277                at_times.push(points);
5278            }
5279            sampled.push(at_times);
5280        }
5281        // A row through every `stride`-th sample: its worst miss at the
5282        // samples it leaves out, over every wall and time.
5283        let thinned = |stride: usize| -> Result<f64, KernelRefusal> {
5284            let coarse_lambdas: Vec<f64> = lambdas.iter().step_by(stride).copied().collect();
5285            let mut worst = 0.0f64;
5286            for at_times in &sampled {
5287                for points in at_times {
5288                    let coarse_points: Vec<Vec3> = points.iter().step_by(stride).copied().collect();
5289                    let coarse = frag(crate::interpolate_curve(&coarse_points, 5, &coarse_lambdas), "loft_row")?;
5290                    for (i, x) in points.iter().enumerate().filter(|(i, _)| i % stride != 0) {
5291                        worst = worst.max(frag(coarse.evaluate(lambdas[i]), "loft_row")?.sub(*x).length());
5292                    }
5293                }
5294            }
5295            Ok(worst)
5296        };
5297        // Each wall's rows pass through as few of its samples as hold every
5298        // exact sample within a quarter of the target, at every time (a loop
5299        // smooth but for one sharp bend needs its samples only there, and the
5300        // wall's size is what the solid's users pay for): from every 16th,
5301        // a stretch that misses at a sample it leaves out gets its middle one.
5302        let spans = lambdas.len() - 1;
5303        let mut kept: Vec<Vec<usize>> = Vec::with_capacity(sampled.len());
5304        for at_times in &sampled {
5305            let coarsest = if spans % 16 == 0 && spans >= 96 { 16 } else { 1 };
5306            let mut subset: Vec<usize> = (0..=spans).step_by(coarsest).collect();
5307            loop {
5308                let subset_lambdas: Vec<f64> = subset.iter().map(|&i| lambdas[i]).collect();
5309                let mut misses = vec![0.0f64; subset.len() - 1];
5310                for points in at_times {
5311                    let row_points: Vec<Vec3> = subset.iter().map(|&i| points[i]).collect();
5312                    let row = frag(crate::interpolate_curve(&row_points, 5, &subset_lambdas), "loft_row")?;
5313                    for k in 0..subset.len() - 1 {
5314                        for i in subset[k] + 1..subset[k + 1] {
5315                            misses[k] = misses[k].max(frag(row.evaluate(lambdas[i]), "loft_row")?.sub(points[i]).length());
5316                        }
5317                    }
5318                }
5319                let mut refined = Vec::with_capacity(2 * subset.len());
5320                for k in 0..subset.len() - 1 {
5321                    refined.push(subset[k]);
5322                    if misses[k] > 0.25 * target {
5323                        refined.push((subset[k] + subset[k + 1]) / 2);
5324                    }
5325                }
5326                refined.push(spans);
5327                if refined.len() == subset.len() {
5328                    break;
5329                }
5330                subset = refined;
5331            }
5332            kept.push(subset);
5333        }
5334        // Where a wall keeps neighbouring samples there is none left out
5335        // between them to measure at: a row passes through its samples, and
5336        // between them it is as good as the loop is smooth at that spacing.
5337        // Its miss there is estimated from the rows through every other
5338        // sample, scaled by the quintic's 2^-6.
5339        let dense = kept.iter().any(|subset| subset.windows(2).any(|pair| pair[1] == pair[0] + 1));
5340        let between = if dense { thinned(2)? / 64.0 } else { 0.0 };
5341        for (index, &(c, back_forward)) in grazing.iter().enumerate() {
5342            let row_lambdas: Vec<f64> = kept[index].iter().map(|&i| lambdas[i]).collect();
5343            let mut rows: Vec<NurbsCurve> = Vec::with_capacity(times.len());
5344            for points in &sampled[index] {
5345                let row_points: Vec<Vec3> = kept[index].iter().map(|&i| points[i]).collect();
5346                rows.push(frag(crate::interpolate_curve(&row_points, 5, &row_lambdas), "loft_row")?);
5347            }
5348            let knots_u = rows[0].knots.clone();
5349            let mut net: Vec<Vec<Vec4>> = Vec::with_capacity(rows[0].control_points.len());
5350            let mut knots_v = Vec::new();
5351            for k in 0..rows[0].control_points.len() {
5352                let column: Vec<Vec3> = rows.iter().map(|row| row.control_points[k].point()).collect::<Result<_, _>>().map_err(|e| refuse("loft", e))?;
5353                let across = frag(crate::interpolate_curve(&column, 5, &fractions), "loft_column")?;
5354                knots_v = across.knots.clone();
5355                net.push(across.control_points.clone());
5356            }
5357            let surface = frag(NurbsSurface::new(5, 5, knots_u, knots_v, net), "loft_wall")?;
5358            walls.push((c, back_forward, surface, rows.first().cloned().expect("rows"), rows.last().cloned().expect("rows")));
5359        }
5360        if between > target {
5361            return Err(refuse("loft_rows", format!("the lofted wall's rows stay about {between:e} off the grazing loop between its samples")));
5362        }
5363        // Against the exact loop in the middle of each span, every sample.
5364        let mut misses = vec![0.0f64; count];
5365        for j in 0..count {
5366            let t = 0.5 * (times[j] + times[j + 1]);
5367            let fraction = 0.5 * (fractions[j] + fractions[j + 1]);
5368            let split = if lean { with_pcurves_skipped(|| split_at(t))? } else { split_at(t)? };
5369            if signature(&split)? != shape {
5370                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
5371            }
5372            for (c, back_forward, surface, _, _) in &walls {
5373                let exact = samples_of(&split, *c, *back_forward, t)?;
5374                for (i, x) in exact.iter().enumerate() {
5375                    misses[j] = misses[j].max(frag(surface.evaluate(lambdas[i], fraction), "loft_check")?.sub(*x).length());
5376                }
5377            }
5378        }
5379        let worst = misses.iter().copied().fold(0.0f64, f64::max);
5380        if worst > target {
5381            if count > 2000 {
5382                return Err(refuse("loft_accuracy", format!("the lofted wall stays {worst:e} off the grazing loop")));
5383            }
5384            // A span missing by more than half the target is cut into
5385            // ceil((e / (target / 4))^(1/6)) pieces; the rest stay.
5386            let mut refined = Vec::with_capacity(2 * fractions.len());
5387            for j in 0..count {
5388                let pieces = if misses[j] > 0.5 * target { ((misses[j] / (0.25 * target)).powf(1.0 / 6.0).ceil() as usize).max(2) } else { 1 };
5389                for k in 0..pieces {
5390                    refined.push(fractions[j] + (fractions[j + 1] - fractions[j]) * k as f64 / pieces as f64);
5391                }
5392            }
5393            refined.push(1.0);
5394            fractions = refined;
5395            continue;
5396        }
5397        // Each K corner's path through the sample times.
5398        let mut paths: HashMap<usize, Vec<Vec3>> = HashMap::new();
5399        for &(c, _) in &grazing {
5400            for r in [splits[0].curves[c].start, splits[0].curves[c].end] {
5401                paths.entry(r).or_insert_with(|| splits.iter().zip(&times).map(|(split, &t)| screw.apply(t, split.points[r])).collect());
5402            }
5403        }
5404        return assemble_lofted(screw, &splits[0], &splits[count], &walls, &fractions, &paths, target);
5405    }
5406}
5407
5408/// Refuse a lofted wall with an edge of regression: across one the wall's
5409/// normal turns over, and the band beside it lies inside nearby poses (the
5410/// sweep folds within a few degrees of the motion, which no probe walk is
5411/// dense enough to be sure of seeing). Normals are compared between
5412/// neighbours on every time row and between rows, outside what the end trims
5413/// take away (`removed`, chart rings) and a few columns off its edge (a fold
5414/// line meets the end at the cut's own ends). `fit`: how near the wall keeps
5415/// to its exact loop (a length).
5416fn wall_regular(surface: &NurbsSurface, fractions: &[f64], removed: &[&[[f64; 2]]], fit: f64) -> Result<(), KernelRefusal> {
5417    const COLUMNS: usize = 4 * LOFT_SAMPLES;
5418    let mut rows: Vec<f64> = Vec::with_capacity(2 * fractions.len());
5419    for j in 0..fractions.len() {
5420        rows.push(fractions[j]);
5421        if j + 1 < fractions.len() {
5422            rows.push(0.5 * (fractions[j] + fractions[j + 1]));
5423        }
5424    }
5425    let normal = |u: f64, v: f64| -> Result<Option<Vec3>, KernelRefusal> {
5426        let h = 1e-6;
5427        let (ua, ub, va, vb) = ((u - h).max(0.0), (u + h).min(1.0), (v - h).max(0.0), (v + h).min(1.0));
5428        let du = frag(surface.evaluate(ub, v), "regular")?.sub(frag(surface.evaluate(ua, v), "regular")?).scale(1.0 / (ub - ua));
5429        let dv = frag(surface.evaluate(u, vb), "regular")?.sub(frag(surface.evaluate(u, va), "regular")?).scale(1.0 / (vb - va));
5430        // Where the wall's two directions all but line up, or it is no
5431        // wider than its own fit's ripple (a corner it pinches to), it has
5432        // no normal to speak of: the fit's noise would turn it.
5433        let cross = du.cross(dv);
5434        if cross.length() <= 1e-6 * du.length() * dv.length() || du.length().min(dv.length()) <= 1e3 * fit {
5435            return Ok(None);
5436        }
5437        Ok(cross.normalized().ok())
5438    };
5439    // Each trimmed-away ring's box, grown by the reach of `near_ring` and a hair: a point
5440    // outside it is neither inside the ring (a closed polygon) nor that near it, so the box
5441    // answers for it as the ring's own tests would.
5442    let reach = 4.0 / COLUMNS as f64;
5443    let boxes: Vec<[f64; 4]> = removed
5444        .iter()
5445        .map(|ring| {
5446            let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
5447            for p in ring.iter() {
5448                lo = [lo[0].min(p[0]), lo[1].min(p[1])];
5449                hi = [hi[0].max(p[0]), hi[1].max(p[1])];
5450            }
5451            let pad = reach * (1.0 + 1e-9) + 1e-12;
5452            [lo[0] - pad, hi[0] + pad, lo[1] - pad, hi[1] + pad]
5453        })
5454        .collect();
5455    let mut previous: Option<Vec<Option<Vec3>>> = None;
5456    for &v in &rows {
5457        // What a trim takes away is not part of the body.
5458        let row: Vec<Option<Vec3>> = (0..=COLUMNS)
5459            .map(|i| {
5460                let u = i as f64 / COLUMNS as f64;
5461                let taken = removed.iter().zip(&boxes).any(|(ring, b)| {
5462                    !(u < b[0] || u > b[1] || v < b[2] || v > b[3]) && (inside_ring(ring, [u, v]) || near_ring(ring, [u, v], reach))
5463                });
5464                if taken { Ok(None) } else { normal(u, v) }
5465            })
5466            .collect::<Result<_, _>>()?;
5467        for i in 0..COLUMNS {
5468            if let (Some(a), Some(b)) = (row[i], row[i + 1]) {
5469                if a.dot(b) < -0.5 {
5470                    return Err(refuse("wall_folds", format!("a lofted wall turns over (an edge of regression near parameter ({:.4}, {v:.4})); the sweep folds onto itself", i as f64 / COLUMNS as f64)));
5471                }
5472            }
5473            if let Some(Some(Some(a))) = previous.as_ref().map(|p| p.get(i).copied()) {
5474                if let Some(b) = row[i] {
5475                    if a.dot(b) < -0.5 {
5476                        return Err(refuse("wall_folds", format!("a lofted wall turns over (an edge of regression near parameter ({:.4}, {v:.4})); the sweep folds onto itself", i as f64 / COLUMNS as f64)));
5477                    }
5478                }
5479            }
5480        }
5481        previous = Some(row);
5482    }
5483    Ok(())
5484}
5485
5486/// A stretch of a wall's row at v, from u = a to u = b, as an edge's curve.
5487fn row_piece(wall: &NurbsSurface, v: f64, a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
5488    let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
5489    let along: Vec<Vec3> = ts.iter().map(|&s| frag(wall.evaluate((a + (b - a) * s).clamp(0.0, 1.0), v), "wall")).collect::<Result<_, _>>()?;
5490    frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
5491}
5492
5493/// A wall's end row in pieces around its trims and breaks (one more than the
5494/// spans), at v.
5495fn row_pieces(wall: &NurbsSurface, v: f64, spans: &[TrimSpan]) -> Result<Vec<NurbsCurve>, KernelRefusal> {
5496    let mut pieces = Vec::with_capacity(spans.len() + 1);
5497    let mut from = 0.0;
5498    for span in spans {
5499        pieces.push(row_piece(wall, v, from, span.lambdas[0])?);
5500        from = span.lambdas[1];
5501    }
5502    pieces.push(row_piece(wall, v, from, 1.0)?);
5503    Ok(pieces)
5504}
5505
5506/// The wall over u ∈ [a, b] only, in the same parameters.
5507/// Can `pcurve` (in a wall's chart) meet the split segment u = tip.u, v in
5508/// [v_lo, v_hi], anywhere but at the tip itself? A pcurve that ENDS at the
5509/// tip (a side of the double curve) touches it there: a short stub at that end
5510/// must leave the tip into one side of the line or away from the segment, and
5511/// the rest is tested. Every other piece is decided on the convex hull of its
5512/// control points (positive weights), halved where a hull straddles the
5513/// segment; one still straddling after 24 halvings counts as meeting it.
5514fn hull_meets_segment(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64) -> Result<bool, KernelRefusal> {
5515    let uv = |p: &Vec4| [p.x / p.w, p.y / p.w];
5516    let near_tip = |p: [f64; 2]| (p[0] - tip[0]).abs() <= 1e-9 && (p[1] - tip[1]).abs() <= 1e-9;
5517    let (first, last) = (uv(&pcurve.control_points[0]), uv(&pcurve.control_points[pcurve.control_points.len() - 1]));
5518    if !(near_tip(first) || near_tip(last)) {
5519        return hull_straddles(pcurve, tip, v_lo, v_hi, 0);
5520    }
5521    if near_tip(first) && near_tip(last) {
5522        return Ok(true);
5523    }
5524    let [d0, d1] = frag(pcurve.domain(), "domain")?;
5525    let at = if near_tip(first) { d0 + 1e-3 * (d1 - d0) } else { d1 - 1e-3 * (d1 - d0) };
5526    let (a, b) = frag(pcurve.split(at), "split")?;
5527    let (stub, rest) = if near_tip(first) { (a, b) } else { (b, a) };
5528    let side: Vec<f64> = stub.control_points.iter().map(|p| uv(p)[0] - tip[0]).collect();
5529    let one_side = side.iter().all(|d| *d >= -1e-12) || side.iter().all(|d| *d <= 1e-12);
5530    // The segment runs from the tip towards the far row: away is the other way.
5531    let segment_below = v_lo < tip[1] - 1e-12;
5532    let away = stub.control_points.iter().all(|p| if segment_below { uv(p)[1] >= tip[1] - 1e-9 } else { uv(p)[1] <= tip[1] + 1e-9 });
5533    if !(one_side || away) {
5534        return Ok(true);
5535    }
5536    hull_straddles(&rest, tip, v_lo, v_hi, 0)
5537}
5538
5539fn hull_straddles(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64, depth: usize) -> Result<bool, KernelRefusal> {
5540    let points: Vec<[f64; 2]> = pcurve.control_points.iter().map(|p| [p.x / p.w, p.y / p.w]).collect();
5541    let (u_min, u_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[0]), hi.max(p[0])));
5542    let (w_min, w_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[1]), hi.max(p[1])));
5543    if u_min > tip[0] + 1e-12 || u_max < tip[0] - 1e-12 || w_min > v_hi + 1e-12 || w_max < v_lo - 1e-12 {
5544        return Ok(false);
5545    }
5546    if depth >= 24 {
5547        return Ok(true);
5548    }
5549    let [d0, d1] = frag(pcurve.domain(), "domain")?;
5550    match pcurve.split(0.5 * (d0 + d1)) {
5551        Ok((a, b)) => Ok(hull_straddles(&a, tip, v_lo, v_hi, depth + 1)? || hull_straddles(&b, tip, v_lo, v_hi, depth + 1)?),
5552        // Too short to halve: count it as meeting the segment.
5553        Err(_) => Ok(true),
5554    }
5555}
5556
5557/// `BREP_SWEEP_SPLIT_CROSSING` (default on; `=0` off): a lofted wall that
5558/// turns over near one end is split at its swallowtail's point whenever the
5559/// split segment to the far row crosses no trim curve, not only where the
5560/// trimmed row keeps to its side of the tip's u; otherwise the wall stays one
5561/// face carrying its double curve as a slot (one edge used twice), which
5562/// meshes poorly at the slot's tip.
5563fn split_crossing_on() -> bool {
5564    crate::switch!("BREP_SWEEP_SPLIT_CROSSING", true)
5565}
5566
5567fn restrict_u(surface: &NurbsSurface, a: f64, b: f64) -> Result<NurbsSurface, KernelRefusal> {
5568    let [u0, u1] = frag(surface.domain_u(), "domain")?;
5569    if a <= u0 + 1e-12 && b >= u1 - 1e-12 {
5570        return Ok(surface.clone());
5571    }
5572    let columns = surface.control_points[0].len();
5573    let mut knots = Vec::new();
5574    let mut net: Vec<Vec<Vec4>> = Vec::new();
5575    for j in 0..columns {
5576        let line: Vec<Vec4> = surface.control_points.iter().map(|row| row[j]).collect();
5577        let mut curve = frag(NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), line), "restrict")?;
5578        if b < u1 - 1e-12 {
5579            curve = frag(curve.split(b), "restrict")?.0;
5580        }
5581        if a > u0 + 1e-12 {
5582            curve = frag(curve.split(a), "restrict")?.1;
5583        }
5584        if j == 0 {
5585            knots = curve.knots.clone();
5586            net = vec![Vec::with_capacity(columns); curve.control_points.len()];
5587        }
5588        for (i, point) in curve.control_points.iter().enumerate() {
5589            net[i].push(*point);
5590        }
5591    }
5592    frag(NurbsSurface::new(surface.degree_u, surface.degree_v, knots, surface.knots_v.clone(), net), "restrict")
5593}
5594
5595/// One place a wall is cut back where an end pose bulges past it: the wall
5596/// parameter range [λa, λb] along the grazing loop where the trim leaves and
5597/// rejoins it, the cut (from the point at λa to the point at λb, on both the
5598/// wall and the pose), the wall's side of the trim from λa to λb (`chain`),
5599/// the double curve and its swallowtail point if the trim follows one, and
5600/// the part of the wall's chart it takes away (`removed`, (u, v) points
5601/// around it).
5602struct TrimSpan {
5603    lambdas: [f64; 2],
5604    points: [Vec3; 2],
5605    /// None: no cut at all, only a break in the end's row at λa = λb (where
5606    /// a line splitting the wall lands on it).
5607    cut: Option<NurbsCurve>,
5608    chain: Vec<(TrimPiece, bool, NurbsCurve)>,
5609    slot: Option<(NurbsCurve, Vec3)>,
5610    /// The swallowtail's point in the wall's chart (u, v), where the trim
5611    /// follows a double curve.
5612    tip: Option<[f64; 2]>,
5613    removed: Vec<[f64; 2]>,
5614}
5615
5616/// Every place an end pose bulges past one wall, in order along the loop, and
5617/// the loop's pieces around them (one more than the spans).
5618struct EndTrim {
5619    spans: Vec<TrimSpan>,
5620    pieces: Vec<NurbsCurve>,
5621}
5622
5623/// Which edge a piece of a trimmed wall's end runs on: the cut it shares with
5624/// the cap, or the wall's own double curve (both of the slot's sides).
5625#[derive(Clone, Copy, PartialEq, Eq, Debug)]
5626enum TrimPiece {
5627    Cut,
5628    Slot,
5629}
5630
5631/// The cut of a lofted wall (u along the grazing loop, v the motion's time
5632/// fraction) by the pose at its end (`end` 0: v = 0, 1: v = 1), if the pose
5633/// bulges past it, else None.
5634///
5635/// The wall meets the pose along K and leaves it to second order (K grazes),
5636/// so with ε the time fraction from the end, f = d / ε² (d the pose's signed
5637/// distance) is smooth up to the end. The part of the wall inside the pose is
5638/// where f < 0; its boundary is traced as the curve f = 0 from the end and back
5639/// to it. It need not be a graph over u: a tongue of it may run on past where
5640/// it left the end.
5641///
5642/// `fit`: how near the wall keeps to the exact loop (a length).
5643fn end_trim(screw: &Screw, split: &Split, t: f64, wall: &NurbsSurface, end: usize, fit: f64) -> Result<Option<EndTrim>, KernelRefusal> {
5644    let v_of = |e: f64| if end == 1 { 1.0 - e } else { e };
5645    let at = |u: f64, e: f64| -> Result<Vec3, KernelRefusal> { frag(wall.evaluate(u.clamp(0.0, 1.0), v_of(e)), "wall") };
5646    let f = |u: f64, e: f64| -> Result<f64, KernelRefusal> { Ok(split.distance(screw.invert(t, at(u, e)?)) / (e * e)) };
5647    // Below `floor` the walls' fit swamps d / ε².
5648    let floor = 1e-3;
5649    // How far into the motion (as a fraction of it) a trim may reach (a fold
5650    // band can run most of a span); past that the end pose meets a distant
5651    // part of the sweep (`end_trim_deep`).
5652    let window = 0.6;
5653    let noise = 2.0 * fit / (floor * floor);
5654    // Where the wall dips into the pose just off the end.
5655    let n = 2000;
5656    let edge: Vec<f64> = (0..=n).map(|i| f(i as f64 / n as f64, floor)).collect::<Result<_, _>>()?;
5657    // Inside: the stretches where f is negative, those that dip below the
5658    // fit's noise somewhere (a stretch that never does is the fit's own).
5659    let mut inside: Vec<bool> = edge.iter().map(|&x| x < 0.0).collect();
5660    let mut i = 0;
5661    while i <= n {
5662        if !inside[i] {
5663            i += 1;
5664            continue;
5665        }
5666        let mut j = i;
5667        while j < n && inside[j + 1] {
5668            j += 1;
5669        }
5670        if edge[i..=j].iter().all(|&x| x >= -noise) {
5671            for flag in &mut inside[i..=j] {
5672                *flag = false;
5673            }
5674        }
5675        i = j + 1;
5676    }
5677    if !inside.iter().any(|&x| x) {
5678        // Nothing near the end; a pocket deeper in is caught below.
5679        return pierced(&f, floor, window, noise, &[]);
5680    }
5681    if inside[0] || inside[n] || inside[1] || inside[n - 1] {
5682        return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
5683    }
5684    // Crossings of the floor line, by bisection between samples of either sign.
5685    let mut crossings: Vec<f64> = Vec::new();
5686    for i in 0..n {
5687        if inside[i] != inside[i + 1] {
5688            let (mut a, mut b) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
5689            let a_inside = inside[i];
5690            for _ in 0..60 {
5691                let mid = 0.5 * (a + b);
5692                if (f(mid, floor)? < 0.0) == a_inside { a = mid } else { b = mid }
5693            }
5694            crossings.push(0.5 * (a + b));
5695        }
5696    }
5697    if crossings.len() % 2 != 0 || crossings.is_empty() {
5698        return Err(refuse("end_trim", "an end pose's bulges past a wall do not pair up".into()));
5699    }
5700    // Trace f = 0 from the first crossing of each pair into the wall until it
5701    // returns to the floor; it must come back at the pair's other crossing.
5702    let gradient = |u: f64, e: f64| -> Result<[f64; 2], KernelRefusal> {
5703        let h = 1e-6;
5704        Ok([(f(u + h, e)? - f(u - h, e)?) / (2.0 * h), (f(u, e + h)? - f(u, e - h)?) / (2.0 * h)])
5705    };
5706    let settle = |mut p: [f64; 2]| -> Result<[f64; 2], KernelRefusal> {
5707        for _ in 0..30 {
5708            let value = f(p[0], p[1])?;
5709            let g = gradient(p[0], p[1])?;
5710            let norm = g[0] * g[0] + g[1] * g[1];
5711            if norm == 0.0 {
5712                return Err(refuse("end_trim", "the cut of an end pose has a flat point".into()));
5713            }
5714            p = [p[0] - value * g[0] / norm, p[1] - value * g[1] / norm];
5715            if value.abs() * p[1] * p[1] < 1e-14 * split.scale {
5716                break;
5717            }
5718        }
5719        Ok(p)
5720    };
5721    let step = 1e-3;
5722    let mut cuts: Vec<Vec<[f64; 2]>> = Vec::new();
5723    // Each cut starts at the lowest crossing not yet used and ends at the
5724    // unused one it comes back to.
5725    let mut unused: Vec<f64> = crossings.clone();
5726    while !unused.is_empty() {
5727        let start = unused.remove(0);
5728        let mut points: Vec<[f64; 2]> = vec![[start, floor]];
5729        let mut heading = [0.0, 1.0];
5730        loop {
5731            let last = *points.last().expect("points");
5732            let g = gradient(last[0], last[1])?;
5733            let length = g[0].hypot(g[1]);
5734            let mut tangent = [-g[1] / length, g[0] / length];
5735            if tangent[0] * heading[0] + tangent[1] * heading[1] < 0.0 {
5736                tangent = [-tangent[0], -tangent[1]];
5737            }
5738            let next = settle([last[0] + step * tangent[0], last[1] + step * tangent[1]])?;
5739            if next[1] < floor {
5740                break;
5741            }
5742            if next[0] <= 1e-3 || next[0] >= 1.0 - 1e-3 {
5743                return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
5744            }
5745            if next[1] > window {
5746                return Err(refuse("end_trim_deep", "an end pose holds a deep part of a wall".into()));
5747            }
5748            if points.len() > 20_000 {
5749                return Err(refuse("end_trim", "the cut of an end pose does not close".into()));
5750            }
5751            heading = [next[0] - last[0], next[1] - last[1]];
5752            points.push(next);
5753        }
5754        let back = *points.last().expect("points");
5755        let Some(at_end) = unused.iter().position(|&c| (back[0] - c).abs() <= 2.0 * step) else {
5756            return Err(refuse("end_trim", "the cut of an end pose does not come back where it should".into()));
5757        };
5758        let back_at = unused.remove(at_end);
5759        // A dip that never rises off the floor and comes straight back is
5760        // the fit's noise at the end, not a bulge.
5761        if points.len() == 1 && (back_at - start).abs() <= step {
5762            continue;
5763        }
5764        points.push([back_at, floor]);
5765        // Down to the end itself along the cut's direction at the floor (taken
5766        // from the first point clearly above it).
5767        let to_end = |p: [f64; 2], rest: &[[f64; 2]], reversed: bool| -> Result<[f64; 2], KernelRefusal> {
5768            // Along the cut's own tangent there (across the gradient of f), so
5769            // the run to the end continues it smoothly.
5770            let g = gradient(p[0], p[1])?;
5771            if g[0].abs() > 1e-3 * g[1].abs() {
5772                return Ok([p[0] + g[1] / g[0] * p[1], 0.0]);
5773            }
5774            let clear = |q: &&[f64; 2]| q[1] - p[1] > 0.25 * step;
5775            let found = if reversed { rest.iter().rev().find(clear) } else { rest.iter().find(clear) };
5776            Ok(match found {
5777                Some(q) => [p[0] - (q[0] - p[0]) / (q[1] - p[1]) * p[1], 0.0],
5778                None => [p[0], 0.0],
5779            })
5780        };
5781        let count = points.len();
5782        let (first, last) = (to_end(points[0], &points[1..], false)?, to_end(points[count - 1], &points[..count - 1], true)?);
5783        if [first[0], last[0]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
5784            return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
5785        }
5786        points.insert(0, first);
5787        points.push(last);
5788        if points[0][0] > points[points.len() - 1][0] {
5789            points.reverse();
5790        }
5791        cuts.push(points);
5792    }
5793    let rings: Vec<&[[f64; 2]]> = cuts.iter().map(|c| c.as_slice()).collect();
5794    pierced(&f, floor, window, noise, &rings)?;
5795    let chart = |p: [f64; 2]| [p[0], v_of(p[1])];
5796    // A curve on the wall through chart points and its pcurve, both on the
5797    // given parameters (normalized to [0, 1]); chart-length parameters by
5798    // default (the wall's own speed collapses near an edge of regression, so
5799    // 3D chord lengths would bunch them).
5800    let chart_lengths = |chart_points: &[[f64; 2]]| -> Vec<f64> {
5801        let mut params = vec![0.0];
5802        for k in 1..chart_points.len() {
5803            let gap = (chart_points[k][0] - chart_points[k - 1][0]).hypot(chart_points[k][1] - chart_points[k - 1][1]);
5804            params.push(params[k - 1] + gap.max(1e-15));
5805        }
5806        params
5807    };
5808    // Returns the curve, its pcurve, and how far the pcurve's image strays
5809    // from the curve between the points.
5810    let curve_through = |chart_points: &[[f64; 2]], params: &[f64], what: &'static str| -> Result<(NurbsCurve, NurbsCurve, f64), KernelRefusal> {
5811        let total = *params.last().expect("params");
5812        let params: Vec<f64> = params.iter().map(|x| x / total).collect();
5813        let world: Vec<Vec3> = chart_points.iter().map(|p| at(p[0], p[1])).collect::<Result<_, _>>()?;
5814        let uv: Vec<Vec3> = chart_points.iter().map(|p| Vec3::new(p[0], v_of(p[1]), 0.0)).collect();
5815        let (curve, pcurve) = (frag(crate::interpolate_curve(&world, 5, &params), what)?, frag(crate::interpolate_curve(&uv, 5, &params), what)?);
5816        // Between the points too: the pcurve's image stays on the curve.
5817        let mut worst = 0.0f64;
5818        for k in 0..params.len() - 1 {
5819            let s = 0.5 * (params[k] + params[k + 1]);
5820            let q = frag(pcurve.evaluate(s), "pcurve")?;
5821            let e = if end == 1 { 1.0 - q.y } else { q.y };
5822            worst = worst.max(at(q.x, e)?.sub(frag(curve.evaluate(s), "curve")?).length());
5823        }
5824        Ok((curve, pcurve, worst))
5825    };
5826    // A trim curve is refined until its pcurve's image is within `fine` of
5827    // it, and taken as near as it gets if within `loose` (a double curve has
5828    // a cusp at its swallowtail's point, where no finer trace helps; a
5829    // tighter bar costs a thin tool many rounds and buys no reader anything).
5830    let (fine, loose) = (1e-7 * split.scale, 1e-7 * split.scale);
5831    let missed = |what: &str| refuse("end_trim", format!("the {what}'s pcurve leaves it between its points however finely it is traced"));
5832    // The cut, refined where its fit misses: a settled point between each
5833    // pair of traced ones (on the stretches run straight to the end, their
5834    // middles).
5835    let cut_through = |mut chart_points: Vec<[f64; 2]>| -> Result<(NurbsCurve, NurbsCurve), KernelRefusal> {
5836        let mut best: Option<(NurbsCurve, NurbsCurve, f64)> = None;
5837        for _ in 0..7 {
5838            let fitted = curve_through(&chart_points, &chart_lengths(&chart_points), "cut")?;
5839            let done = fitted.2 <= fine;
5840            if best.as_ref().map_or(true, |b| fitted.2 < b.2) {
5841                best = Some(fitted);
5842            }
5843            if done {
5844                break;
5845            }
5846            let mut finer = Vec::with_capacity(2 * chart_points.len());
5847            for k in 0..chart_points.len() - 1 {
5848                finer.push(chart_points[k]);
5849                let (p, q) = (chart_points[k], chart_points[k + 1]);
5850                let middle = [0.5 * (p[0] + q[0]), 0.5 * (p[1] + q[1])];
5851                // Below the floor the cut runs straight to the end: split it there as a line.
5852                finer.push(if p[1] >= floor && q[1] >= floor { settle(middle)? } else { middle });
5853            }
5854            finer.push(chart_points[chart_points.len() - 1]);
5855            chart_points = finer;
5856        }
5857        match best {
5858            Some((curve, pcurve, worst)) if worst <= loose => Ok((curve, pcurve)),
5859            _ => Err(missed("cut")),
5860        }
5861    };
5862    let piece = |a: f64, b: f64| -> Result<NurbsCurve, KernelRefusal> {
5863        let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
5864        let along: Vec<Vec3> = ts.iter().map(|&s| at(a + (b - a) * s, 0.0)).collect::<Result<_, _>>()?;
5865        frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
5866    };
5867    // Where the wall turns over near the end (a swallowtail), the cut passes
5868    // through a point of the end's own loop K a second time, on the wall's far
5869    // sheet: there the wall's double curve starts, and the trim follows it to
5870    // the swallowtail's point and back instead of the cut's first stretch.
5871    let span_of = |points: &Vec<[f64; 2]>| -> Result<TrimSpan, KernelRefusal> {
5872        if let Some((k, ua, b)) = double_start(&at, points, floor)? {
5873            // The double curve, traced more finely while its fit misses.
5874            let mut traced: Option<(Vec<[f64; 2]>, Vec<[f64; 2]>, NurbsCurve, NurbsCurve, NurbsCurve, f64)> = None;
5875            for round in 0..5 {
5876                let (a_side, b_side) = double_curve(&at, [ua, 0.0], b, window, 2e-3 / f64::from(1u32 << round))?;
5877                // Both sides on the continuation's own arc length, so the double
5878                // curve and its two pcurves share one parameter.
5879                let mut sigma = vec![0.0];
5880                for k in 1..a_side.len() {
5881                    let step = (a_side[k][0] - a_side[k - 1][0]).hypot(a_side[k][1] - a_side[k - 1][1]).hypot((b_side[k][0] - b_side[k - 1][0]).hypot(b_side[k][1] - b_side[k - 1][1]));
5882                    sigma.push(sigma[k - 1] + step.max(1e-15));
5883                }
5884                let ((slot, pa, miss_a), (_, pb, miss_b)) = (curve_through(&a_side, &sigma, "double_curve")?, curve_through(&b_side, &sigma, "double_curve")?);
5885                let worst = miss_a.max(miss_b);
5886                if traced.as_ref().map_or(true, |t| worst < t.5) {
5887                    traced = Some((a_side, b_side, slot, pa, pb, worst));
5888                }
5889                if worst <= fine {
5890                    break;
5891                }
5892            }
5893            let Some((a_side, b_side, slot, pa, pb, _)) = traced.filter(|t| t.5 <= loose) else { return Err(missed("double curve")) };
5894            // The cut keeps the stretch from the far sheet's point to its end away
5895            // from where the double curve leaves K.
5896            let low = ua < points[0][0];
5897            if !low && ua <= points[points.len() - 1][0] {
5898                return Err(refuse("end_trim", "the double curve of a wall leaves its end inside the cut".into()));
5899            }
5900            let mut kept: Vec<[f64; 2]> = if low { points[k..].to_vec() } else { points[..=k].to_vec() };
5901            if low { kept[0] = b } else { *kept.last_mut().expect("kept") = b }
5902            let (cut, cut_pcurve) = cut_through(kept.clone())?;
5903            let tip = at(a_side[a_side.len() - 1][0], a_side[a_side.len() - 1][1])?;
5904            // The wall's side of the trim from the low end to the high one.
5905            let chain = if low {
5906                vec![(TrimPiece::Slot, true, pa), (TrimPiece::Slot, false, frag(pb.reversed(), "reversed")?), (TrimPiece::Cut, true, cut_pcurve)]
5907            } else {
5908                vec![(TrimPiece::Cut, true, cut_pcurve), (TrimPiece::Slot, true, pb), (TrimPiece::Slot, false, frag(pa.reversed(), "reversed")?)]
5909            };
5910            let lambdas = if low { [ua, points[points.len() - 1][0]] } else { [points[0][0], ua] };
5911            let mut removed: Vec<[f64; 2]> = Vec::new();
5912            if low {
5913                removed.extend(a_side.iter().map(|&p| chart(p)));
5914                removed.extend(b_side.iter().rev().map(|&p| chart(p)));
5915                removed.extend(kept.iter().map(|&p| chart(p)));
5916            } else {
5917                removed.extend(kept.iter().map(|&p| chart(p)));
5918                removed.extend(b_side.iter().map(|&p| chart(p)));
5919                removed.extend(a_side.iter().rev().map(|&p| chart(p)));
5920            }
5921            // Everything the end pose holds must be in what goes.
5922            let dropped: Vec<[f64; 2]> = if low { points[..k].to_vec() } else { points[k + 1..].to_vec() };
5923            for p in dropped.iter().filter(|p| p[1] > 2.0 * floor && (p[0] - b[0]).hypot(p[1] - b[1]) > 5e-3) {
5924                if !inside_ring(&removed, chart(*p)) {
5925                    return Err(refuse("end_trim", "the cut of an end pose leaves the part of the wall its double curve takes away".into()));
5926                }
5927            }
5928            let points3 = [at(lambdas[0], 0.0)?, at(lambdas[1], 0.0)?];
5929            // The double curve's sides part about its end: one keeps to
5930            // each side of the swallowtail's point along the loop, so a
5931            // line through that point splits the wall between them.
5932            let tip_chart = chart(a_side[a_side.len() - 1]);
5933            let side = |points: &[[f64; 2]]| points.iter().map(|q| q[0] - tip_chart[0]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), d| (lo.min(d), hi.max(d)));
5934            let ((a_lo, a_hi), (b_lo, b_hi)) = (side(&a_side), side(&b_side));
5935            let parted = (a_lo >= -1e-9 && b_hi <= 1e-9) || (a_hi <= 1e-9 && b_lo >= -1e-9);
5936            if !parted {
5937                return Err(refuse("end_trim", "the two sides of a wall's double curve do not keep to either side of its end".into()));
5938            }
5939            return Ok(TrimSpan { lambdas, points: points3, cut: Some(cut), chain, slot: Some((slot, tip)), tip: Some(tip_chart), removed });
5940        }
5941        let (cut, wall_pcurve) = cut_through(points.clone())?;
5942        let (la, lb) = (points[0][0], points[points.len() - 1][0]);
5943        let removed: Vec<[f64; 2]> = points.iter().map(|&p| chart(p)).collect();
5944        Ok(TrimSpan { lambdas: [la, lb], points: [at(la, 0.0)?, at(lb, 0.0)?], cut: Some(cut), chain: vec![(TrimPiece::Cut, true, wall_pcurve)], slot: None, tip: None, removed })
5945    };
5946    if cuts.is_empty() {
5947        return pierced(&f, floor, window, noise, &[]);
5948    }
5949    let mut spans = Vec::with_capacity(cuts.len());
5950    for points in &cuts {
5951        spans.push(span_of(points)?);
5952    }
5953    spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
5954    // A trim wholly inside what another takes away adds nothing (a bulge of
5955    // the end pose inside a swallowtail's slot).
5956    let edge_row = v_of(0.0);
5957    let within = |inner: &TrimSpan, outer: &TrimSpan| -> bool {
5958        inner.lambdas[0] >= outer.lambdas[0]
5959            && inner.lambdas[1] <= outer.lambdas[1]
5960            && inner.removed.iter().filter(|p| (p[1] - edge_row).abs() > floor).all(|&p| inside_ring(&outer.removed, p) || near_ring(&outer.removed, p, 1e-3))
5961    };
5962    let mut k = 0;
5963    while k < spans.len() {
5964        if (0..spans.len()).any(|j| j != k && within(&spans[k], &spans[j])) {
5965            spans.remove(k);
5966        } else {
5967            k += 1;
5968        }
5969    }
5970    for pair in spans.windows(2) {
5971        if pair[0].lambdas[1] >= pair[1].lambdas[0] {
5972            return Err(refuse("end_trim", "an end pose's trims of a wall overlap".into()));
5973        }
5974    }
5975    let mut pieces = Vec::with_capacity(spans.len() + 1);
5976    let mut from = 0.0;
5977    for span in &spans {
5978        pieces.push(piece(from, span.lambdas[0])?);
5979        from = span.lambdas[1];
5980    }
5981    pieces.push(piece(from, 1.0)?);
5982    Ok(Some(EndTrim { spans, pieces }))
5983}
5984
5985
5986
5987/// Is q within `reach` of the closed polygon `ring`'s sides?
5988fn near_ring(ring: &[[f64; 2]], q: [f64; 2], reach: f64) -> bool {
5989    (0..ring.len()).any(|k| {
5990        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
5991        let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
5992        let length = dx * dx + dy * dy;
5993        let s = if length > 0.0 { (((q[0] - a[0]) * dx + (q[1] - a[1]) * dy) / length).clamp(0.0, 1.0) } else { 0.0 };
5994        (q[0] - a[0] - s * dx).hypot(q[1] - a[1] - s * dy) < reach
5995    })
5996}
5997
5998/// Is q inside the closed polygon `ring` (its last point joins its first)?
5999fn inside_ring(ring: &[[f64; 2]], q: [f64; 2]) -> bool {
6000    let mut crossings = 0;
6001    for k in 0..ring.len() {
6002        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
6003        if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (q[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) {
6004            crossings += 1;
6005        }
6006    }
6007    crossings % 2 == 1
6008}
6009
6010/// The point of an end pose's cut (chart points (u, ε), ε the time fraction
6011/// from the end) that lies on the end's own loop K a second time, away from
6012/// the cut's ends: (its index along the cut, the loop parameter u of the point
6013/// of K it meets, and the refined (u, ε) on the cut), if there is one.
6014fn double_start(at: &dyn Fn(f64, f64) -> Result<Vec3, KernelRefusal>, points: &[[f64; 2]], floor: f64) -> Result<Option<(usize, f64, [f64; 2])>, KernelRefusal> {
6015    let n = 4000;
6016    let row: Vec<Vec3> = (0..=n).map(|i| at(i as f64 / n as f64, 0.0)).collect::<Result<_, _>>()?;
6017    let scale = row.iter().fold(0.0f64, |m, p| m.max(p.sub(row[0]).length())).max(1e-300);
6018    let mut best: Option<(f64, usize, usize)> = None;
6019    for (k, p) in points.iter().enumerate() {
6020        if p[1] < 4.0 * floor {
6021            continue;
6022        }
6023        let x = at(p[0], p[1])?;
6024        let (i, d) = row.iter().enumerate().map(|(i, q)| (i, q.sub(x).length())).fold((0, f64::INFINITY), |a, b| if b.1 < a.1 { b } else { a });
6025        // The cut nears K at its own ends in proportion to ε; the second
6026        // meeting is where that ratio drops to nothing.
6027        if best.map_or(true, |b| d / p[1] < b.0 / points[b.1][1]) {
6028            best = Some((d, k, i));
6029        }
6030    }
6031    let Some((distance, k, i)) = best else { return Ok(None) };
6032    // Coarse: the cut's points are a few thousandths of the chart apart.
6033    if distance > 5e-3 * scale {
6034        return Ok(None);
6035    }
6036    // Newton on at(b) = at(u, 0) for (b_u, b_ε, u).
6037    let mut x = [points[k][0], points[k][1], i as f64 / n as f64];
6038    let h = 1e-7;
6039    for _ in 0..40 {
6040        let g = at(x[0], x[1])?.sub(at(x[2], 0.0)?);
6041        if g.length() < 1e-13 * scale {
6042            // Not the trivial meeting of the end row with itself.
6043            if x[1] < 2.0 * floor || !(0.0..=1.0).contains(&x[0]) || !(0.0..=1.0).contains(&x[2]) {
6044                return Ok(None);
6045            }
6046            return Ok(Some((k, x[2], [x[0], x[1]])));
6047        }
6048        let c0 = at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h);
6049        let c1 = at(x[0], x[1] + h)?.sub(at(x[0], x[1] - h)?).scale(0.5 / h);
6050        let c2 = at(x[2] + h, 0.0)?.sub(at(x[2] - h, 0.0)?).scale(-0.5 / h);
6051        let det = c0.dot(c1.cross(c2));
6052        if det.abs() < 1e-300 {
6053            break;
6054        }
6055        // Cramer's rule for [c0 c1 c2] d = -g.
6056        let r = g.scale(-1.0);
6057        let d = [r.dot(c1.cross(c2)) / det, c0.dot(r.cross(c2)) / det, c0.dot(c1.cross(r)) / det];
6058        x = [x[0] + d[0], x[1] + d[1], x[2] + d[2]];
6059    }
6060    if distance < 1e-6 * scale {
6061        return Err(refuse("end_trim", "an end pose's cut meets its own loop, but not exactly enough to follow".into()));
6062    }
6063    Ok(None)
6064}
6065
6066/// The double curve of a wall from where it leaves the end (a, on the end's
6067/// loop) and its partner b on the far sheet, traced by continuation of
6068/// at(a) = at(b) in (u, ε) for both, to the swallowtail point where the two
6069/// sides meet. Returns both sides' chart points, ending at the same point.
6070fn double_curve(at: &dyn Fn(f64, f64) -> Result<Vec3, KernelRefusal>, a: [f64; 2], b: [f64; 2], window: f64, step: f64) -> Result<(Vec<[f64; 2]>, Vec<[f64; 2]>), KernelRefusal> {
6071    let h = 1e-7;
6072    let scale = at(0.0, 0.0)?.sub(at(1.0, 0.0)?).length().max(at(0.5, 0.0)?.sub(at(0.0, 0.0)?).length()).max(1e-300);
6073    let jacobian = |x: [f64; 4]| -> Result<[Vec3; 4], KernelRefusal> {
6074        Ok([
6075            at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h),
6076            at(x[0], x[1] + h)?.sub(at(x[0], (x[1] - h).max(0.0))?).scale(1.0 / (h + x[1].min(h))),
6077            at(x[2] + h, x[3])?.sub(at(x[2] - h, x[3])?).scale(-0.5 / h),
6078            at(x[2], x[3] + h)?.sub(at(x[2], (x[3] - h).max(0.0))?).scale(-1.0 / (h + x[3].min(h))),
6079        ])
6080    };
6081    let residual = |x: [f64; 4]| -> Result<Vec3, KernelRefusal> { Ok(at(x[0], x[1])?.sub(at(x[2], x[3])?)) };
6082    // The null direction of the 3x4 Jacobian: its signed 3x3 minors.
6083    let null = |j: &[Vec3; 4]| -> [f64; 4] {
6084        let minor = |p: usize, q: usize, r: usize| j[p].dot(j[q].cross(j[r]));
6085        let n = [minor(1, 2, 3), -minor(0, 2, 3), minor(0, 1, 3), -minor(0, 1, 2)];
6086        let length = n.iter().map(|x| x * x).sum::<f64>().sqrt().max(1e-300);
6087        [n[0] / length, n[1] / length, n[2] / length, n[3] / length]
6088    };
6089    // Minimum-norm Newton back onto at(a) = at(b).
6090    let correct = |mut x: [f64; 4]| -> Result<Option<[f64; 4]>, KernelRefusal> {
6091        for _ in 0..30 {
6092            let g = residual(x)?;
6093            if g.length() < 1e-13 * scale {
6094                return Ok(Some(x));
6095            }
6096            let j = jacobian(x)?;
6097            // J Jᵀ y = -g, step = Jᵀ y.
6098            let mut m = [[0.0; 3]; 3];
6099            let rows = [[j[0].x, j[1].x, j[2].x, j[3].x], [j[0].y, j[1].y, j[2].y, j[3].y], [j[0].z, j[1].z, j[2].z, j[3].z]];
6100            for p in 0..3 {
6101                for q in 0..3 {
6102                    m[p][q] = (0..4).map(|c| rows[p][c] * rows[q][c]).sum();
6103                }
6104            }
6105            let det = m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
6106            if det.abs() < 1e-300 {
6107                return Ok(None);
6108            }
6109            let r = [-g.x, -g.y, -g.z];
6110            let solve = |col: usize| -> f64 {
6111                let mut a = m;
6112                for p in 0..3 {
6113                    a[p][col] = r[p];
6114                }
6115                (a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])) / det
6116            };
6117            let y = [solve(0), solve(1), solve(2)];
6118            for c in 0..4 {
6119                x[c] += (0..3).map(|p| rows[p][c] * y[p]).sum::<f64>();
6120            }
6121        }
6122        Ok(None)
6123    };
6124    let mut x = [a[0], a[1], b[0], b[1]];
6125    let mut a_side = vec![a];
6126    let mut b_side = vec![b];
6127    let mut heading: Option<[f64; 4]> = None;
6128    loop {
6129        let separation = (x[0] - x[2]).hypot(x[1] - x[3]);
6130        if separation < 3.0 * step && a_side.len() > 2 {
6131            let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
6132            a_side.push(tip);
6133            b_side.push(tip);
6134            return Ok((a_side, b_side));
6135        }
6136        let mut t = null(&jacobian(x)?);
6137        let reference = heading.unwrap_or([0.0, 1.0, 0.0, 0.0]);
6138        if (0..4).map(|c| t[c] * reference[c]).sum::<f64>() < 0.0 {
6139            t = [-t[0], -t[1], -t[2], -t[3]];
6140        }
6141        let mut next = None;
6142        let mut length = step;
6143        for _ in 0..6 {
6144            let guess = [x[0] + length * t[0], x[1] + length * t[1], x[2] + length * t[2], x[3] + length * t[3]];
6145            if let Some(y) = correct(guess)? {
6146                next = Some(y);
6147                break;
6148            }
6149            length *= 0.5;
6150        }
6151        let Some(y) = next else {
6152            // Near the swallowtail's point the two sheets turn tangent and
6153            // Newton gives out; close there if the sides are that near.
6154            if separation < 2e-2 && a_side.len() > 2 {
6155                let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
6156                a_side.push(tip);
6157                b_side.push(tip);
6158                return Ok((a_side, b_side));
6159            }
6160            return Err(refuse("end_trim", format!("the double curve of a wall cannot be followed (sides {separation:e} apart)")));
6161        };
6162        if [y[0], y[2]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
6163            return Err(refuse("end_trim_corner", DOUBLE_CURVE_CORNER.into()));
6164        }
6165        if y[1] > window || y[3] > window || y[1] < 0.0 || y[3] < 0.0 {
6166            return Err(refuse("end_trim_deep", format!("the double curve of a wall runs deep into the motion or back past its end (its sides at time fractions {:.4} and {:.4} from the end, {} points in)", y[1], y[3], a_side.len())));
6167        }
6168        if a_side.len() > 20_000 {
6169            return Err(refuse("end_trim", "the double curve of a wall does not close".into()));
6170        }
6171        heading = Some([y[0] - x[0], y[1] - x[1], y[2] - x[2], y[3] - x[3]]);
6172        x = y;
6173        a_side.push([x[0], x[1]]);
6174        b_side.push([x[2], x[3]]);
6175    }
6176}
6177
6178/// Refuse a wall the end pose holds a part of that no cut encloses: a pocket
6179/// of the wall inside the pose away from the end.
6180fn pierced(
6181    f: &dyn Fn(f64, f64) -> Result<f64, KernelRefusal>,
6182    floor: f64,
6183    window: f64,
6184    noise: f64,
6185    cuts: &[&[[f64; 2]]],
6186) -> Result<Option<EndTrim>, KernelRefusal> {
6187    let enclosed = |q: [f64; 2]| -> bool { cuts.iter().any(|ring| inside_ring(ring, q)) };
6188    for i in 1..200 {
6189        for j in 1..=40 {
6190            let (u, e) = (i as f64 / 200.0, floor + (window - floor) * (j as f64 / 40.0).powi(2));
6191            // d itself against the fit's noise: f grows as 1 / ε² near the end.
6192            if f(u, e)? * e * e < -noise * floor * floor && !enclosed([u, e]) {
6193                return Err(refuse("end_trim_deep", "an end pose holds a part of a wall away from its end".into()));
6194            }
6195        }
6196    }
6197    Ok(None)
6198}
6199
6200#[allow(clippy::too_many_arguments)]
6201fn assemble_lofted(
6202    screw: &Screw,
6203    first: &Split,
6204    last: &Split,
6205    walls: &[(usize, bool, NurbsSurface, NurbsCurve, NurbsCurve)],
6206    times: &[f64],
6207    paths: &HashMap<usize, Vec<Vec3>>,
6208    fit: f64,
6209) -> Result<BrepSolid, KernelRefusal> {
6210    let mut shell = Shell::new();
6211    let ends = [(first, screw.t0), (last, screw.t1)];
6212    // Where an end pose bulges past a wall near its grazing loop (a saddle side
6213    // curving past the wall it touches), cut the wall back to where it
6214    // re-enters the pose and carry the end cap across the loop to there.
6215    let mut trims: HashMap<(usize, usize), EndTrim> = HashMap::new();
6216    // Walls split into strips along lines through their swallowtails' points.
6217    let mut split_walls: std::collections::HashSet<usize> = std::collections::HashSet::new();
6218    for (index, (_, _, surface, _, _)) in walls.iter().enumerate() {
6219        for end in 0..2 {
6220            if let Some(trim) = end_trim(screw, ends[end].0, ends[end].1, surface, end, fit)? {
6221                trims.insert((index, end), trim);
6222            }
6223        }
6224        let removed: Vec<&[[f64; 2]]> = (0..2).filter_map(|end| trims.get(&(index, end))).flat_map(|trim| trim.spans.iter().map(|span| span.removed.as_slice())).collect();
6225        wall_regular(surface, times, &removed, fit)?;
6226        // A trim along a double curve has that curve as one edge on both its
6227        // sides: on one face its two uses could not be told apart from its
6228        // 3D curve alone (the wall passes through it twice). The wall is split
6229        // along the parameter line from each swallowtail's point to the far
6230        // end's row, which that row is broken at.
6231        let tips_at = |end: usize| -> Vec<[f64; 2]> { trims.get(&(index, end)).map(|trim| trim.spans.iter().filter_map(|span| span.tip).collect()).unwrap_or_default() };
6232        let (tips0, tips1) = (tips_at(0), tips_at(1));
6233        if !tips0.is_empty() && !tips1.is_empty() {
6234            return Err(refuse("wall_split", "a wall turns over near both its ends".into()));
6235        }
6236        let (far, tips) = if tips0.is_empty() { (0usize, tips1) } else { (1usize, tips0) };
6237        // A straight split line serves only where the trimmed row keeps to
6238        // its own side of it: all that comes before the swallowtail's point
6239        // along the row at or below its u, all after at or above. (A cut
6240        // that bulges across it would be crossed by the line; such a wall
6241        // stays one face.)
6242        let straight = |trim: &EndTrim| -> Result<bool, KernelRefusal> {
6243            for (k, span) in trim.spans.iter().enumerate() {
6244                let Some(tip) = span.tip else { continue };
6245                let first_slot = span.chain.iter().position(|piece| piece.0 == TrimPiece::Slot).unwrap_or(0);
6246                for (j, other) in trim.spans.iter().enumerate() {
6247                    for (n, (_, _, pcurve)) in other.chain.iter().enumerate() {
6248                        let before = j < k || (j == k && n <= first_slot);
6249                        let [d0, d1] = frag(pcurve.domain(), "domain")?;
6250                        for i in 0..=32 {
6251                            let u = frag(pcurve.evaluate(d0 + (d1 - d0) * i as f64 / 32.0), "pcurve")?.x;
6252                            if (before && u > tip[0] + 1e-9) || (!before && u < tip[0] - 1e-9) {
6253                                return Ok(false);
6254                            }
6255                        }
6256                    }
6257                }
6258            }
6259            Ok(true)
6260        };
6261        // Or, where the trimmed row strays across the tip's u only beyond the
6262        // tip (near its own end), the split segment itself: from the tip to
6263        // the far row, crossed by none of either end's trim curves. Each strip
6264        // then lies on the wall over the u its own pcurves span.
6265        let crossing_free = |trim_near: &EndTrim| -> Result<bool, KernelRefusal> {
6266            let v_far = far as f64;
6267            for tip in &tips {
6268                let (v_lo, v_hi) = if v_far < tip[1] { (v_far, tip[1]) } else { (tip[1], v_far) };
6269                let ends = [Some(trim_near), trims.get(&(index, far))];
6270                for trim in ends.into_iter().flatten() {
6271                    for span in &trim.spans {
6272                        for (_, _, pcurve) in &span.chain {
6273                            if hull_meets_segment(pcurve, tip, v_lo, v_hi)? {
6274                                return Ok(false);
6275                            }
6276                        }
6277                    }
6278                }
6279            }
6280            Ok(true)
6281        };
6282        let split_here = !tips.is_empty()
6283            && match trims.get(&(index, 1 - far)) {
6284                Some(trim) => straight(trim)? || (split_crossing_on() && crossing_free(trim)?),
6285                None => false,
6286            };
6287        if split_here {
6288            split_walls.insert(index);
6289            let v_far = far as f64;
6290            let mut spans = trims.remove(&(index, far)).map(|trim| trim.spans).unwrap_or_default();
6291            for tip in &tips {
6292                if spans.iter().any(|span| tip[0] > span.lambdas[0] - 1e-9 && tip[0] < span.lambdas[1] + 1e-9) || tip[0] <= 1e-9 || tip[0] >= 1.0 - 1e-9 {
6293                    return Err(refuse("wall_split", "a wall's split line lands in a trim of its far end".into()));
6294                }
6295                let point = frag(surface.evaluate(tip[0], v_far), "wall")?;
6296                spans.push(TrimSpan { lambdas: [tip[0], tip[0]], points: [point, point], cut: None, chain: Vec::new(), slot: None, tip: None, removed: Vec::new() });
6297            }
6298            spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
6299            let pieces = row_pieces(surface, v_far, &spans)?;
6300            trims.insert((index, far), EndTrim { spans, pieces });
6301        }
6302    }
6303    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
6304    let mut vertex = |shell: &mut Shell, end: usize, p: usize| -> u64 {
6305        *vertex_at.entry((end, p)).or_insert_with(|| shell.vertex(screw.apply(ends[end].1, ends[end].0.points[p])))
6306    };
6307    let grazing: HashMap<usize, usize> = walls.iter().enumerate().map(|(index, w)| (w.0, index)).collect();
6308    // Edges at each end: K curves from the walls' end rows (in the tool
6309    // curve's direction), the rest the end split's own curves moved.
6310    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
6311    let mut edge_curve: HashMap<(usize, usize), NurbsCurve> = HashMap::new();
6312    // Per trimmed wall end: the loop's piece edges, and each span's cut and
6313    // double-curve edges (u64::MAX where a span has none).
6314    let mut trim_edges: HashMap<(usize, usize), (Vec<u64>, Vec<[u64; 2]>)> = HashMap::new();
6315    // Per trimmed wall end and span: the vertex at its low end, and at the
6316    // swallowtail's point where it has one.
6317    let mut trim_vertices: HashMap<(usize, usize), Vec<(u64, Option<u64>)>> = HashMap::new();
6318    for end in 0..2 {
6319        let (split, t) = ends[end];
6320        for (c, tool_curve) in split.curves.iter().enumerate() {
6321            let used = split.caps.iter().any(|cap| cap.front == (end == 1) && cap.coedges.iter().any(|e| e.0 == c));
6322            if !used {
6323                continue;
6324            }
6325            if let Some(&index) = grazing.get(&c) {
6326                if let Some(trim) = trims.get(&(index, end)) {
6327                    // Pieces in the wall's direction: K up to the cut, the cut, K after it.
6328                    let back_forward = walls[index].1;
6329                    let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
6330                    let (vf, vt) = (vertex(&mut shell, end, from), vertex(&mut shell, end, to));
6331                    let mut piece_edges = Vec::with_capacity(trim.pieces.len());
6332                    let mut span_edges = Vec::with_capacity(trim.spans.len());
6333                    let mut start = vf;
6334                    let mut span_vertices = Vec::with_capacity(trim.spans.len());
6335                    for (span, piece) in trim.spans.iter().zip(&trim.pieces) {
6336                        let va = shell.vertex(span.points[0]);
6337                        piece_edges.push(shell.edge(piece.clone(), start, va, false)?);
6338                        let Some(cut_curve) = &span.cut else {
6339                            // A break only: the row goes on from the same vertex.
6340                            span_edges.push([u64::MAX, u64::MAX]);
6341                            span_vertices.push((va, None));
6342                            start = va;
6343                            continue;
6344                        };
6345                        let vb = shell.vertex(span.points[1]);
6346                        let cut = shell.edge(cut_curve.clone(), va, vb, false)?;
6347                        // The double curve runs from where it leaves K (at
6348                        // the low end of the span if its chain starts with
6349                        // it) to the swallowtail's point.
6350                        let (slot, tip_vertex) = match &span.slot {
6351                            Some((curve, tip)) => {
6352                                let from = if span.chain[0].0 == TrimPiece::Slot { va } else { vb };
6353                                let tip = shell.vertex(*tip);
6354                                (shell.edge(curve.clone(), from, tip, false)?, Some(tip))
6355                            }
6356                            None => (u64::MAX, None),
6357                        };
6358                        span_edges.push([cut, slot]);
6359                        span_vertices.push((va, tip_vertex));
6360                        start = vb;
6361                    }
6362                    trim_vertices.insert((index, end), span_vertices);
6363                    piece_edges.push(shell.edge(trim.pieces[trim.pieces.len() - 1].clone(), start, vt, false)?);
6364                    trim_edges.insert((index, end), (piece_edges, span_edges));
6365                    continue;
6366                }
6367            }
6368            let curve = match grazing.get(&c) {
6369                Some(&index) => {
6370                    let (_, back_forward, _, row0, row1) = &walls[index];
6371                    let row = if end == 0 { row0 } else { row1 };
6372                    if *back_forward { frag(row.reversed(), "reversed")? } else { row.clone() }
6373                }
6374                None => screw.move_curve(t, &tool_curve.curve)?,
6375            };
6376            let (a, b) = (vertex(&mut shell, end, tool_curve.start), vertex(&mut shell, end, tool_curve.end));
6377            let edge = shell.edge(curve.clone(), a, b, tool_curve.degenerate)?;
6378            edge_at.insert((end, c), edge);
6379            edge_curve.insert((end, c), curve);
6380        }
6381    }
6382    for end in 0..2 {
6383        let (split, t) = ends[end];
6384        for cap in split.caps.iter().filter(|cap| cap.front == (end == 1)) {
6385            let surface = screw.move_surface(t, &cap.surface)?;
6386            let mut coedges = Vec::with_capacity(cap.coedges.len());
6387            for (c, forward, pcurve) in &cap.coedges {
6388                if let Some(&index) = grazing.get(c) {
6389                    if let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) {
6390                        let Some(chart) = cap.chart.as_ref() else {
6391                            return Err(refuse("end_trim", "an end pose bulges past a wall beside a cap without a chart".into()));
6392                        };
6393                        // The cap runs the tool's curve forward or back; the
6394                        // pieces run the wall's way: loop piece, cut, loop
6395                        // piece, ... loop piece.
6396                        let along = *forward != walls[index].1;
6397                        let mut pieces: Vec<(u64, &NurbsCurve)> = Vec::with_capacity(2 * trim.pieces.len());
6398                        for (k, piece) in trim.pieces.iter().enumerate() {
6399                            pieces.push((piece_edges[k], piece));
6400                            if let Some(cut) = trim.spans.get(k).and_then(|span| span.cut.as_ref()) {
6401                                pieces.push((span_edges[k][0], cut));
6402                            }
6403                        }
6404                        if !along {
6405                            pieces.reverse();
6406                        }
6407                        for (edge, curve) in pieces {
6408                            coedges.push((edge, along, charted_pcurve(chart, screw, t, curve, along)?));
6409                        }
6410                        continue;
6411                    }
6412                }
6413                let pcurve = if grazing.contains_key(c) && cap.chart.is_some() {
6414                    charted_pcurve(cap.chart.as_ref().expect("chart"), screw, t, &edge_curve[&(end, *c)], *forward)?
6415                } else if grazing.contains_key(c) {
6416                    match projected_pcurve(&surface, &edge_curve[&(end, *c)], *forward) {
6417                        Ok(p) => p,
6418                        Err(error) => {
6419                            // Which: the exact samples themselves, or the row between them?
6420                            let samples = split.curves[*c].samples.as_ref().map(|list| {
6421                                list.iter()
6422                                    .map(|&x| crate::project_point_to_surface(&surface, screw.apply(t, x)).map(|f| f.distance).unwrap_or(f64::NAN))
6423                                    .fold(0.0f64, f64::max)
6424                            });
6425                            let line = split.curves[*c].curve.degree;
6426                            return Err(KernelRefusal::unsupported(
6427                                KernelStage::Classify,
6428                                "loft_cap",
6429                                format!("{} (curve {c} of degree {line}, end {end}, its exact samples off the cap by {samples:?}, cap degrees {}x{})", error.message, surface.degree_u, surface.degree_v),
6430                            ));
6431                        }
6432                    }
6433                } else {
6434                    pcurve.clone()
6435                };
6436                coedges.push((edge_at[&(end, *c)], *forward, pcurve));
6437            }
6438            shell.face(surface, coedges);
6439        }
6440    }
6441    // Orbits of K's corners: interpolated through the sample times as the
6442    // walls' end columns are.
6443    let mut orbits: HashMap<usize, u64> = HashMap::new();
6444    let mut keys: Vec<usize> = paths.keys().copied().collect();
6445    keys.sort_unstable();
6446    for r in keys {
6447        let curve = frag(crate::interpolate_curve(&paths[&r], 5, times), "orbit")?;
6448        let (a, b) = (vertex(&mut shell, 0, r), vertex(&mut shell, 1, r));
6449        orbits.insert(r, shell.edge(curve, a, b, false)?);
6450    }
6451    // One piece of a wall's end row in the direction of u: (edge, traversed
6452    // forward?, pcurve that way), and where a split line meets the row right
6453    // after it: (u, v, vertex).
6454    type RowPiece = (u64, bool, NurbsCurve, Option<(f64, f64, u64)>);
6455    for (index, (c, back_forward, surface, _, _)) in walls.iter().enumerate() {
6456        let tool_curve = &first.curves[*c];
6457        let (from, to) = if *back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
6458        let row = |end: usize| -> Result<Vec<RowPiece>, KernelRefusal> {
6459            let v = end as f64;
6460            let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) else {
6461                return Ok(vec![(edge_at[&(end, *c)], !*back_forward, uv_line([0.0, v], [1.0, v])?, None)]);
6462            };
6463            let vertices = &trim_vertices[&(index, end)];
6464            let mut list: Vec<RowPiece> = Vec::new();
6465            let mut at = 0.0;
6466            for (k, span) in trim.spans.iter().enumerate() {
6467                let broken = if span.cut.is_none() { Some((span.lambdas[0], v, vertices[k].0)) } else { None };
6468                list.push((piece_edges[k], true, uv_line([at, v], [span.lambdas[0], v])?, broken));
6469                for (n, (piece, forward, pcurve)) in span.chain.iter().enumerate() {
6470                    let edge = if *piece == TrimPiece::Cut { span_edges[k][0] } else { span_edges[k][1] };
6471                    // The swallowtail's point lies between the double curve's two uses.
6472                    let between = *piece == TrimPiece::Slot && span.chain.get(n + 1).is_some_and(|next| next.0 == TrimPiece::Slot);
6473                    let tip = match (span.tip, vertices[k].1) {
6474                        (Some(tip), Some(vertex)) if between && split_walls.contains(&index) => Some((tip[0], tip[1], vertex)),
6475                        _ => None,
6476                    };
6477                    list.push((edge, *forward, pcurve.clone(), tip));
6478                }
6479                at = span.lambdas[1];
6480            }
6481            list.push((piece_edges[trim.spans.len()], true, uv_line([at, v], [1.0, v])?, None));
6482            Ok(list)
6483        };
6484        let (bottom, top) = (row(0)?, row(1)?);
6485        let (low, high): (Vec<(f64, f64, u64)>, Vec<(f64, f64, u64)>) = (bottom.iter().filter_map(|piece| piece.3).collect(), top.iter().filter_map(|piece| piece.3).collect());
6486        if low.len() != high.len() || low.iter().zip(&high).any(|(a, b)| (a.0 - b.0).abs() > 1e-9) {
6487            return Err(refuse("wall_split", "a wall's split lines do not run from one end's row to the other's".into()));
6488        }
6489        // The split lines, each from its lower point to its upper.
6490        let mut lines: Vec<(u64, f64, f64, f64)> = Vec::with_capacity(low.len());
6491        for (below, above) in low.iter().zip(&high) {
6492            let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
6493            let along: Vec<Vec3> = ts.iter().map(|&s| frag(surface.evaluate(below.0, below.1 + (above.1 - below.1) * s), "wall")).collect::<Result<_, _>>()?;
6494            let edge = shell.edge(frag(crate::interpolate_curve(&along, 5, &ts), "split_line")?, below.2, above.2, false)?;
6495            lines.push((edge, below.0, below.1, above.1));
6496        }
6497        // Each row in the stretches between the split lines.
6498        let stretches = |list: Vec<RowPiece>| -> Vec<Vec<(u64, bool, NurbsCurve)>> {
6499            let mut out = vec![Vec::new()];
6500            for (edge, forward, pcurve, cut) in list {
6501                out.last_mut().expect("stretch").push((edge, forward, pcurve));
6502                if cut.is_some() {
6503                    out.push(Vec::new());
6504                }
6505            }
6506            out
6507        };
6508        let (bottoms, tops) = (stretches(bottom), stretches(top));
6509        // A strip between two split lines (or the wall's sides): along the
6510        // start row, up its far side, back along the end row, down its near
6511        // side; on the wall over its own stretch of u only.
6512        for j in 0..=lines.len() {
6513            let mut coedges = bottoms[j].clone();
6514            match lines.get(j) {
6515                Some(&(edge, u, v0, v1)) => coedges.push((edge, true, uv_line([u, v0], [u, v1])?)),
6516                None => coedges.push((orbits[&to], true, uv_line([1.0, 0.0], [1.0, 1.0])?)),
6517            }
6518            for (edge, forward, pcurve) in tops[j].iter().rev() {
6519                coedges.push((*edge, !*forward, frag(pcurve.reversed(), "reversed")?));
6520            }
6521            match j.checked_sub(1).map(|k| lines[k]) {
6522                Some((edge, u, v0, v1)) => coedges.push((edge, false, uv_line([u, v1], [u, v0])?)),
6523                None => coedges.push((orbits[&from], false, uv_line([0.0, 1.0], [0.0, 0.0])?)),
6524            }
6525            let (mut ua, mut ub) = (if j == 0 { 0.0 } else { lines[j - 1].1 }, lines.get(j).map_or(1.0, |line| line.1));
6526            // A strip whose trim strays past its split line (beyond the tip)
6527            // takes the wall over that u too: the parameters are the wall's.
6528            if lines.len() > 0 && split_crossing_on() {
6529                // Its control points bound each pcurve (positive weights).
6530                for (_, _, pcurve) in &coedges {
6531                    for point in &pcurve.control_points {
6532                        let u = point.x / point.w;
6533                        if u < ua - 1e-9 {
6534                            ua = u.max(0.0);
6535                        }
6536                        if u > ub + 1e-9 {
6537                            ub = u.min(1.0);
6538                        }
6539                    }
6540                }
6541            }
6542            shell.face(restrict_u(surface, ua, ub)?, coedges);
6543        }
6544    }
6545    let body = shell.solid();
6546    let issues = body.validate();
6547    if !issues.is_empty() {
6548        // Name the faces whose coedges stray: their pcurves' ends on the surface
6549        // against their edges' ends.
6550        let mut notes = Vec::new();
6551        for face in body.shells.iter().flat_map(|s| &s.faces) {
6552            for coedge in &face.loops[0].coedges {
6553                let edge = body.edges.iter().find(|e| e.id == coedge.edge_id).expect("edge");
6554                let [p0, p1] = frag(coedge.pcurve.domain(), "domain")?;
6555                let a = frag(coedge.pcurve.evaluate(p0), "uv")?;
6556                let on = frag(face.surface.evaluate_extended(a.x, a.y), "on")?;
6557                let at = frag(edge.curve.evaluate(if coedge.forward { edge.t0 } else { edge.t1 }), "at")?;
6558                if on.sub(at).length() > 1e-6 {
6559                    notes.push(format!("face {} (degrees {}x{}) coedge on edge {} starts {:?} on the surface, its edge {:?}", face.id, face.surface.degree_u, face.surface.degree_v, edge.id, on, at));
6560                }
6561                let _ = p1;
6562            }
6563        }
6564        return Err(refuse("assembly", format!("the lofted sweep is not valid: {:?}; {}", issues.first(), notes.iter().take(4).cloned().collect::<Vec<_>>().join("; "))));
6565    }
6566    check_single_pass(screw, first, &body, &std::collections::HashSet::new())?;
6567    Ok(body)
6568}
6569
6570/// Is the world point y inside the moving tool at some time of the motion?
6571/// Steps t by the distance over a bound on the speed of any tool point near y.
6572fn covered(screw: &Screw, split: &Split, reach: Option<&ToolReach>, y: Vec3, normal: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
6573    // A ball carried by a frame along a cubic: the question read off the cubic
6574    // (`BREP_SWEEP_BALL_COVER`, default on; its check mode walks as well).
6575    if crate::solid_sweep_one_pass::ball_cover_on() {
6576        if let (Some(frame), None, Shape::Revolved { origin, axis, meridian }) = (&screw.frame, &screw.turns, &split.shape) {
6577            if let Some((centre, r)) = crate::solid_sweep_one_pass::ball_of_revolved(*origin, *axis, meridian) {
6578                let offset = centre.sub(screw.a).length();
6579                if let Some(answer) = crate::solid_sweep_one_pass::ball_on_cubic_covered(frame.control, screw.t0, screw.t1, offset, r, y, margin) {
6580                    if !crate::solid_sweep_one_pass::ball_cover_check_on() {
6581                        return Ok(answer);
6582                    }
6583                    let walked = covered_walk(screw, split, reach, y, normal, margin)?;
6584                    crate::solid_sweep_one_pass::ball_cover_check_record(walked == answer);
6585                    return Ok(walked);
6586                }
6587            }
6588        }
6589    }
6590    covered_walk(screw, split, reach, y, normal, margin)
6591}
6592
6593/// [`covered`] by walking the motion.
6594fn covered_walk(screw: &Screw, split: &Split, reach: Option<&ToolReach>, y: Vec3, normal: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
6595    if reach.is_some_and(|reach| reach.never_inside(screw, y, normal, margin)) {
6596        return Ok(false);
6597    }
6598    if let Some(found) = reach.and_then(|reach| reach.turn_about_parallel_axis(screw, y, margin)) {
6599        return found;
6600    }
6601    let speed = preimage_speed_bound(screw, split, y);
6602    let floor = (screw.t1 - screw.t0) * 1e-7;
6603    let glide = Glide::of(screw, y);
6604    let mut t = screw.t0;
6605    let mut steps = 0usize;
6606    loop {
6607        let p = screw.invert(t, y);
6608        let d = split.distance(p);
6609        if d < -margin {
6610            return Ok(true);
6611        }
6612        if t >= screw.t1 {
6613            return Ok(false);
6614        }
6615        if steps > 2_000_000 {
6616            return Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into()));
6617        }
6618        let first = (d.abs() + margin) / speed;
6619        let second = glide.as_ref().map_or(0.0, |glide| glide.step(split, p, t, d, margin, speed, screw.t1 - t));
6620        let second = if second.is_finite() { second } else { 0.0 };
6621        t = (t + first.max(second).max(floor)).min(screw.t1);
6622        steps += 1;
6623    }
6624}
6625
6626/// The preimage of a probe under a plain screw, as an explicit curve: with
6627/// `u` the probe's offset from the axis square to it and `v = e × u`,
6628/// `p(t) = a + (e·(y − a) − advance(t))·e + cos(ωt)·u − sin(ωt)·v`. Its
6629/// second derivative is no longer than `ω²·|u| + 2|c₂|` (`curve`).
6630///
6631/// The walk in time steps by the tool's distance over the preimage's speed:
6632/// beside a wall the tool grazes (a thread's flank, a ball's groove) the
6633/// distance stays the probe's tiny offset through the whole contact and the
6634/// walk crawls, some π·√(2R/δ) steps a probe. Where the path runs along the
6635/// tool rather than into it, its tangent line stays clear of the tool for
6636/// far longer, and the path leaves that line by no more than `curve·h²/2`:
6637/// the second-order step is the longest `h` the tool's distance from the
6638/// tangent segment, less that, keeps above −margin. It is never shorter than
6639/// the first-order step, and skips no time the probe is deeper than the margin.
6640struct Glide {
6641    e: Vec3,
6642    u: Vec3,
6643    v: Vec3,
6644    omega: f64,
6645    c: f64,
6646    c2: f64,
6647    curve: f64,
6648    /// Under `frame_glide_on`, a frame riding a curve: the probe's preimage
6649    /// `a + R(−θ(t))(y − P(t))` read through the frame (frame, y).
6650    riding: Option<(Frame, Vec3)>,
6651    /// Under `turns_glide_on`, two turns about fixed axes: the probe's preimage under them (turns, y).
6652    turning: Option<(Turns, Vec3)>,
6653    /// Under `frame_windows_on`, the bound on |p''| over each of equal windows
6654    /// of the motion (start, width, bounds), each no looser than `curve`.
6655    windows: Option<(f64, f64, Vec<f64>)>,
6656}
6657
6658/// The riding frame's |p''| bound read window by window (default on; `=0`
6659/// keeps one bound over the whole motion). Either is a bound; a window's is
6660/// read where the step stays within it, so steps lengthen where the curve
6661/// bends gently.
6662fn frame_windows_on() -> bool {
6663    crate::switch!("BREP_SWEEP_FRAME_WINDOWS", true)
6664}
6665
6666/// The second-order step for two turns about fixed axes (`BREP_SWEEP_TURNS_GLIDE`, default on;
6667/// `=0` restores the first-order walk).
6668fn turns_glide_on() -> bool {
6669    crate::switch!("BREP_SWEEP_TURNS_GLIDE", true)
6670}
6671
6672/// The second-order step for frames riding a curve (default on; `=0` restores the first-order walk).
6673fn frame_glide_on() -> bool {
6674    crate::switch!("BREP_SWEEP_FRAME_GLIDE", true)
6675}
6676
6677impl Glide {
6678    fn of(screw: &Screw, y: Vec3) -> Option<Glide> {
6679        if let (Some(frame), None, true) = (&screw.frame, &screw.turns, frame_glide_on()) {
6680            return Glide::riding(screw, frame, y);
6681        }
6682        if let (Some(turns), true) = (&screw.turns, turns_glide_on()) {
6683            return Glide::turning(turns, y);
6684        }
6685        if screw.frame.is_some() || screw.turns.is_some() {
6686            return None;
6687        }
6688        let r = y.sub(screw.a);
6689        let u = r.sub(screw.e.scale(r.dot(screw.e)));
6690        let curve = screw.omega * screw.omega * u.length() + 2.0 * screw.c2.abs();
6691        // A bound rounded to nothing, or below the normal range, is not one:
6692        // only a slide (no turn, no rise) is straight.
6693        let straight = screw.omega == 0.0 && screw.c2 == 0.0;
6694        if !straight && !(curve >= f64::MIN_POSITIVE && curve.is_finite()) {
6695            return None;
6696        }
6697        Some(Glide { e: screw.e, u, v: screw.e.cross(u), omega: screw.omega, c: screw.c, c2: screw.c2, curve, riding: None, turning: None, windows: None })
6698    }
6699
6700    /// A frame riding a planar cubic: the preimage `p = a + R(−θ) q`,
6701    /// `q = y − P(t)`, turns about `up`, and its second derivative is
6702    /// `R(−θ)(θ'² up×(up×q) − θ'' up×q + 2θ' up×P' − P'')`, so
6703    /// `|p''| ≤ (θ'² + |θ''|)·|q| + 2|θ'|·|P'| + |P''|`. Over the motion's
6704    /// span |P'| and |P''| are bounded by their control polygons and |P'''|
6705    /// is a constant; `θ' = up·(P'×P'')/|P'|²` and θ'' are bounded through a
6706    /// lower bound on |P'| (its samples less |P''| times half their spacing;
6707    /// no glide where that is not positive); `|q| ≤ |y − P(t₀)| + |P'|·span`.
6708    fn riding(screw: &Screw, frame: &Frame, y: Vec3) -> Option<Glide> {
6709        let [p0, p1, p2, p3] = frame.control;
6710        let first = [p1.sub(p0), p2.sub(p1), p3.sub(p2)].map(|d| d.scale(3.0).length()).into_iter().fold(0.0f64, f64::max);
6711        let second = [p2.sub(p1.scale(2.0)).add(p0), p3.sub(p2.scale(2.0)).add(p1)].map(|d| d.scale(6.0).length()).into_iter().fold(0.0f64, f64::max);
6712        let third = p3.sub(p2.scale(3.0)).add(p1.scale(3.0)).sub(p0).scale(6.0).length();
6713        let (t0, t1) = (screw.t0, screw.t1);
6714        let n = 256;
6715        let slowest = (0..=n).map(|k| frame.first(t0 + (t1 - t0) * k as f64 / n as f64).length()).fold(f64::INFINITY, f64::min);
6716        let floor = slowest - second * 0.5 * (t1 - t0) / n as f64;
6717        if !(floor > 0.0) {
6718            return None;
6719        }
6720        let w1 = first * second / (floor * floor);
6721        let w2 = third * first / (floor * floor) + 2.0 * first * first * second * second / floor.powi(4);
6722        let q = y.sub(frame.point(t0)).length() + first * (t1 - t0);
6723        let curve = (w1 * w1 + w2) * q + 2.0 * w1 * first + second;
6724        if !(curve.is_finite() && curve >= f64::MIN_POSITIVE) {
6725            return None;
6726        }
6727        // Window by window: |P'| by the hull of its quadratic over the window,
6728        // |P''| (linear) at the window's ends, the floor on |P'| from eight
6729        // samples less |P''| times half their spacing, |q| from the window's
6730        // start; each bound kept no looser than the whole motion's.
6731        let windows = frame_windows_on().then(|| {
6732            let count = 32usize;
6733            let width = (t1 - t0) / count as f64;
6734            let bounds = (0..count)
6735                .map(|i| {
6736                    let (a, b) = (t0 + width * i as f64, t0 + width * (i + 1) as f64);
6737                    let (da, db) = (frame.first(a), frame.first(b));
6738                    let middle = da.add(frame.second(a).scale(0.5 * (b - a)));
6739                    let first_w = da.length().max(db.length()).max(middle.length());
6740                    let second_w = frame.second(a).length().max(frame.second(b).length());
6741                    let m = 8;
6742                    let slow = (0..=m).map(|j| frame.first(a + (b - a) * j as f64 / m as f64).length()).fold(f64::INFINITY, f64::min);
6743                    let floor_w = slow - second_w * 0.5 * (b - a) / m as f64;
6744                    if !(floor_w > 0.0) {
6745                        return curve;
6746                    }
6747                    let w1 = first_w * second_w / (floor_w * floor_w);
6748                    let w2 = third * first_w / (floor_w * floor_w) + 2.0 * first_w * first_w * second_w * second_w / floor_w.powi(4);
6749                    let q_w = y.sub(frame.point(a)).length() + first_w * (b - a);
6750                    let c = (w1 * w1 + w2) * q_w + 2.0 * w1 * first_w + second_w;
6751                    if c.is_finite() && c >= f64::MIN_POSITIVE { c.min(curve) } else { curve }
6752                })
6753                .collect::<Vec<f64>>();
6754            (t0, width, bounds)
6755        });
6756        let zero = Vec3::new(0.0, 0.0, 0.0);
6757        Some(Glide { e: frame.up, u: zero, v: zero, omega: 0.0, c: 0.0, c2: 0.0, curve, riding: Some((*frame, y)), turning: None, windows })
6758    }
6759
6760    /// Two turns about fixed axes (unit `d₀`, `d₁` through `P₀`, `P₁` at rates `r₀`, `r₁`): the
6761    /// preimage `p = P₀ + R₀(−r₀t)(x − P₀)`, `x = P₁ + R₁(−r₁t)(y − P₁)`. With `x' = −r₁ d₁×(x − P₁)`
6762    /// and `x'' = −r₁ d₁×x'`, `p'' = R₀(x'') − 2r₀ d₀×R₀(x') + r₀² d₀×(d₀×(p − P₀))`, so
6763    /// `|p''| ≤ (r₁² + 2|r₀ r₁|)·|y − P₁| + r₀²·(|y − P₁| + |P₁ − P₀|)` (rotations keep lengths).
6764    fn turning(turns: &Turns, y: Vec3) -> Option<Glide> {
6765        let a = y.sub(turns.points[1]).length();
6766        let d = a + turns.points[1].sub(turns.points[0]).length();
6767        let (r0, r1) = (turns.rates[0].abs(), turns.rates[1].abs());
6768        let curve = (r1 * r1 + 2.0 * r0 * r1) * a + r0 * r0 * d;
6769        if !(curve.is_finite() && curve >= f64::MIN_POSITIVE) {
6770            return None;
6771        }
6772        let zero = Vec3::new(0.0, 0.0, 0.0);
6773        Some(Glide { e: zero, u: zero, v: zero, omega: 0.0, c: 0.0, c2: 0.0, curve, riding: None, turning: Some((*turns, y)), windows: None })
6774    }
6775
6776    /// The bound on |p''| over [t, t + h]: the most of the windows it meets,
6777    /// or the whole motion's.
6778    fn curve_over(&self, t: f64, h: f64) -> f64 {
6779        match &self.windows {
6780            Some((t0, width, bounds)) => {
6781                let last = bounds.len() - 1;
6782                let index = |x: f64| -> usize {
6783                    let k = ((x - t0) / width).floor();
6784                    if k.is_nan() || k <= 0.0 { 0 } else { (k as usize).min(last) }
6785                };
6786                bounds[index(t)..=index(t + h)].iter().fold(0.0f64, |a, &b| a.max(b))
6787            }
6788            None => self.curve,
6789        }
6790    }
6791
6792    /// `p'(t)`.
6793    fn velocity(&self, t: f64) -> Vec3 {
6794        if let Some((turns, y)) = &self.turning {
6795            let (p0, p1) = (turns.points[0], turns.points[1]);
6796            let (d0, d1) = (turns.directions[0], turns.directions[1]);
6797            let (r0, r1) = (turns.rates[0], turns.rates[1]);
6798            let arm1 = y.sub(p1).rotate_about(d1, -r1 * t);
6799            let x_rate = d1.cross(arm1).scale(-r1);
6800            let arm0 = p1.add(arm1).sub(p0).rotate_about(d0, -r0 * t);
6801            return x_rate.rotate_about(d0, -r0 * t).sub(d0.cross(arm0).scale(r0));
6802        }
6803        if let Some((frame, y)) = &self.riding {
6804            // p' = R(−θ)(−θ' up×q − P'), q = y − P(t).
6805            let q = y.sub(frame.point(t));
6806            let inner = frame.up.cross(q).scale(-frame.angle_rate(t)).sub(frame.first(t));
6807            return inner.rotate_about(frame.up, -frame.angle(t));
6808        }
6809        let (sin, cos) = (self.omega * t).sin_cos();
6810        self.e
6811            .scale(-(self.c + 2.0 * self.c2 * t))
6812            .sub(self.u.scale(self.omega * sin))
6813            .sub(self.v.scale(self.omega * cos))
6814    }
6815
6816    /// The second-order step from `t`, where the preimage is `p` at the
6817    /// tool's distance `d` (at most `left`; 0 when it finds none).
6818    #[allow(clippy::too_many_arguments)]
6819    fn step(&self, split: &Split, p: Vec3, t: f64, d: f64, margin: f64, speed: f64, left: f64) -> f64 {
6820        let velocity = self.velocity(t);
6821        // (the planes' root is read in closed form under one bound: the
6822        // windows' over the rest of the motion)
6823        let m = if self.windows.is_some() { self.curve_over(t, left) } else { self.curve };
6824        match &split.shape {
6825            // Each face's plane alone bounds the distance from below:
6826            // g(t + h) ≥ g + g'·h − m·h²/2, held above −margin up to the root.
6827            Shape::Planes(planes) => {
6828                let mut best = 0.0f64;
6829                for (n, offset) in planes {
6830                    let g = n.dot(p) - offset;
6831                    if g + margin <= 0.0 {
6832                        continue;
6833                    }
6834                    let slope = n.dot(velocity);
6835                    // The root, in the form that neither overflows nor cancels.
6836                    let h = if m > 0.0 {
6837                        let root = slope.hypot((2.0 * m * (g + margin)).sqrt());
6838                        if slope >= 0.0 { (slope + root) / m } else { 2.0 * (g + margin) / (root - slope) }
6839                    } else if slope >= 0.0 {
6840                        left
6841                    } else {
6842                        (g + margin) / -slope
6843                    };
6844                    if h.is_finite() {
6845                        best = best.max(h);
6846                    }
6847                }
6848                best.min(left)
6849            }
6850            // In the meridian plane: the path (ρ, z) about the tool's axis and
6851            // its tangent segment, whose distance from the outline is bounded
6852            // below piece by piece; the path leaves the segment by at most
6853            // m₂·h²/2, m₂ = 2m + speed²/ρ_min (the radius' bend), ρ_min > 0.
6854            Shape::Revolved { origin, axis, meridian } => {
6855                if d < 0.0 {
6856                    return 0.0;
6857                }
6858                let r = p.sub(*origin);
6859                let z = r.dot(*axis);
6860                let flat = r.sub(axis.scale(z));
6861                let rho = flat.length();
6862                if rho <= 0.0 {
6863                    return 0.0;
6864                }
6865                let dz = velocity.dot(*axis);
6866                let dflat = velocity.sub(axis.scale(dz));
6867                let drho = flat.dot(dflat) / rho;
6868                let q = [rho, z];
6869                let walk_sqrt = walk_sqrt_on();
6870                let mut best = 0.0f64;
6871                let mut h = (d + margin) / speed;
6872                for _ in 0..64 {
6873                    h *= 2.0;
6874                    if h > left {
6875                        h = left;
6876                    }
6877                    // Under the windows, the speed over [t, t + h] by the
6878                    // step's own: |p'| ≤ |p'(t)| + m·h, no more than `speed`.
6879                    let (m, speed) = if self.windows.is_some() {
6880                        let m = self.curve_over(t, h);
6881                        (m, (velocity.length() + m * h).min(speed))
6882                    } else {
6883                        (m, speed)
6884                    };
6885                    let low = rho - speed * h;
6886                    if low <= 0.0 {
6887                        break;
6888                    }
6889                    let bend = 2.0 * m + speed * speed / low;
6890                    let end = [rho + drho * h, z + dz * h];
6891                    let clear = if walk_sqrt {
6892                        meridian.iter().map(|piece| segment_clearance_sqrt(piece, q, end)).fold(f64::INFINITY, f64::min)
6893                    } else {
6894                        meridian.iter().map(|piece| segment_clearance(piece, q, end)).fold(f64::INFINITY, f64::min)
6895                    };
6896                    // A segment that touches the outline may enter the tool: no bound.
6897                    let held = clear - 0.5 * bend * h * h;
6898                    if !held.is_finite() || clear <= 0.0 || held < -margin {
6899                        break;
6900                    }
6901                    best = h;
6902                    if h >= left {
6903                        break;
6904                    }
6905                }
6906                best
6907            }
6908        }
6909    }
6910}
6911
6912/// A lower bound on the distance between the segment `a`–`b` and a meridian
6913/// piece: a line piece's exact distance (0 where they cross), an arc's from
6914/// its whole circle.
6915fn segment_clearance(piece: &OutlinePiece, a: [f64; 2], b: [f64; 2]) -> f64 {
6916    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
6917    let dot = |p: [f64; 2], q: [f64; 2]| p[0] * q[0] + p[1] * q[1];
6918    let cross = |p: [f64; 2], q: [f64; 2]| p[0] * q[1] - p[1] * q[0];
6919    let to_segment = |x: [f64; 2], s: [f64; 2], e: [f64; 2]| -> f64 {
6920        let d = sub(e, s);
6921        let len2 = dot(d, d);
6922        let w = if len2 > 0.0 { (dot(sub(x, s), d) / len2).clamp(0.0, 1.0) } else { 0.0 };
6923        let foot = [s[0] + d[0] * w, s[1] + d[1] * w];
6924        let gap = sub(x, foot);
6925        gap[0].hypot(gap[1])
6926    };
6927    match *piece {
6928        OutlinePiece::Line { from, to } => {
6929            let (d1, d2) = (sub(b, a), sub(to, from));
6930            let denom = cross(d1, d2);
6931            if denom != 0.0 {
6932                let w = sub(from, a);
6933                let (s, t) = (cross(w, d2) / denom, cross(w, d1) / denom);
6934                if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
6935                    return 0.0;
6936                }
6937            }
6938            to_segment(a, from, to).min(to_segment(b, from, to)).min(to_segment(from, a, b)).min(to_segment(to, a, b))
6939        }
6940        OutlinePiece::Arc { centre, radius, .. } => {
6941            let near = to_segment(centre, a, b);
6942            let far = { let (x, y) = (sub(a, centre), sub(b, centre)); x[0].hypot(x[1]).max(y[0].hypot(y[1])) };
6943            (near - radius).max(radius - far).max(0.0)
6944        }
6945        // no bound read for an ellipse: zero is one
6946        OutlinePiece::Ellipse { .. } => 0.0,
6947    }
6948}
6949
6950/// The switch for [`segment_clearance_sqrt`] in the walk's second-order step
6951/// (default on; `=0` reads `segment_clearance`).
6952fn walk_sqrt_on() -> bool {
6953    crate::switch!("BREP_SWEEP_WALK_SQRT", true)
6954}
6955
6956/// [`segment_clearance`] without `hypot`: a line piece's least squared gap,
6957/// one square root; an arc's lengths by `sqrt` (within a rounding of `hypot`).
6958/// A square outside the range where squaring is exact to a rounding (below
6959/// 1e-290, which takes in an underflow to zero, or above 1e290) reads the
6960/// piece by `segment_clearance` instead.
6961fn segment_clearance_sqrt(piece: &OutlinePiece, a: [f64; 2], b: [f64; 2]) -> f64 {
6962    let in_range = |x: f64| (1e-290..=1e290).contains(&x);
6963    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
6964    let dot = |p: [f64; 2], q: [f64; 2]| p[0] * q[0] + p[1] * q[1];
6965    let cross = |p: [f64; 2], q: [f64; 2]| p[0] * q[1] - p[1] * q[0];
6966    let to_segment_squared = |x: [f64; 2], s: [f64; 2], e: [f64; 2]| -> f64 {
6967        let d = sub(e, s);
6968        let len2 = dot(d, d);
6969        let w = if len2 > 0.0 { (dot(sub(x, s), d) / len2).clamp(0.0, 1.0) } else { 0.0 };
6970        let gap = sub(x, [s[0] + d[0] * w, s[1] + d[1] * w]);
6971        dot(gap, gap)
6972    };
6973    match *piece {
6974        OutlinePiece::Line { from, to } => {
6975            let (d1, d2) = (sub(b, a), sub(to, from));
6976            let denom = cross(d1, d2);
6977            if denom != 0.0 {
6978                let w = sub(from, a);
6979                let (s, t) = (cross(w, d2) / denom, cross(w, d1) / denom);
6980                if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
6981                    return 0.0;
6982                }
6983            }
6984            let least = to_segment_squared(a, from, to)
6985                .min(to_segment_squared(b, from, to))
6986                .min(to_segment_squared(from, a, b))
6987                .min(to_segment_squared(to, a, b));
6988            if !in_range(least) {
6989                return segment_clearance(piece, a, b);
6990            }
6991            least.sqrt()
6992        }
6993        OutlinePiece::Arc { centre, radius, .. } => {
6994            let near = to_segment_squared(centre, a, b);
6995            let (x, y) = (sub(a, centre), sub(b, centre));
6996            let far = dot(x, x).max(dot(y, y));
6997            if !(in_range(near) && in_range(far)) {
6998                return segment_clearance(piece, a, b);
6999            }
7000            (near.sqrt() - radius).max(radius - far.sqrt()).max(0.0)
7001        }
7002        OutlinePiece::Ellipse { .. } => 0.0,
7003    }
7004}
7005
7006/// A bound on how fast the tool-frame preimage `screw.invert(t, y)` of the
7007/// world point `y` moves per unit `t`; the tool's distance (1-Lipschitz)
7008/// changes no faster along it.
7009///
7010/// A plain screw about one fixed axis carries the preimage round that axis at
7011/// its distance from it, `ρ`, and along it at the advance's rate, two motions
7012/// square to each other: no faster than `hypot(|ω|·ρ, rate)`. A point near the axis barely moves, so a probe beside
7013/// a tool point on the axis (a coin turned about a line through its rim) walks
7014/// the motion in a few long steps, not millions of floor-sized ones. A riding
7015/// frame or two turns keep the coarser bound through `a`.
7016fn preimage_speed_bound(screw: &Screw, split: &Split, y: Vec3) -> f64 {
7017    let speed = if screw.frame.is_none() && screw.turns.is_none() {
7018        let r = y.sub(screw.a);
7019        let rho = r.sub(screw.e.scale(r.dot(screw.e))).length();
7020        (screw.omega.abs() * rho).hypot(screw.rate_bound())
7021    } else {
7022        let reach = y.sub(screw.a).length() + split.scale + screw.extent;
7023        screw.omega.abs() * reach + screw.rate_bound()
7024    };
7025    speed.max(1e-300)
7026}
7027
7028/// How far a revolved tool reaches about a plain screw's axis: its axial
7029/// coordinate `e·(x − a)` lies within `axial` and its distance from the axis
7030/// within `radial`, for every tool point `x` (bounds, not extremes: a meridian
7031/// line is bounded at its ends, an arc by its whole circle).
7032///
7033/// A plain screw keeps each point's distance from its axis and shifts its
7034/// axial coordinate only by the advance (a slide keeps every coordinate across
7035/// its direction), so a point `y` whose preimage stays outside these bounds
7036/// all through the motion is never inside the tool, and `covered` need not
7037/// walk the motion to say so. Without this a probe beside a face the tool runs
7038/// along all through the motion (the flat top of a coin turned about a line
7039/// through its rim, the floor of an end mill's pass) creeps through it in
7040/// steps of its own tiny distance from the tool.
7041struct ToolReach {
7042    /// The tool's revolution: its origin less the screw's point, its unit axis
7043    /// and its meridian (radius, height along the axis).
7044    base: Vec3,
7045    axis: Vec3,
7046    meridian: Vec<OutlinePiece>,
7047    axial: [f64; 2],
7048    radial: [f64; 2],
7049}
7050
7051/// The largest of |m₀|·p + m₁·q over a meridian (p ≥ 0): a line at its ends,
7052/// an arc by its circle (Cauchy–Schwarz on the offset from its centre).
7053fn meridian_most(meridian: &[OutlinePiece], p: f64, q: f64) -> f64 {
7054    meridian
7055        .iter()
7056        .map(|piece| match *piece {
7057            OutlinePiece::Line { from, to } => (from[0].abs() * p + from[1] * q).max(to[0].abs() * p + to[1] * q),
7058            OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() * p + centre[1] * q + radius * p.hypot(q),
7059            // within the circle of its larger semi-axis
7060            OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() * p + centre[1] * q + semi[0].max(semi[1]) * p.hypot(q),
7061        })
7062        .fold(f64::NEG_INFINITY, f64::max)
7063}
7064
7065impl ToolReach {
7066    fn of(screw: &Screw, split: &Split) -> Option<ToolReach> {
7067        if screw.frame.is_some() || screw.turns.is_some() {
7068            return None;
7069        }
7070        let Shape::Revolved { origin, axis, meridian } = &split.shape else { return None };
7071        let e = screw.e;
7072        // x − a = (origin − a) + m₁·axis + m₀·(unit vector ⊥ axis).
7073        let base = origin.sub(screw.a);
7074        let along = axis.dot(e);
7075        let across = axis.cross(e).length();
7076        let middle = base.dot(e);
7077        let top = middle + meridian_most(meridian, across, along);
7078        let bottom = middle - meridian_most(meridian, across, -along);
7079        // Off the axis: within |(origin − a)⊥| ± (|m₀| + |m₁|·|axis⊥e|).
7080        let off = base.sub(e.scale(middle)).length();
7081        let spread = meridian
7082            .iter()
7083            .map(|piece| match *piece {
7084                OutlinePiece::Line { from, to } => (from[0].abs() + from[1].abs() * across).max(to[0].abs() + to[1].abs() * across),
7085                OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() + centre[1].abs() * across + radius * (1.0 + across * across).sqrt(),
7086                OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() + centre[1].abs() * across + semi[0].max(semi[1]) * (1.0 + across * across).sqrt(),
7087            })
7088            .fold(f64::NEG_INFINITY, f64::max);
7089        let reach = ToolReach { base, axis: *axis, meridian: meridian.clone(), axial: [bottom, top], radial: [off - spread, off + spread] };
7090        (top.is_finite() && bottom.is_finite() && spread.is_finite()).then_some(reach)
7091    }
7092
7093    /// `covered` for a turn (no advance) about an axis along the tool's own,
7094    /// walked in the tool's radius instead of in time; `None` when the motion
7095    /// is not such a turn.
7096    ///
7097    /// The preimage keeps its height along the tool's axis, and its distance
7098    /// from that axis is `ρ_w² = ρ² + s² − 2·ρ·s·cos(θ − θ_W)`, `ρ` its own
7099    /// distance from the turn's axis, `s` the tool axis' and `θ − θ_W` the
7100    /// angle between them, which the turn sweeps through an interval. So the
7101    /// preimage takes every radius between the least and the most `ρ_w` over
7102    /// that interval, and no other: it is ever deeper than the margin inside
7103    /// the tool if and only if some radius in that range is, at that height.
7104    /// The meridian's distance is 1-Lipschitz in the radius, so the range is
7105    /// walked by it. Each radius is met once, where the walk in time crawls
7106    /// past a probe the tool grazes (by the probe's own tiny offset over the
7107    /// turn's speed at each step).
7108    fn turn_about_parallel_axis(&self, screw: &Screw, y: Vec3, margin: f64) -> Option<Result<bool, KernelRefusal>> {
7109        if screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 || self.axis.cross(screw.e).length() != 0.0 {
7110            return None;
7111        }
7112        let e = screw.e;
7113        let r = y.sub(screw.a);
7114        // From the tool's origin to the probe, and its height along the tool's
7115        // axis (the turn keeps it).
7116        let from_tool = r.sub(self.base);
7117        let height = from_tool.dot(self.axis);
7118        // In the plane square to the axis, from the turn's axis: the probe `P`
7119        // and the tool's axis `W`, and the probe from the tool's axis, `P − W`
7120        // (formed as one difference, not as two far points less each other).
7121        let flat = |x: Vec3| x.sub(e.scale(x.dot(e)));
7122        let (probe, tool, apart) = (flat(r), flat(self.base), flat(from_tool));
7123        let (rho, s) = (probe.length(), tool.length());
7124        // Rounding of the coordinates read here, a few ulps of the largest: past
7125        // a quarter of the margin, the walk in time decides instead.
7126        let slack = 64.0 * f64::EPSILON * (r.length() + self.base.length() + height.abs());
7127        if slack > 0.25 * margin {
7128            return None;
7129        }
7130        // The preimage at time t is R(−ω·t)·P: its distance from the tool's axis
7131        // is |R(φ)·(P − W) + (R(φ) − I)·W|, with R(φ) − I = −2 sin²(φ/2) + sin φ·(e ×).
7132        let radius = |phi: f64| -> f64 {
7133            let half = (0.5 * phi).sin();
7134            let turned = apart.rotate_about(e, phi).add(tool.scale(-2.0 * half * half)).add(e.cross(tool).scale(phi.sin()));
7135            turned.length()
7136        };
7137        let (phi0, phi1) = (-screw.omega * screw.t0, -screw.omega * screw.t1);
7138        // The angle from W to P; R(φ)·P lies along W at start + φ ≡ 0 and opposite it at ≡ π.
7139        let start = if rho == 0.0 || s == 0.0 { 0.0 } else { e.dot(tool.cross(probe)).atan2(tool.dot(probe)) };
7140        let (lo, hi) = ((start + phi0).min(start + phi1), (start + phi0).max(start + phi1));
7141        // Does [lo, hi] hold an angle ≡ `at` (mod 2π)?
7142        let holds = |at: f64| (lo - at).div_euclid(TAU) != (hi - at).div_euclid(TAU) || (lo - at).rem_euclid(TAU) == 0.0;
7143        let ends = [radius(phi0), radius(phi1)];
7144        // | |P| − |W| | as |(P − W)·(P + W)| / (|P| + |W|): no cancellation.
7145        let nearest = if rho + s > 0.0 { apart.dot(probe.add(tool)).abs() / (rho + s) } else { 0.0 };
7146        let mut least = if holds(0.0) { nearest } else { ends[0].min(ends[1]) };
7147        let mut most = if holds(PI) { rho + s } else { ends[0].max(ends[1]) };
7148        least = (least - slack).max(0.0);
7149        most += slack;
7150        let mut at = least;
7151        // No floor on the step (it is never less than the margin): a floor
7152        // could step over a wall thinner than itself.
7153        let mut steps = 0usize;
7154        loop {
7155            let d = outline_signed_distance(&self.meridian, [at, height]);
7156            if d < -margin {
7157                return Some(Ok(true));
7158            }
7159            if at >= most {
7160                return Some(Ok(false));
7161            }
7162            if steps > 2_000_000 {
7163                return Some(Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into())));
7164            }
7165            at = (at + d.abs() + margin).min(most);
7166            steps += 1;
7167        }
7168    }
7169
7170    /// A bound on `u·(x − a)` over the tool, `u` a unit direction.
7171    fn support(&self, u: Vec3) -> f64 {
7172        let along = u.dot(self.axis);
7173        let across = u.sub(self.axis.scale(along)).length();
7174        u.dot(self.base) + meridian_most(&self.meridian, across, along)
7175    }
7176
7177    /// Is `y`'s preimage outside the tool's reach, or within half the margin
7178    /// of its edge, at every time of the motion? Then the tool's boundary is
7179    /// within half the margin of every preimage inside (straight out of the
7180    /// bound), and none is deeper than the margin. `normal`: the probe's face
7181    /// normal, across which a slide is also tried.
7182    fn never_inside(&self, screw: &Screw, y: Vec3, normal: Vec3, margin: f64) -> bool {
7183        let r = y.sub(screw.a);
7184        let z = r.dot(screw.e);
7185        let rho = r.sub(screw.e.scale(z)).length();
7186        let mut advances = vec![screw.advance(screw.t0), screw.advance(screw.t1)];
7187        if screw.c2 != 0.0 {
7188            let vertex = -screw.c / (2.0 * screw.c2);
7189            if vertex > screw.t0 && vertex < screw.t1 {
7190                advances.push(screw.advance(vertex));
7191            }
7192        }
7193        let low = advances.iter().copied().fold(f64::INFINITY, f64::min);
7194        let high = advances.iter().copied().fold(f64::NEG_INFINITY, f64::max);
7195        // Half the margin, less what rounding may have cost the coordinates
7196        // and bounds compared (a few ulps of the largest of them).
7197        let size = r.length() + low.abs().max(high.abs()) + self.base.length() + self.radial[1].abs() + self.axial[0].abs().max(self.axial[1].abs());
7198        let half = 0.5 * margin - 1e-13 * size;
7199        if half <= 0.0 {
7200            return false;
7201        }
7202        if z - high >= self.axial[1] - half || z - low <= self.axial[0] + half {
7203            return true;
7204        }
7205        if rho >= self.radial[1] - half || (self.radial[0] > 0.0 && rho <= self.radial[0] + half) {
7206            return true;
7207        }
7208        // A slide carries the preimage along its direction only. `u` is meant
7209        // across it, but whatever of `e` rounding leaves in it moves `u·r`
7210        // with the advance: take the least `u·r` reaches over the motion.
7211        if screw.omega == 0.0 {
7212            if let Ok(u) = normal.sub(screw.e.scale(normal.dot(screw.e))).normalized() {
7213                let drift = u.dot(screw.e);
7214                let least = u.dot(r) - (drift * low).max(drift * high);
7215                if least >= self.support(u) - half {
7216                    return true;
7217                }
7218            }
7219        }
7220        false
7221    }
7222}
7223
7224/// Refuse a sweep that covers points just outside its own faces.
7225///
7226/// `sliding`: faces the tool slides within all through the motion. A probe
7227/// just off one stays that near the tool the whole way, and the walk's step
7228/// is that distance: it stands a thousand times further off them (whatever
7229/// of the tool rides higher than that over such a face is still found).
7230fn check_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
7231    let (on, check) = (parallel_turn_one_pass_on(), parallel_turn_one_pass_check_on());
7232    if (on || check) && parallel_turn_one_pass(screw, split) {
7233        if !check {
7234            return Ok(());
7235        }
7236        let walked = walk_single_pass(screw, split, body, sliding);
7237        PARALLEL_TURN_CHECK.with(|cell| {
7238            let (n, bad) = cell.get();
7239            cell.set((n + 1, bad + u64::from(walked.is_err())));
7240        });
7241        return walked;
7242    }
7243    walk_single_pass(screw, split, body, sliding)
7244}
7245
7246/// `BREP_SWEEP_PARALLEL_TURN_ONE_PASS` (default on, `=0` walks): the one-pass check
7247/// answered in closed form for a solid of revolution turned (no advance)
7248/// about an axis parallel to its own, `D` from it, whose every section square
7249/// to the axes is one disc of radius `r(z) <= r_max < D`. A point's
7250/// distance from the turn's axis stays fixed; the disc at its height covers,
7251/// of the circle it runs on, one arc of half-angle at most `asin(r_max / D)`
7252/// centred on the tool's axis, and that arc moves round with the turn. The
7253/// point is inside over one interval of the turn unless the arc comes round
7254/// to it again: never while the turn is short of `2π − 2 asin(r_max / D)`.
7255/// The sampled walk is then not needed.
7256pub(crate) fn parallel_turn_one_pass_on() -> bool {
7257    crate::switch!("BREP_SWEEP_PARALLEL_TURN_ONE_PASS", true)
7258}
7259
7260/// `BREP_SWEEP_PARALLEL_TURN_ONE_PASS_CHECK` (default off): where the closed
7261/// form says one pass, the walk runs too and decides; the tally counts the
7262/// walks that refused ([`parallel_turn_one_pass_check_take`]).
7263fn parallel_turn_one_pass_check_on() -> bool {
7264    crate::switch!("BREP_SWEEP_PARALLEL_TURN_ONE_PASS_CHECK", false)
7265}
7266
7267thread_local! {
7268    static PARALLEL_TURN_CHECK: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
7269}
7270
7271/// (closed-form one-pass answers walked, walks that refused) on this thread
7272/// since the last call.
7273pub fn parallel_turn_one_pass_check_take() -> (u64, u64) {
7274    PARALLEL_TURN_CHECK.with(|cell| cell.replace((0, 0)))
7275}
7276
7277/// Whether the closed form above proves the sweep one pass.
7278fn parallel_turn_one_pass(screw: &Screw, split: &Split) -> bool {
7279    if screw.frame.is_some() || screw.turns.is_some() || screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 {
7280        return false;
7281    }
7282    let Shape::Revolved { origin, axis, meridian } = &split.shape else { return false };
7283    if axis.cross(screw.e).length() > 1e-12 {
7284        return false;
7285    }
7286    let apart = origin.sub(screw.a);
7287    let d = apart.sub(screw.e.scale(apart.dot(screw.e))).length();
7288    // Every section one disc: the outline less its pieces on the axis is one
7289    // run whose axial coordinate never turns back (lines; arcs without a
7290    // turning point inside), and its largest radius.
7291    // On the axis exactly: a wall any way off it is a bore, however thin.
7292    let on_axis = |p: [f64; 2]| p[0] == 0.0;
7293    let axial: Vec<bool> = meridian.iter().map(|piece| matches!(*piece, OutlinePiece::Line { from, to } if on_axis(from) && on_axis(to))).collect();
7294    let changes = (0..axial.len()).filter(|&k| axial[k] != axial[(k + 1) % axial.len()]).count();
7295    if changes != 2 {
7296        return false; // the pieces on the axis are not one run of them
7297    }
7298    let mut direction = 0i32;
7299    let mut r_max = 0.0f64;
7300    let mut agree = |sign: i32| -> bool {
7301        if sign == 0 {
7302            return true;
7303        }
7304        if direction == 0 {
7305            direction = sign;
7306        }
7307        direction == sign
7308    };
7309    for piece in meridian {
7310        match *piece {
7311            OutlinePiece::Line { from, to } => {
7312                if on_axis(from) && on_axis(to) {
7313                    continue;
7314                }
7315                if from[0] < -1e-12 || to[0] < -1e-12 {
7316                    return false;
7317                }
7318                r_max = r_max.max(from[0]).max(to[0]);
7319                let rise = to[1] - from[1];
7320                if !agree(if rise > 0.0 { 1 } else if rise < 0.0 { -1 } else { 0 }) {
7321                    return false;
7322                }
7323            }
7324            OutlinePiece::Arc { centre, radius, start, end } => {
7325                let (lo, hi) = (start.min(end), start.max(end));
7326                if !(hi > lo) || !(radius > 0.0) {
7327                    return false;
7328                }
7329                // Turning points of the axial coordinate (cos a = 0) strictly inside.
7330                let first = ((lo - FRAC_PI_2) / PI).floor() as i64 + 1;
7331                if FRAC_PI_2 + first as f64 * PI < hi - 1e-12 {
7332                    return false;
7333                }
7334                // Its radial reach: the ends, and a = 0 (mod 2π) inside.
7335                let reach = |a: f64| centre[0] + radius * a.cos();
7336                r_max = r_max.max(reach(start)).max(reach(end));
7337                if (lo / TAU).ceil() * TAU < hi {
7338                    r_max = r_max.max(centre[0] + radius);
7339                }
7340                if centre[0] - radius < -1e-12 && (lo..hi).contains(&PI) {
7341                    return false;
7342                }
7343                let mid = 0.5 * (start + end);
7344                let rise = radius * mid.cos() * (end - start).signum();
7345                if !agree(if rise > 0.0 { 1 } else if rise < 0.0 { -1 } else { 0 }) {
7346                    return false;
7347                }
7348            }
7349            _ => return false,
7350        }
7351    }
7352    if !(r_max > 0.0 && r_max < d * (1.0 - 1e-9)) {
7353        return false;
7354    }
7355    let turn = (screw.omega * (screw.t1 - screw.t0)).abs();
7356    turn + 2.0 * (r_max / d).asin() < TAU * (1.0 - 1e-9)
7357}
7358
7359fn walk_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
7360    let margin = 1e-9 * split.scale;
7361    let reach = ToolReach::of(screw, split);
7362    for face in body.shells.iter().flat_map(|s| &s.faces) {
7363        let step = if sliding.contains(&face.id) { 1e-3 * split.scale } else { 1e-6 * split.scale };
7364        let surface = &face.surface;
7365        // Probe inside the face: towards each corner of its loop from the
7366        // average of its corners (caps are convex in their parameters), and on
7367        // a grid for the four-sided walls.
7368        let mut corners: Vec<[f64; 2]> = Vec::new();
7369        for coedge in &face.loops[0].coedges {
7370            let domain = frag(coedge.pcurve.domain(), "domain")?;
7371            for k in 0..4 {
7372                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 4.0), "pcurve")?;
7373                corners.push([p.x, p.y]);
7374            }
7375        }
7376        let middle = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
7377        let middle = [middle[0] / corners.len() as f64, middle[1] / corners.len() as f64];
7378        let mut probes: Vec<[f64; 2]> = vec![middle];
7379        for c in &corners {
7380            for w in [0.25, 0.5, 0.75, 0.9, 0.99] {
7381                probes.push([middle[0] + (c[0] - middle[0]) * w, middle[1] + (c[1] - middle[1]) * w]);
7382            }
7383        }
7384        if surface.degree_v == 5 {
7385            let [u0, u1] = frag(surface.domain_u(), "domain")?;
7386            for i in 1..8 {
7387                for j in 1..64 {
7388                    probes.push([u0 + (u1 - u0) * i as f64 / 8.0, j as f64 / 64.0]);
7389                }
7390            }
7391        }
7392        let ([u0, u1], [v0, v1]) = (frag(surface.domain_u(), "domain")?, frag(surface.domain_v(), "domain")?);
7393        // Keep the probes inside the face's own loop (a face under a grazing
7394        // curve that dips is not convex in its parameters).
7395        let mut ring: Vec<[f64; 2]> = Vec::new();
7396        for coedge in &face.loops[0].coedges {
7397            let domain = frag(coedge.pcurve.domain(), "domain")?;
7398            for k in 0..32 {
7399                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 32.0), "pcurve")?;
7400                ring.push([p.x, p.y]);
7401            }
7402        }
7403        let (lo, hi) = ring.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), q| ([lo[0].min(q[0]), lo[1].min(q[1])], [hi[0].max(q[0]), hi[1].max(q[1])]));
7404        for i in 1..12 {
7405            for j in 1..12 {
7406                probes.push([lo[0] + (hi[0] - lo[0]) * i as f64 / 12.0, lo[1] + (hi[1] - lo[1]) * j as f64 / 12.0]);
7407            }
7408        }
7409        let inside = |q: [f64; 2]| -> bool {
7410            let mut crossings = 0;
7411            for k in 0..ring.len() {
7412                let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
7413                if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (q[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) {
7414                    crossings += 1;
7415                }
7416            }
7417            crossings % 2 == 1
7418        };
7419        for [u, v] in probes.into_iter().filter(|&q| inside(q)) {
7420            let p = frag(surface.evaluate(u, v), "probe")?;
7421            let (hu, hv) = (1e-6 * (u1 - u0), 1e-6 * (v1 - v0));
7422            // Derivatives, not raw differences: their cross product is
7423            // measured against an absolute zero.
7424            let (ua, ub, va, vb) = ((u - hu).max(u0), (u + hu).min(u1), (v - hv).max(v0), (v + hv).min(v1));
7425            let du = frag(surface.evaluate(ub, v), "probe")?.sub(frag(surface.evaluate(ua, v), "probe")?).scale(1.0 / (ub - ua));
7426            let dv = frag(surface.evaluate(u, vb), "probe")?.sub(frag(surface.evaluate(u, va), "probe")?).scale(1.0 / (vb - va));
7427            let Ok(n) = du.cross(dv).normalized() else { continue };
7428            let n = if face.same_sense { n } else { n.scale(-1.0) };
7429            if covered(screw, split, reach.as_ref(), p.add(n.scale(step)), n, margin)? {
7430                return Err(refuse("folds", format!("the sweep passes over a point twice (just outside its own face at {p:?}); not one pass")));
7431            }
7432        }
7433    }
7434    Ok(())
7435}
7436
7437
7438#[path = "solid_sweep_ring_fold.rs"]
7439mod ring_fold;
7440
7441#[path = "solid_sweep_ball_screw.rs"]
7442mod ball_screw;
7443
7444