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::{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    fn invert(&self, x: Vec3) -> [f64; 2] {
459        match *self {
460            Chart::Plane { origin, u, v } => {
461                let d = x.sub(origin);
462                [d.dot(u), d.dot(v)]
463            }
464            Chart::Revolution { origin, w, u1, u2, alpha, theta, spans_u, meridian } => {
465                let r = x.sub(origin);
466                let z = r.dot(w);
467                let rho = r.sub(w.scale(z)).length();
468                let mid = alpha + 0.5 * theta;
469                let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
470                let u = crate::circle_angle_to_parameter(spans_u, theta, psi - alpha);
471                let v = match meridian {
472                    MeridianChart::Line { m0, m1 } => {
473                        let (a, b) = (m1[0] - m0[0], m1[1] - m0[1]);
474                        ((rho - m0[0]) * a + (z - m0[1]) * b) / (a * a + b * b)
475                    }
476                    MeridianChart::Arc { centre, start, sweep, spans } => {
477                        let mid = start + 0.5 * sweep;
478                        let angle = mid + ((z - centre[1]).atan2(rho - centre[0]) - mid + PI).rem_euclid(TAU) - PI;
479                        crate::circle_angle_to_parameter(spans, sweep, angle - start)
480                    }
481                };
482                [u, v]
483            }
484        }
485    }
486}
487
488/// The spans `make_revolution` gives a sweep of `theta`.
489fn spans_of(surface_knots_u: &[f64]) -> usize {
490    (surface_knots_u.len() - 6) / 2 + 1
491}
492
493/// The tool's boundary split along K, in the tool's own frame.
494struct Split {
495    points: Vec<Vec3>,
496    curves: Vec<ToolCurve>,
497    caps: Vec<Cap>,
498    /// Flat ends that slide within their own plane all through the motion.
499    slides: Vec<SlideDisc>,
500    /// Cylinders that slide along their own generators all through it.
501    slide_sides: Vec<SlideSide>,
502    scale: f64,
503    shape: Shape,
504}
505
506/// A flat end about the tool's axis whose every point moves within the
507/// end's own plane (a turn about a parallel axis, a slide across the tool's
508/// axis): neither front nor back. What it sweeps is one face of the sweep in
509/// that plane, bounded by the rim's arcs beside back faces where the motion
510/// starts, its arcs beside front faces where it stops, and the paths of the
511/// points between them. `rim`: the rim's arcs counter-clockwise about the
512/// outward normal `u × v`, each with its direction of traversal.
513struct SlideDisc {
514    centre: Vec3,
515    u: Vec3,
516    v: Vec3,
517    rim: Vec<(usize, bool)>,
518}
519
520/// A cylinder about the tool's axis slid along that axis: every point moves
521/// along its own generator. What it sweeps is the cylinder from one rim where
522/// that rim's neighbour sits (back at the start, front at the end) to the
523/// other rim where its neighbour sits. `patches`: per stretch between two
524/// seam angles, (the angle it starts at, its sweep, the start rim's arc, the
525/// end rim's arc, the rim points at the start angle: start rim, end rim).
526struct SlideSide {
527    origin: Vec3,
528    w: Vec3,
529    patches: Vec<(f64, f64, usize, usize, [usize; 2])>,
530}
531
532/// What the membership oracle measures.
533enum Shape {
534    Planes(Vec<(Vec3, f64)>),
535    Revolved { origin: Vec3, axis: Vec3, meridian: Vec<OutlinePiece> },
536}
537
538impl Split {
539    /// Signed distance to the tool in its own frame (negative inside).
540    fn distance(&self, x: Vec3) -> f64 {
541        match &self.shape {
542            Shape::Planes(planes) => planes.iter().map(|(n, d)| n.dot(x) - d).fold(f64::NEG_INFINITY, f64::max),
543            Shape::Revolved { origin, axis, meridian } => {
544                let r = x.sub(*origin);
545                let z = r.dot(*axis);
546                let rho = r.sub(axis.scale(z)).length();
547                outline_signed_distance(meridian, [rho, z])
548            }
549        }
550    }
551
552    /// K: each curve with a front cap on one side and a back cap on the
553    /// other, with the direction in which the back cap runs along it (the back
554    /// on its left seen from outside).
555    fn grazing(&self) -> Result<Vec<(usize, bool)>, KernelRefusal> {
556        let mut uses: HashMap<usize, Vec<(bool, bool)>> = HashMap::new();
557        for cap in &self.caps {
558            for &(curve, forward, _) in &cap.coedges {
559                uses.entry(curve).or_default().push((forward, cap.front));
560            }
561        }
562        let mut grazing = Vec::new();
563        for (curve, list) in uses {
564            if self.curves[curve].degenerate {
565                continue;
566            }
567            // A sliding end's rim carries no wall: it moves within the end's plane.
568            if list.len() == 1
569                && (self.slides.iter().any(|slide| slide.rim.iter().any(|&(c, _)| c == curve))
570                    || self.slide_sides.iter().any(|side| side.patches.iter().any(|patch| patch.2 == curve || patch.3 == curve)))
571            {
572                continue;
573            }
574            match list.as_slice() {
575                [(fa, front_a), (fb, front_b)] => {
576                    if fa == fb {
577                        return Err(refuse("split_topology", "two caps run one boundary curve the same way".into()));
578                    }
579                    if front_a != front_b {
580                        grazing.push((curve, if *front_a { *fb } else { *fa }));
581                    }
582                }
583                _ => return Err(refuse("split_topology", format!("a boundary curve is used {} times", list.len()))),
584            }
585        }
586        grazing.sort_unstable();
587        Ok(grazing)
588    }
589}
590
591fn uv_line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
592    frag(make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)), "pcurve")
593}
594
595/// The plane through `origin` with in-plane axes u, v (u × v outward), as a
596/// patch covering `points`; and the map to its parameters.
597fn plane_patch(origin: Vec3, u: Vec3, v: Vec3, points: &[Vec3]) -> Result<NurbsSurface, KernelRefusal> {
598    let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
599    for p in points {
600        let q = [p.sub(origin).dot(u), p.sub(origin).dot(v)];
601        for k in 0..2 {
602            lo[k] = lo[k].min(q[k]);
603            hi[k] = hi[k].max(q[k]);
604        }
605    }
606    let at = |s: f64, t: f64| Vec4::from_point(origin.add(u.scale(s)).add(v.scale(t)), 1.0);
607    frag(
608        NurbsSurface::new(
609            1,
610            1,
611            vec![lo[0], lo[0], hi[0], hi[0]],
612            vec![lo[1], lo[1], hi[1], hi[1]],
613            vec![vec![at(lo[0], lo[1]), at(lo[0], hi[1])], vec![at(hi[0], lo[1]), at(hi[0], hi[1])]],
614        ),
615        "plane_surface",
616    )
617}
618
619/// A curve lying in the plane (origin, u, v), as a pcurve of that plane:
620/// its control points projected, weights kept (exact, the map is affine).
621fn plane_pcurve(origin: Vec3, u: Vec3, v: Vec3, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
622    let mut points = Vec::with_capacity(curve.control_points.len());
623    for p in &curve.control_points {
624        let x = frag(p.point(), "control_point")?.sub(origin);
625        points.push(Vec4::from_point(Vec3::new(x.dot(u), x.dot(v), 0.0), p.w));
626    }
627    let pcurve = frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "plane_pcurve")?;
628    if forward { Ok(pcurve) } else { frag(pcurve.reversed(), "plane_pcurve") }
629}
630
631fn split_polyhedron(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<Split, KernelRefusal> {
632    if vertices.len() < 4 || faces.len() < 4 {
633        return Err(input("polyhedron", "a polyhedron needs at least four corners and four faces".into()));
634    }
635    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);
636    let scale = vertices.iter().map(|p| p.sub(centroid).length()).fold(0.0f64, f64::max).max(1e-300);
637    let tolerance = 1e-12 * scale.max(screw.a.sub(centroid).length());
638    let mut loops: Vec<Vec<usize>> = Vec::with_capacity(faces.len());
639    let mut planes = Vec::with_capacity(faces.len());
640    for face in faces {
641        if face.len() < 3 || face.iter().any(|&i| i >= vertices.len()) {
642            return Err(input("face", "a face needs three or more existing corners".into()));
643        }
644        let mut normal = Vec3::new(0.0, 0.0, 0.0);
645        for k in 0..face.len() {
646            let (p, q) = (vertices[face[k]], vertices[face[(k + 1) % face.len()]]);
647            normal = normal.add(p.sub(centroid).cross(q.sub(centroid)));
648        }
649        let mut normal = normal.normalized().map_err(|_| input("face", "a face has no area".into()))?;
650        let mut face = face.clone();
651        if normal.dot(vertices[face[0]].sub(centroid)) < 0.0 {
652            normal = normal.scale(-1.0);
653            face.reverse();
654        }
655        let offset = normal.dot(vertices[face[0]]);
656        for p in vertices {
657            if normal.dot(*p) - offset > 1e-9 * scale {
658                return Err(refuse("not_convex", "the polyhedron is not convex".into()));
659            }
660        }
661        for &i in &face {
662            if (normal.dot(vertices[i]) - offset).abs() > 1e-9 * scale {
663                return Err(input("face", "a face's corners are not in one plane".into()));
664            }
665        }
666        loops.push(face);
667        planes.push((normal, offset));
668    }
669    // Each face's grazing value (affine along the face).
670    let g = |face: usize, x: Vec3| -> f64 {
671        let value = screw.velocity(x).dot(planes[face].0);
672        if value.abs() <= tolerance * screw.velocity(x).length().max(1.0) { 0.0 } else { value }
673    };
674    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
675    for (index, face) in loops.iter().enumerate() {
676        for k in 0..face.len() {
677            owner.insert((face[k], face[(k + 1) % face.len()]), index);
678        }
679    }
680    for &(i, j) in owner.keys() {
681        if !owner.contains_key(&(j, i)) {
682            return Err(input("closed", "the polyhedron's faces do not close".into()));
683        }
684    }
685    // Split points on edges: where either neighbour's grazing value crosses zero.
686    let mut points: Vec<Vec3> = vertices.to_vec();
687    let mut edge_splits: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
688    let mut keys: Vec<(usize, usize)> = owner.keys().copied().filter(|&(i, j)| i < j).collect();
689    keys.sort_unstable();
690    for (i, j) in keys {
691        let mut params: Vec<f64> = Vec::new();
692        for f in [owner[&(i, j)], owner[&(j, i)]] {
693            let (gi, gj) = (g(f, vertices[i]), g(f, vertices[j]));
694            if gi * gj < 0.0 {
695                params.push(gi / (gi - gj));
696            }
697        }
698        params.sort_by(|a, b| a.total_cmp(b));
699        params.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
700        let mut list = Vec::new();
701        for s in params {
702            points.push(vertices[i].add(vertices[j].sub(vertices[i]).scale(s)));
703            list.push(points.len() - 1);
704        }
705        edge_splits.insert((i, j), list);
706    }
707    let splits_along = |i: usize, j: usize| -> Vec<usize> {
708        if i < j {
709            edge_splits[&(i, j)].clone()
710        } else {
711            edge_splits[&(j, i)].iter().rev().copied().collect()
712        }
713    };
714    // Sub-faces as point rings, counter-clockwise from outside.
715    let mut rings: Vec<(Vec<usize>, usize, bool)> = Vec::new();
716    for (index, face) in loops.iter().enumerate() {
717        let mut ring: Vec<usize> = Vec::new();
718        for k in 0..face.len() {
719            ring.push(face[k]);
720            ring.extend(splits_along(face[k], face[(k + 1) % face.len()]));
721        }
722        let values: Vec<f64> = ring.iter().map(|&p| g(index, points[p])).collect();
723        let positive = values.iter().any(|&v| v > 0.0);
724        let negative = values.iter().any(|&v| v < 0.0);
725        if !positive && !negative {
726            return Err(refuse("face_in_own_plane", format!("face {index} moves in its own plane (its sweep is flat)")));
727        }
728        if !(positive && negative) {
729            rings.push((ring, index, positive));
730            continue;
731        }
732        let zeros: Vec<usize> = (0..ring.len()).filter(|&k| values[k] == 0.0).collect();
733        if zeros.len() != 2 {
734            return Err(refuse("grazing_split", format!("face {index} meets its grazing line {} times", zeros.len())));
735        }
736        let (za, zb) = (zeros[0], zeros[1]);
737        if za + 1 == zb || (zb + 1) % ring.len() == za {
738            return Err(refuse("grazing_split", format!("face {index} is split along one of its own edges")));
739        }
740        let first: Vec<usize> = (za..=zb).map(|k| ring[k]).collect();
741        let second: Vec<usize> = (zb..ring.len()).chain(0..=za).map(|k| ring[k]).collect();
742        let first_front = values[za + 1] > 0.0;
743        rings.push((first, index, first_front));
744        rings.push((second, index, !first_front));
745    }
746    // A growing rise moves the grazing lines: every sub-face must keep its side
747    // at both ends of the motion.
748    if screw.c2 != 0.0 {
749        for (ring, face, front) in &rings {
750            for &p in ring {
751                for t in [screw.t0, screw.t1] {
752                    let value = screw.velocity_at(t, points[p]).dot(planes[*face].0);
753                    let slack = tolerance * screw.velocity_at(t, points[p]).length().max(1.0);
754                    if (*front && value < -slack) || (!*front && value > slack) {
755                        return Err(refuse("rising_sides", format!("face {face} changes side as the rise grows")));
756                    }
757                }
758            }
759        }
760    }
761    // Curves: one straight segment per point pair.
762    let mut curves: Vec<ToolCurve> = Vec::new();
763    let mut by_pair: HashMap<(usize, usize), usize> = HashMap::new();
764    let mut caps = Vec::with_capacity(rings.len());
765    for (ring, face, front) in rings {
766        let normal = planes[face].0;
767        let origin = points[ring[0]];
768        let u = frag(points[ring[1]].sub(origin).normalized(), "plane_axis")?;
769        let v = normal.cross(u);
770        let corners: Vec<Vec3> = ring.iter().map(|&p| points[p]).collect();
771        let surface = plane_patch(origin, u, v, &corners)?;
772        let mut coedges = Vec::with_capacity(ring.len());
773        for k in 0..ring.len() {
774            let (p, q) = (ring[k], ring[(k + 1) % ring.len()]);
775            let key = (p.min(q), p.max(q));
776            let index = match by_pair.get(&key) {
777                Some(&index) => index,
778                None => {
779                    curves.push(ToolCurve {
780                        curve: frag(make_line(points[key.0], points[key.1]), "line")?,
781                        start: key.0,
782                        end: key.1,
783                        degenerate: false,
784                        samples: None,
785                    });
786                    by_pair.insert(key, curves.len() - 1);
787                    curves.len() - 1
788                }
789            };
790            let forward = p == key.0;
791            coedges.push((index, forward, plane_pcurve(origin, u, v, &curves[index].curve, forward)?));
792        }
793        caps.push(Cap { surface, front, coedges, chart: Some(Chart::Plane { origin, u, v }) });
794    }
795    Ok(Split { points, curves, caps, slides: Vec::new(), slide_sides: Vec::new(), scale, shape: Shape::Planes(planes) })
796}
797
798/// The grazing value `A cos ψ + B sin ψ + C` of a face of revolution at one
799/// meridian point, from three samples.
800pub fn harmonic(g: impl Fn(f64) -> f64) -> (f64, f64, f64) {
801    let (g0, g90, g180) = (g(0.0), g(0.5 * PI), g(PI));
802    let c = 0.5 * (g0 + g180);
803    (0.5 * (g0 - g180), g90 - c, c)
804}
805
806pub fn piece_point(piece: &OutlinePiece, s: f64) -> [f64; 2] {
807    match *piece {
808        OutlinePiece::Line { from, to } => [from[0] + (to[0] - from[0]) * s, from[1] + (to[1] - from[1]) * s],
809        OutlinePiece::Arc { centre, radius, start, end } => {
810            let angle = start + (end - start) * s;
811            [centre[0] + radius * angle.cos(), centre[1] + radius * angle.sin()]
812        }
813        OutlinePiece::Ellipse { centre, semi, rotation, start, end } => crate::solid_sweep::ellipse_point(centre, semi, rotation, start + (end - start) * s),
814    }
815}
816
817/// The whole sweep takes meridians of lines and circular arcs; an elliptic
818/// piece is swept only by [`crate::sweep_solid_within`]'s region engine.
819fn refuse_elliptic(meridian: &[OutlinePiece]) -> Result<(), KernelRefusal> {
820    if meridian.iter().any(|piece| matches!(piece, OutlinePiece::Ellipse { .. })) {
821        return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into()));
822    }
823    Ok(())
824}
825
826fn split_revolved(
827    screw: &Screw,
828    origin: Vec3,
829    axis: Vec3,
830    radial: Vec3,
831    meridian: &[OutlinePiece],
832) -> Result<Split, KernelRefusal> {
833    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
834    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
835    let u2 = w.cross(u1);
836    refuse_elliptic(meridian)?;
837    if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian {
838        if ((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius {
839            return split_torus(screw, origin, w, u1, u2, *centre, *radius, meridian);
840        }
841    }
842    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()));
843    let scale = meridian
844        .iter()
845        .flat_map(|p| [piece_point(p, 0.0), piece_point(p, 1.0)])
846        .map(|q| q[0].abs().max(q[1].abs()))
847        .fold(0.0f64, f64::max)
848        .max(1e-300);
849    let on_axis = |q: [f64; 2]| q[0].abs() <= 1e-12 * scale;
850    // Orientation of the meridian outline (+1 counter-clockwise in (ρ, z)).
851    let mut area = 0.0;
852    for piece in meridian {
853        for k in 0..16 {
854            let (p, q) = (piece_point(piece, k as f64 / 16.0), piece_point(piece, (k + 1) as f64 / 16.0));
855            area += p[0] * q[1] - q[0] * p[1];
856        }
857    }
858    // Work counter-clockwise in (ρ, z): a revolved patch's u × v is then outward.
859    let reversed_meridian: Vec<OutlinePiece>;
860    let meridian: &[OutlinePiece] = if area > 0.0 {
861        meridian
862    } else {
863        reversed_meridian = meridian
864            .iter()
865            .rev()
866            .map(|piece| match *piece {
867                OutlinePiece::Line { from, to } => OutlinePiece::Line { from: to, to: from },
868                OutlinePiece::Arc { centre, radius, start, end } => OutlinePiece::Arc { centre, radius, start: end, end: start },
869                OutlinePiece::Ellipse { centre, semi, rotation, start, end } => OutlinePiece::Ellipse { centre, semi, rotation, start: end, end: start },
870            })
871            .collect();
872        &reversed_meridian
873    };
874    let ccw = true;
875    // Outward normal in (ρ, z) of a piece at s.
876    let normal = |piece: &OutlinePiece, s: f64| -> [f64; 2] {
877        let (p, q) = (piece_point(piece, (s - 1e-6).max(0.0)), piece_point(piece, (s + 1e-6).min(1.0)));
878        let (dx, dz) = (q[0] - p[0], q[1] - p[1]);
879        let length = dx.hypot(dz);
880        if ccw { [dz / length, -dx / length] } else { [-dz / length, dx / length] }
881    };
882    let g = |piece: &OutlinePiece, s: f64, psi: f64| -> f64 {
883        let m = piece_point(piece, s);
884        let n = normal(piece, s);
885        let x = at(m[0], m[1], psi);
886        let normal = w.scale(n[1]).add(u1.scale(n[0] * psi.cos())).add(u2.scale(n[0] * psi.sin()));
887        screw.velocity(x).dot(normal)
888    };
889    // The faces: pieces off the axis.
890    let faces: Vec<usize> = (0..meridian.len())
891        .filter(|&i| !(matches!(meridian[i], OutlinePiece::Line { .. }) && on_axis(piece_point(&meridian[i], 0.0)) && on_axis(piece_point(&meridian[i], 1.0))))
892        .collect();
893    // Each face's split angles (where K meets it, constant along it), or its
894    // great circle.
895    enum Kind {
896        /// A cylinder or cone (or a flat end) split along generators at these
897        /// angles (empty: one side).
898        Ruled(Vec<f64>),
899        /// A cylinder or cone whose two grazing curves move round it along
900        /// the meridian (`branches`), from rim to rim.
901        Moving,
902        /// A hemisphere from a pole to an equator rim, split by the great
903        /// circle square to its centre's velocity.
904        Sphere { centre: Vec3, pole_at_start: bool },
905        /// A whole ball (a half circle from pole to pole), split by that
906        /// great circle into two hemispheres.
907        Ball { centre: Vec3, radius: f64 },
908        /// A rounded corner (a zone of a torus: an arc whose centre is off the
909        /// axis), crossed by K as a graph v(ψ) of the tube angle for ψ from
910        /// `psi_a` to `psi_b`, entering and leaving at the same rim (the end
911        /// rim when `at_end`).
912        TorusZone { psi_a: f64, psi_b: f64, at_end: bool },
913        /// A flat end that slides within its own plane (`SlideDisc`).
914        Slide,
915        /// A cylinder slid along its own axis (`SlideSide`).
916        SlideSide,
917        /// A rounded corner split along meridian arcs at these angles (the
918        /// grazing curve keeps its angle about the axis: a turn about a
919        /// parallel axis, a slide across the tool's axis).
920        RuledArc(Vec<f64>),
921    }
922    // The two grazing angles of a cylinder or cone at s, the lower and the
923    // upper, unwrapped against s = 0: the front lies between them.
924    let branches = |piece: &OutlinePiece, s: f64| -> Option<(f64, f64)> {
925        let reference = {
926            let (a, b, _) = harmonic(|psi| g(piece, 0.0, psi));
927            b.atan2(a)
928        };
929        let (a, b, c) = harmonic(|psi| g(piece, s, psi));
930        let r = a.hypot(b);
931        if !(c.abs() < r * (1.0 - 1e-9)) {
932            return None;
933        }
934        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
935        let spread = (-c / r).acos();
936        Some((base - spread, base + spread))
937    };
938    let mut kinds: Vec<Kind> = Vec::with_capacity(faces.len());
939    for &i in &faces {
940        let piece = &meridian[i];
941        match *piece {
942            OutlinePiece::Ellipse { .. } => return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into())),
943            OutlinePiece::Line { .. } => {
944                let roots = |s: f64| -> Vec<f64> {
945                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
946                    let r = a.hypot(b);
947                    if c.abs() >= r * (1.0 - 1e-12) {
948                        return Vec::new();
949                    }
950                    let base = b.atan2(a);
951                    let spread = (-c / r).acos();
952                    let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
953                    list.sort_by(|x, y| x.total_cmp(y));
954                    list
955                };
956                // Where the grazing value vanishes all round (a rim through
957                // the motion's axis turning in its own plane) it names no
958                // angle; read the roots where it does not.
959                let alive = |s: f64| {
960                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
961                    a.hypot(b).max(c.abs()) > 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound())
962                };
963                let readings: Vec<Vec<f64>> = [0.0, 0.5, 1.0].into_iter().filter(|&t| alive(t)).map(roots).collect();
964                if readings.is_empty() {
965                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
966                    let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
967                    if flat && (on_axis(m0) || on_axis(m1)) {
968                        kinds.push(Kind::Slide);
969                        continue;
970                    }
971                    let upright = (m0[0] - m1[0]).abs() <= 1e-12 * scale;
972                    if upright && screw.omega == 0.0 && screw.turns.is_none() && screw.frame.is_none() {
973                        kinds.push(Kind::SlideSide);
974                        continue;
975                    }
976                    return Err(refuse("revolved_grazing", format!("meridian piece {i} grazes all over")));
977                }
978                let r0 = readings[0].clone();
979                let still = readings.iter().all(|r| r.len() == r0.len() && r.iter().zip(&r0).all(|(x, y)| (x - y).abs() < 1e-10));
980                if still {
981                    // A face wholly on one side that is not a disc about the
982                    // axis (a cone to its point, an annulus, a whole side):
983                    // two halves of the same side, seamed at 0 and π.
984                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
985                    let disc = (m0[1] - m1[1]).abs() <= 1e-12 * scale && (on_axis(m0) || on_axis(m1));
986                    kinds.push(Kind::Ruled(if r0.is_empty() && !disc { vec![0.0, PI] } else { r0 }));
987                    continue;
988                }
989                let mut previous: Option<(f64, f64)> = None;
990                for k in 0..=64 {
991                    let Some(pair) = branches(piece, k as f64 / 64.0) else {
992                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} do not run rim to rim")));
993                    };
994                    if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
995                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} turn too fast")));
996                    }
997                    previous = Some(pair);
998                }
999                kinds.push(Kind::Moving);
1000            }
1001            OutlinePiece::Arc { centre, radius, start, end } => {
1002                let (p0, p1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1003                let span = (end - start).abs();
1004                let centre_on_axis = on_axis(centre);
1005                let pole_at_start = on_axis(p0);
1006                let equator = |p: [f64; 2]| (p[1] - centre[1]).abs() <= 1e-12 * scale && (p[0] - radius).abs() <= 1e-12 * scale;
1007                if centre_on_axis && (span - PI).abs() < 1e-12 && pole_at_start && on_axis(p1) {
1008                    kinds.push(Kind::Ball { centre: origin.add(w.scale(centre[1])), radius });
1009                    continue;
1010                }
1011                if centre[0] > radius * (1.0 + 1e-9) && end > start && span <= PI + 1e-12 {
1012                    let at_rim = |v: f64| [centre[0] + radius * v.cos(), centre[1] + radius * v.sin()];
1013                    let g_tube = |psi: f64, v: f64| -> f64 {
1014                        let m = at_rim(v);
1015                        let x = at(m[0], m[1], psi);
1016                        let normal = w.scale(v.sin()).add(u1.scale(v.cos() * psi.cos())).add(u2.scale(v.cos() * psi.sin()));
1017                        screw.velocity(x).dot(normal)
1018                    };
1019                    // K at the same angles about the axis all along the arc?
1020                    {
1021                        let roots_at = |v: f64| -> Option<Vec<f64>> {
1022                            let (a, b, c) = harmonic(|psi| g_tube(psi, v));
1023                            let r = a.hypot(b);
1024                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1025                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1026                                return None;
1027                            }
1028                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1029                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1030                            list.sort_by(|x, y| x.total_cmp(y));
1031                            Some(list)
1032                        };
1033                        let readings: Vec<Option<Vec<f64>>> = [0.25, 0.5, 0.75].into_iter().map(|t| roots_at(start + (end - start) * t)).collect();
1034                        if let [Some(r0), Some(r1), Some(r2)] = readings.as_slice() {
1035                            if r0.iter().zip(r1).chain(r0.iter().zip(r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1036                                kinds.push(Kind::RuledArc(r0.clone()));
1037                                continue;
1038                            }
1039                        }
1040                    }
1041                    if span >= PI {
1042                        return Err(refuse("revolved_arc", format!("meridian piece {i}: a half-round rim is swept only where its grazing curves keep their angle")));
1043                    }
1044                    let in_zone = |psi: f64| -> Result<Option<f64>, KernelRefusal> {
1045                        let (a, b, c) = harmonic(|v| g_tube(psi, v));
1046                        let r = a.hypot(b);
1047                        if !(c.abs() < r) {
1048                            return Ok(None);
1049                        }
1050                        let base = b.atan2(a);
1051                        let spread = (-c / r).acos();
1052                        let inside: Vec<f64> = [base - spread, base + spread]
1053                            .into_iter()
1054                            .map(|v| start + (v - start).rem_euclid(TAU))
1055                            .filter(|&v| v <= end)
1056                            .collect();
1057                        match inside.as_slice() {
1058                            [] => Ok(None),
1059                            [v] => Ok(Some(*v)),
1060                            _ => Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner twice at one angle"))),
1061                        }
1062                    };
1063                    let count = 720;
1064                    let has: Vec<bool> = (0..count).map(|k| in_zone(TAU * k as f64 / count as f64).map(|r| r.is_some())).collect::<Result<_, _>>()?;
1065                    let rises: Vec<usize> = (0..count).filter(|&k| has[k] && !has[(k + count - 1) % count]).collect();
1066                    let falls: Vec<usize> = (0..count).filter(|&k| !has[k] && has[(k + count - 1) % count]).collect();
1067                    let ([rise], [fall]) = (rises.as_slice(), falls.as_slice()) else {
1068                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve does not cross the rounded corner once")));
1069                    };
1070                    // The crossing's ends: roots of the grazing value along the rim it meets.
1071                    let estimate = |k: usize| TAU * (k as f64 - 0.5) / count as f64;
1072                    let (ea, eb) = (estimate(*rise), estimate(*fall));
1073                    let sample = |k: usize| TAU * (k % count) as f64 / count as f64;
1074                    let probe_v = in_zone(sample(*rise))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1075                    let at_end = (probe_v - end).abs() < (probe_v - start).abs();
1076                    let rim_v = if at_end { end } else { start };
1077                    let (a, b, c) = harmonic(|psi| g_tube(psi, rim_v));
1078                    let r = a.hypot(b);
1079                    let base = b.atan2(a);
1080                    let spread = (-c / r).acos();
1081                    let roots = [base - spread, base + spread];
1082                    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");
1083                    let (psi_a, psi_b) = (nearest(ea).rem_euclid(TAU), nearest(eb).rem_euclid(TAU));
1084                    let psi_b = if psi_b <= psi_a { psi_b + TAU } else { psi_b };
1085                    let leave_v = in_zone(sample(*fall + count - 1))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1086                    if ((leave_v - end).abs() < (leave_v - start).abs()) != at_end {
1087                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner from rim to rim")));
1088                    }
1089                    kinds.push(Kind::TorusZone { psi_a, psi_b, at_end });
1090                    continue;
1091                }
1092                if !(centre_on_axis && (span - 0.5 * PI).abs() < 1e-12 && (pole_at_start && equator(p1) || on_axis(p1) && equator(p0))) {
1093                    // A cap of a sphere about the axis, from its pole to a rim
1094                    // short of (or past) the equator: swept where its grazing
1095                    // curves keep their angle about the axis (meridian arcs
1096                    // through the pole).
1097                    if centre_on_axis && end > start && span < PI && (pole_at_start != on_axis(p1)) {
1098                        let roots_at = |s: f64| -> Option<Vec<f64>> {
1099                            let (a, b, c) = harmonic(|psi| g(piece, s, psi));
1100                            let r = a.hypot(b);
1101                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1102                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1103                                return None;
1104                            }
1105                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1106                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1107                            list.sort_by(|x, y| x.total_cmp(y));
1108                            Some(list)
1109                        };
1110                        if let [Some(r0), Some(r1), Some(r2)] = [0.25, 0.5, 0.75].map(roots_at) {
1111                            if r0.iter().zip(&r1).chain(r0.iter().zip(&r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1112                                kinds.push(Kind::RuledArc(r0));
1113                                continue;
1114                            }
1115                        }
1116                    }
1117                    return Err(refuse("revolved_arc", format!("meridian piece {i}: only a quarter circle from a pole to an equator is swept here")));
1118                }
1119                kinds.push(Kind::Sphere { centre: origin.add(w.scale(centre[1])), pole_at_start });
1120            }
1121        }
1122    }
1123    // Rims: junctions off the axis, with the angles they are split at.
1124    let count = meridian.len();
1125    let junction = |k: usize| piece_point(&meridian[k], 1.0); // between piece k and k + 1
1126    let face_of = |piece: usize| faces.iter().position(|&f| f == piece);
1127    let mut rim_angles: HashMap<usize, Vec<f64>> = HashMap::new();
1128    for k in 0..count {
1129        if on_axis(junction(k)) {
1130            continue;
1131        }
1132        let mut angles: Vec<f64> = Vec::new();
1133        for (piece, s_end) in [(k, 1.0), ((k + 1) % count, 0.0)] {
1134            let Some(f) = face_of(piece) else { continue };
1135            match &kinds[f] {
1136                Kind::Ruled(roots) | Kind::RuledArc(roots) => angles.extend(roots.iter().copied()),
1137                Kind::Ball { .. } | Kind::Slide => {}
1138                Kind::SlideSide => angles.extend([0.0, PI]),
1139                Kind::TorusZone { psi_a, psi_b, .. } => angles.extend([psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)]),
1140                Kind::Moving => {
1141                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1142                    angles.extend([lower.rem_euclid(TAU), upper.rem_euclid(TAU)]);
1143                }
1144                Kind::Sphere { centre, .. } => {
1145                    let d = screw.velocity(*centre).cross(w);
1146                    let base = d.dot(u2).atan2(d.dot(u1)).rem_euclid(TAU);
1147                    angles.extend([base, (base + PI).rem_euclid(TAU)]);
1148                }
1149            }
1150        }
1151        angles.sort_by(|a, b| a.total_cmp(b));
1152        let mut merged: Vec<f64> = Vec::new();
1153        for a in angles {
1154            if merged.last().is_some_and(|&b| (a - b).abs() < 1e-9) || merged.first().is_some_and(|&b| (b + TAU - a).abs() < 1e-9) {
1155                continue;
1156            }
1157            merged.push(a);
1158        }
1159        rim_angles.insert(k, merged);
1160    }
1161    // Every face's own split angles must be its rims' (one arc per patch side).
1162    for (f, &piece) in faces.iter().enumerate() {
1163        for (k, s_end) in [((piece + count - 1) % count, 0.0), (piece, 1.0)] {
1164            let own: Vec<f64> = match &kinds[f] {
1165                Kind::Ruled(roots) | Kind::RuledArc(roots) => roots.clone(),
1166                Kind::Moving => {
1167                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1168                    let mut list = vec![lower.rem_euclid(TAU), upper.rem_euclid(TAU)];
1169                    list.sort_by(|a, b| a.total_cmp(b));
1170                    list
1171                }
1172                Kind::TorusZone { psi_a, psi_b, .. } => {
1173                    let mut list = vec![psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)];
1174                    list.sort_by(|a, b| a.total_cmp(b));
1175                    list
1176                }
1177                Kind::Sphere { .. } | Kind::Ball { .. } | Kind::Slide => continue,
1178                Kind::SlideSide => vec![0.0, PI],
1179            };
1180            if let Some(angles) = rim_angles.get(&k) {
1181                if own.is_empty() {
1182                    continue;
1183                }
1184                if angles.len() != own.len() || angles.iter().zip(&own).any(|(a, b)| (a - b).abs() > 1e-9) {
1185                    return Err(refuse("revolved_rims", format!("meridian piece {piece} splits at other angles than its rim")));
1186                }
1187            }
1188        }
1189    }
1190    let mut points: Vec<Vec3> = Vec::new();
1191    let mut curves: Vec<ToolCurve> = Vec::new();
1192    let mut caps: Vec<Cap> = Vec::new();
1193    let mut slides: Vec<SlideDisc> = Vec::new();
1194    let mut slide_sides: Vec<SlideSide> = Vec::new();
1195    // Rim points and arcs: arc j of rim k runs from angle j to angle j + 1.
1196    let mut rim_points: HashMap<(usize, usize), usize> = HashMap::new();
1197    let mut rim_arcs: HashMap<(usize, usize), usize> = HashMap::new();
1198    let mut rim_keys: Vec<usize> = rim_angles.keys().copied().collect();
1199    rim_keys.sort_unstable();
1200    for &k in &rim_keys {
1201        let q = junction(k);
1202        let angles = rim_angles[&k].clone();
1203        let angles = if angles.is_empty() { vec![0.0] } else { angles };
1204        for (j, &a) in angles.iter().enumerate() {
1205            points.push(at(q[0], q[1], a));
1206            rim_points.insert((k, j), points.len() - 1);
1207        }
1208        for j in 0..angles.len() {
1209            let a = angles[j];
1210            let b = if j + 1 < angles.len() { angles[j + 1] } else { angles[0] + TAU };
1211            let base = at(q[0], q[1], a);
1212            let surface = frag(make_revolution(origin, w, &frag(make_line(base, base.add(w)), "line")?, b - a), "rim")?;
1213            curves.push(ToolCurve {
1214                curve: frag(surface.iso_curve_v(0.0), "rim_arc")?,
1215                start: rim_points[&(k, j)],
1216                end: rim_points[&(k, (j + 1) % angles.len())],
1217                degenerate: false,
1218                samples: Some((0..=LOFT_SAMPLES).map(|i| at(q[0], q[1], a + (b - a) * i as f64 / LOFT_SAMPLES as f64)).collect()),
1219            });
1220            rim_arcs.insert((k, j), curves.len() - 1);
1221        }
1222        rim_angles.insert(k, angles);
1223    }
1224    let arc_index = |k: usize, angle: f64| -> Result<usize, KernelRefusal> {
1225        rim_angles[&k]
1226            .iter()
1227            .position(|&a| ((a - angle).rem_euclid(TAU)).min((angle - a).rem_euclid(TAU)) < 1e-9)
1228            .ok_or_else(|| refuse("revolved_rims", "a patch corner is not on its rim's split".into()))
1229    };
1230    let sign_at = |piece: &OutlinePiece, psi: f64| g(piece, 0.5, psi) > 0.0;
1231    for (f, &piece_index) in faces.iter().enumerate() {
1232        let piece = &meridian[piece_index];
1233        let below = (piece_index + count - 1) % count; // rim at the piece's start
1234        let above = piece_index; // rim at its end
1235        let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1236        match &kinds[f] {
1237            Kind::SlideSide => {
1238                if on_axis(m0) || on_axis(m1) {
1239                    return Err(refuse("revolved_grazing", format!("meridian piece {piece_index} grazes all over")));
1240                }
1241                let seams = [0.0, PI];
1242                let mut patches = Vec::with_capacity(2);
1243                for j in 0..2 {
1244                    let (alpha, theta) = (seams[j], PI);
1245                    let (ib, ia) = (arc_index(below, alpha)?, arc_index(above, alpha)?);
1246                    patches.push((alpha, theta, rim_arcs[&(below, ib)], rim_arcs[&(above, ia)], [rim_points[&(below, ib)], rim_points[&(above, ia)]]));
1247                }
1248                slide_sides.push(SlideSide { origin, w, patches });
1249            }
1250            Kind::RuledArc(roots) => {
1251                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1252                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1253                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1254                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1255                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1256                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1257                    let from = tube_point(psi, start);
1258                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1259                    frag(surface.iso_curve_v(0.0), "tube")
1260                };
1261                // A cap to its pole: the meridian arcs start (or end) there,
1262                // and each patch has a pole in place of a rim arc.
1263                let apex = if on_axis(m0) || on_axis(m1) {
1264                    let m = if on_axis(m0) { m0 } else { m1 };
1265                    points.push(at(0.0, m[1], 0.0));
1266                    Some(points.len() - 1)
1267                } else {
1268                    None
1269                };
1270                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1271                    match (on, apex) {
1272                        (true, Some(p)) => Ok(p),
1273                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1274                    }
1275                };
1276                let mut generators = Vec::with_capacity(roots.len());
1277                for &root in roots {
1278                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1279                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES).map(|i| tube_point(root, start + (end - start) * i as f64 / LOFT_SAMPLES as f64)).collect();
1280                    exact[0] = points[a];
1281                    exact[LOFT_SAMPLES] = points[b];
1282                    curves.push(ToolCurve { curve: generatrix(root)?, start: a, end: b, degenerate: false, samples: Some(exact) });
1283                    generators.push(curves.len() - 1);
1284                }
1285                for j in 0..roots.len() {
1286                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1287                    let surface = frag(make_revolution(origin, w, &generatrix(alpha)?, beta - alpha), "patch")?;
1288                    let (mid_psi, mid_v) = (0.5 * (alpha + beta), 0.5 * (start + end));
1289                    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()));
1290                    let front = screw.velocity(tube_point(mid_psi, mid_v)).dot(mid_normal) > 0.0;
1291                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1292                        let p = apex.expect("apex");
1293                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1294                        curves.len() - 1
1295                    };
1296                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1297                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1298                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1299                    let coedges = vec![
1300                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1301                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1302                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1303                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1304                    ];
1305                    let chart = Chart::Revolution {
1306                        origin,
1307                        w,
1308                        u1,
1309                        u2,
1310                        alpha,
1311                        theta: beta - alpha,
1312                        spans_u: spans_of(&surface.knots_u),
1313                        meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_of(&surface.knots_v) },
1314                    };
1315                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1316                }
1317            }
1318            Kind::Slide => {
1319                let rim = if on_axis(m0) { above } else { below };
1320                let n = normal(piece, 0.5);
1321                let outward = w.scale(n[1].signum());
1322                let arcs = rim_angles[&rim].len();
1323                // Counter-clockwise about the outward normal: increasing ψ about +w.
1324                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1325                slides.push(SlideDisc {
1326                    centre: origin.add(w.scale(m0[1])),
1327                    u: u1,
1328                    v: outward.cross(u1),
1329                    rim: order.into_iter().map(|j| (rim_arcs[&(rim, j)], n[1] > 0.0)).collect(),
1330                });
1331            }
1332            Kind::Ruled(roots) if roots.is_empty() => {
1333                // A flat end wholly on one side: a disc about the axis.
1334                let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
1335                if !flat || !(on_axis(m0) || on_axis(m1)) {
1336                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a whole side or ring is not swept here")));
1337                }
1338                let rim = if on_axis(m0) { above } else { below };
1339                let front = sign_at(piece, 0.0);
1340                if (0..64).any(|k| sign_at(piece, TAU * k as f64 / 64.0) != front) {
1341                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a flat end meets its grazing line")));
1342                }
1343                let n = normal(piece, 0.5);
1344                let outward = w.scale(n[1].signum());
1345                let centre = origin.add(w.scale(m0[1]));
1346                let (u, v) = (u1, outward.cross(u1));
1347                let arcs = rim_angles[&rim].len();
1348                let mut coedges = Vec::with_capacity(arcs);
1349                let mut corners = Vec::new();
1350                // Counter-clockwise about the outward normal: increasing ψ about +w.
1351                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1352                for j in order {
1353                    let c = rim_arcs[&(rim, j)];
1354                    let forward = n[1] > 0.0;
1355                    coedges.push((c, forward, plane_pcurve(centre, u, v, &curves[c].curve, forward)?));
1356                    corners.push(points[curves[c].start]);
1357                }
1358                let r = junction(rim)[0];
1359                corners.extend([centre.add(u.scale(r)).add(v.scale(r)), centre.sub(u.scale(r)).sub(v.scale(r))]);
1360                caps.push(Cap { surface: plane_patch(centre, u, v, &corners)?, front, coedges, chart: Some(Chart::Plane { origin: centre, u, v }) });
1361            }
1362            Kind::Ruled(roots) => {
1363                // A cone to a point: its generators start (or end) at the
1364                // apex, and each patch has a pole there in place of a rim arc.
1365                let apex = if on_axis(m0) || on_axis(m1) {
1366                    let m = if on_axis(m0) { m0 } else { m1 };
1367                    points.push(at(0.0, m[1], 0.0));
1368                    Some(points.len() - 1)
1369                } else {
1370                    None
1371                };
1372                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1373                    match (on, apex) {
1374                        (true, Some(p)) => Ok(p),
1375                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1376                    }
1377                };
1378                // Generators at each root, from the start rim to the end rim.
1379                let mut generators = Vec::with_capacity(roots.len());
1380                for &root in roots {
1381                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1382                    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();
1383                    curves.push(ToolCurve { curve: frag(make_line(points[a], points[b]), "generator")?, start: a, end: b, degenerate: false, samples: Some(line_samples) });
1384                    generators.push(curves.len() - 1);
1385                }
1386                for j in 0..roots.len() {
1387                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1388                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1389                    let surface = frag(make_revolution(origin, w, &generatrix, beta - alpha), "patch")?;
1390                    let front = sign_at(piece, 0.5 * (alpha + beta));
1391                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1392                        let p = apex.expect("apex");
1393                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1394                        curves.len() - 1
1395                    };
1396                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1397                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1398                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1399                    let coedges = vec![
1400                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1401                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1402                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1403                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1404                    ];
1405                    let chart = Chart::Revolution { origin, w, u1, u2, alpha, theta: beta - alpha, spans_u: spans_of(&surface.knots_u), meridian: MeridianChart::Line { m0, m1 } };
1406                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1407                }
1408            }
1409            Kind::Moving => {
1410                if on_axis(m0) || on_axis(m1) {
1411                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a split cone to a point is not swept here")));
1412                }
1413                let n = 128;
1414                let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1415                let pairs: Vec<(f64, f64)> = params.iter().map(|&t| branches(piece, t).expect("checked")).collect();
1416                let pick = |pair: (f64, f64), which: usize| if which == 0 { pair.0 } else { pair.1 };
1417                // K: the lower and upper branch, each from the start rim to the end rim.
1418                let mut branch_curves = [0usize; 2];
1419                for which in 0..2 {
1420                    let (psi0, psi1) = (pick(pairs[0], which), pick(pairs[n], which));
1421                    let start = rim_points[&(below, arc_index(below, psi0)?)];
1422                    let end = rim_points[&(above, arc_index(above, psi1)?)];
1423                    let mut samples: Vec<Vec3> = params
1424                        .iter()
1425                        .zip(&pairs)
1426                        .map(|(&t, &pair)| {
1427                            let m = piece_point(piece, t);
1428                            at(m[0], m[1], pick(pair, which))
1429                        })
1430                        .collect();
1431                    samples[0] = points[start];
1432                    samples[n] = points[end];
1433                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES)
1434                        .map(|i| {
1435                            let t = i as f64 / LOFT_SAMPLES as f64;
1436                            let m = piece_point(piece, t);
1437                            at(m[0], m[1], pick(branches(piece, t).expect("checked"), which))
1438                        })
1439                        .collect();
1440                    exact[0] = points[start];
1441                    exact[LOFT_SAMPLES] = points[end];
1442                    curves.push(ToolCurve { curve: frag(crate::interpolate_curve(&samples, 5, &params), "branch")?, start, end, degenerate: false, samples: Some(exact) });
1443                    branch_curves[which] = curves.len() - 1;
1444                }
1445                // Front between lower and upper; back from upper to lower + 2π.
1446                for (lo_which, hi_which, hi_turn) in [(0usize, 1usize, 0.0), (1, 0, TAU)] {
1447                    let lo = |i: usize| pick(pairs[i], lo_which);
1448                    let hi = |i: usize| pick(pairs[i], hi_which) + hi_turn;
1449                    let alpha = (0..=n).map(lo).fold(f64::INFINITY, f64::min) - 1e-3;
1450                    let theta = (0..=n).map(hi).fold(f64::NEG_INFINITY, f64::max) + 1e-3 - alpha;
1451                    if theta >= TAU {
1452                        return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a side patch wraps all the way round")));
1453                    }
1454                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1455                    let surface = frag(make_revolution(origin, w, &generatrix, theta), "patch")?;
1456                    let spans = (surface.knots_u.len() - 6) / 2 + 1;
1457                    let u_of = |psi: f64| crate::circle_angle_to_parameter(spans, theta, psi - alpha);
1458                    let angle_near = |x: Vec3, guess: f64| -> f64 {
1459                        let r = x.sub(origin);
1460                        let a = r.dot(u2).atan2(r.dot(u1));
1461                        guess + (a - guess + PI).rem_euclid(TAU) - PI
1462                    };
1463                    let front = sign_at(piece, 0.5 * (lo(n / 2) + hi(n / 2)));
1464                    // A rim arc's pcurve on this patch, through its own parameter.
1465                    let rim_pcurve = |arc: usize, v: f64| -> Result<NurbsCurve, KernelRefusal> {
1466                        let curve = &curves[arc].curve;
1467                        let [d0, d1] = frag(curve.domain(), "domain")?;
1468                        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
1469                        let mut uv = Vec::with_capacity(ts.len());
1470                        for &t in &ts {
1471                            let x = frag(curve.evaluate(t), "rim")?;
1472                            uv.push(Vec3::new(u_of(angle_near(x, alpha + 0.5 * theta)), v, 0.0));
1473                        }
1474                        frag(crate::interpolate_curve(&uv, 5, &ts), "rim_pcurve")
1475                    };
1476                    // A grazing branch's pcurve: the image of the built edge,
1477                    // through its own parameter (angle about the axis; place
1478                    // along the meridian line).
1479                    let branch_pcurve = |which: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> {
1480                        let curve = &curves[branch_curves[which]].curve;
1481                        let [d0, d1] = frag(curve.domain(), "domain")?;
1482                        let (span_rho, span_z) = (m1[0] - m0[0], m1[1] - m0[1]);
1483                        let length2 = span_rho * span_rho + span_z * span_z;
1484                        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
1485                        let mut uv = Vec::with_capacity(ts.len());
1486                        for &t in &ts {
1487                            let x = frag(curve.evaluate(t), "branch")?;
1488                            let r = x.sub(origin);
1489                            let z = r.dot(w);
1490                            let rho = r.sub(w.scale(z)).length();
1491                            let along = ((rho - m0[0]) * span_rho + (z - m0[1]) * span_z) / length2;
1492                            uv.push(Vec3::new(u_of(angle_near(x, alpha + 0.5 * theta)), along, 0.0));
1493                        }
1494                        frag(crate::interpolate_curve(&uv, 5, &ts), "branch_pcurve")
1495                    };
1496                    let bottom = rim_arcs[&(below, arc_index(below, lo(0))?)];
1497                    let top = rim_arcs[&(above, arc_index(above, lo(n))?)];
1498                    let coedges = vec![
1499                        (bottom, true, rim_pcurve(bottom, 0.0)?),
1500                        (branch_curves[hi_which], true, branch_pcurve(hi_which, hi_turn)?),
1501                        (top, false, frag(rim_pcurve(top, 1.0)?.reversed(), "reversed")?),
1502                        (branch_curves[lo_which], false, frag(branch_pcurve(lo_which, 0.0)?.reversed(), "reversed")?),
1503                    ];
1504                    let chart_spans = spans_of(&surface.knots_u);
1505                    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 } }) });
1506                }
1507            }
1508            Kind::TorusZone { psi_a, psi_b, at_end } => {
1509                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1510                let (psi_a, psi_b, at_end) = (*psi_a, *psi_b, *at_end);
1511                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1512                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1513                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1514                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()));
1515                let root = |psi: f64| -> Option<f64> {
1516                    let (a, b, c) = harmonic(|v| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)));
1517                    let r = a.hypot(b);
1518                    if !(c.abs() < r) {
1519                        return None;
1520                    }
1521                    let base = b.atan2(a);
1522                    let spread = (-c / r).acos();
1523                    [base - spread, base + spread].into_iter().map(|v| start + (v - start).rem_euclid(TAU)).find(|&v| v <= end + 1e-12)
1524                };
1525                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1526                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1527                    let from = tube_point(psi, start);
1528                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1529                    frag(surface.iso_curve_v(0.0), "tube")
1530                };
1531                let (rim_k, other_k) = if at_end { (above, below) } else { (below, above) };
1532                let ka = rim_points[&(rim_k, arc_index(rim_k, psi_a)?)];
1533                let kb = rim_points[&(rim_k, arc_index(rim_k, psi_b)?)];
1534                // K: the graph over ψ ∈ [ψa, ψb].
1535                let n = 256;
1536                let params: Vec<f64> = (0..=n).map(|j| j as f64 / n as f64).collect();
1537                // Spaced as 1 − cos: where K meets its rim it runs along the
1538                // meridian, so its tube angle goes as √(ψ − ψa); in this
1539                // parameter it is regular.
1540                let psi_of = |t: f64| psi_a + (psi_b - psi_a) * 0.5 * (1.0 - (PI * t).cos());
1541                let mut xyz = Vec::with_capacity(n + 1);
1542                for j in 0..=n {
1543                    let psi = psi_of(params[j]);
1544                    let v = if j == 0 || j == n { if at_end { end } else { start } } else {
1545                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1546                    };
1547                    xyz.push(tube_point(psi, v));
1548                }
1549                xyz[0] = points[ka];
1550                xyz[n] = points[kb];
1551                let mut exact = Vec::with_capacity(LOFT_SAMPLES + 1);
1552                for i in 0..=LOFT_SAMPLES {
1553                    let psi = psi_of(i as f64 / LOFT_SAMPLES as f64);
1554                    let v = if i == 0 || i == LOFT_SAMPLES { if at_end { end } else { start } } else {
1555                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1556                    };
1557                    exact.push(tube_point(psi, v));
1558                }
1559                exact[0] = points[ka];
1560                exact[LOFT_SAMPLES] = points[kb];
1561                curves.push(ToolCurve { curve: frag(crate::interpolate_curve(&xyz, 5, &params), "torus_k")?, start: ka, end: kb, degenerate: false, samples: Some(exact) });
1562                let k_curve = curves.len() - 1;
1563                // Cut meridians at ψa and ψb, from the start rim to the end rim.
1564                let mut cut = [0usize; 2];
1565                for (slot, psi) in [(0, psi_a), (1, psi_b)] {
1566                    let (lo, hi) = (rim_points[&(below, arc_index(below, psi)?)], rim_points[&(above, arc_index(above, psi)?)]);
1567                    curves.push(ToolCurve { curve: generatrix(psi)?, start: lo, end: hi, degenerate: false, samples: None });
1568                    cut[slot] = curves.len() - 1;
1569                }
1570                let label = |psi: f64, v: f64| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)) > 0.0;
1571                // The patch over [α, β] and its exact inverse.
1572                let patch = |alpha: f64, beta: f64| -> Result<(NurbsSurface, usize, usize), KernelRefusal> {
1573                    let g = generatrix(alpha)?;
1574                    let surface = frag(make_revolution(origin, w, &g, beta - alpha), "torus_patch")?;
1575                    let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1576                    let spans_v = (g.knots.len() - 6) / 2 + 1;
1577                    Ok((surface, spans_u, spans_v))
1578                };
1579                let inverse_pcurve = |curve: &NurbsCurve, alpha: f64, beta: f64, spans_u: usize, spans_v: usize, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
1580                    let [d0, d1] = frag(curve.domain(), "domain")?;
1581                    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
1582                    let mut uv = Vec::with_capacity(ts.len());
1583                    for &t in &ts {
1584                        let x = frag(curve.evaluate(t), "point")?;
1585                        let r = x.sub(origin);
1586                        let mid = 0.5 * (alpha + beta);
1587                        let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
1588                        let q = x.sub(tube_centre(psi));
1589                        let radial = u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1590                        let vmid = 0.5 * (start + end);
1591                        let v = vmid + (q.dot(w).atan2(q.dot(radial)) - vmid + PI).rem_euclid(TAU) - PI;
1592                        uv.push(Vec3::new(
1593                            crate::circle_angle_to_parameter(spans_u, beta - alpha, psi - alpha),
1594                            crate::circle_angle_to_parameter(spans_v, end - start, v - start),
1595                            0.0,
1596                        ));
1597                    }
1598                    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "torus_pcurve")?;
1599                    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
1600                };
1601                // The band away from K: a natural patch over [ψb, ψa + 2π].
1602                {
1603                    let (surface, _, band_spans_v) = patch(psi_b, psi_a + TAU)?;
1604                    let (bottom, top) = (rim_arcs[&(below, arc_index(below, psi_b)?)], rim_arcs[&(above, arc_index(above, psi_b)?)]);
1605                    let coedges = vec![
1606                        (bottom, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1607                        (cut[0], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1608                        (top, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1609                        (cut[1], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1610                    ];
1611                    let mid = psi_b + 0.5 * (psi_a + TAU - psi_b);
1612                    let chart_spans = spans_of(&surface.knots_u);
1613                    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 } }) });
1614                }
1615                // Over [ψa, ψb]: the lens between K and its rim, and the rest.
1616                let (surface, spans_u, spans_v) = patch(psi_a, psi_b)?;
1617                let rim_arc = rim_arcs[&(rim_k, arc_index(rim_k, psi_a)?)];
1618                let other_arc = rim_arcs[&(other_k, arc_index(other_k, psi_a)?)];
1619                let mid = 0.5 * (psi_a + psi_b);
1620                let v_k = root(mid).ok_or_else(|| refuse("torus_zone", "no grazing point mid-way".into()))?;
1621                let k_pc = |forward: bool| inverse_pcurve(&curves[k_curve].curve, psi_a, psi_b, spans_u, spans_v, forward);
1622                let lens_v = if at_end { 0.5 * (v_k + end) } else { 0.5 * (v_k + start) };
1623                let rest_v = if at_end { 0.5 * (v_k + start) } else { 0.5 * (v_k + end) };
1624                if at_end {
1625                    // Lens: K (ψa -> ψb) under the end rim, then the end rim back.
1626                    let lens = vec![(k_curve, true, k_pc(true)?), (rim_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?)];
1627                    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 } }) });
1628                    let rest = vec![
1629                        (other_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1630                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1631                        (k_curve, false, k_pc(false)?),
1632                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1633                    ];
1634                    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 } }) });
1635                } else {
1636                    let lens = vec![(rim_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?), (k_curve, false, k_pc(false)?)];
1637                    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 } }) });
1638                    let rest = vec![
1639                        (k_curve, true, k_pc(true)?),
1640                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1641                        (other_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1642                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1643                    ];
1644                    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 } }) });
1645                }
1646            }
1647            Kind::Ball { centre, radius } => {
1648                let m = frag(screw.velocity(*centre).normalized(), "ball_still")?;
1649                let d = frag(w.cross(m).normalized().or_else(|_| u1.cross(m).normalized()), "ball_axis")?;
1650                let (e1, e2) = (centre.add(d.scale(*radius)), centre.sub(d.scale(*radius)));
1651                points.push(e1);
1652                points.push(e2);
1653                let (i1, i2) = (points.len() - 2, points.len() - 1);
1654                let half = frag(make_revolution(*centre, m, &frag(make_line(e1, e1.add(m)), "line")?, PI), "great")?;
1655                let k_a = frag(half.iso_curve_v(0.0), "great")?;
1656                // Exact samples at even angles from e1 round to e2 (for a
1657                // lofted wall), turned the way the curve runs.
1658                let k_a_samples: Vec<Vec3> = {
1659                    let [a0, a1] = frag(k_a.domain(), "domain")?;
1660                    let middle = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?;
1661                    let arm = e1.sub(*centre);
1662                    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 };
1663                    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();
1664                    list[0] = e1;
1665                    list[LOFT_SAMPLES] = e2;
1666                    list
1667                };
1668                curves.push(ToolCurve { curve: k_a.clone(), start: i1, end: i2, degenerate: false, samples: Some(k_a_samples.clone()) });
1669                let k_a_index = curves.len() - 1;
1670                let [a0, a1] = frag(k_a.domain(), "domain")?;
1671                let h = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?.sub(*centre);
1672                let mut k_b_index: Option<usize> = None;
1673                for front in [true, false] {
1674                    let toward = if front { m } else { m.scale(-1.0) };
1675                    let da = if d.cross(h).dot(toward) > 0.0 { d } else { d.scale(-1.0) };
1676                    let mut generatrix = k_a.clone();
1677                    let mut surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1678                    let outward = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1679                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1680                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1681                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1682                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1683                    };
1684                    let mut forward = true;
1685                    if !outward(&surface)? {
1686                        generatrix = frag(generatrix.reversed(), "reversed")?;
1687                        surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1688                        forward = false;
1689                    }
1690                    let (start, end) = if forward { (i1, i2) } else { (i2, i1) };
1691                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1692                    let k_b = match k_b_index {
1693                        Some(index) => index,
1694                        None => {
1695                            // The other half of the great circle: the first half turned half way about `da`.
1696                            let mut samples: Vec<Vec3> = k_a_samples.iter().map(|&x| centre.add(x.sub(*centre).rotate_about(da, PI))).collect();
1697                            if !forward {
1698                                samples.reverse();
1699                            }
1700                            samples[0] = points[start];
1701                            samples[LOFT_SAMPLES] = points[end];
1702                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: Some(samples) });
1703                            k_b_index = Some(curves.len() - 1);
1704                            curves.len() - 1
1705                        }
1706                    };
1707                    let k_b_forward = curves[k_b].start == start;
1708                    let k_b_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1709                    let poles = [start, end].map(|p| {
1710                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1711                        curves.len() - 1
1712                    });
1713                    let coedges = vec![
1714                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1715                        (k_b, k_b_forward, k_b_pcurve),
1716                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1717                        (k_a_index, !forward, uv_line([0.0, g1], [0.0, g0])?),
1718                    ];
1719                    caps.push(Cap { surface, front, coedges, chart: None });
1720                }
1721            }
1722            Kind::Sphere { centre, pole_at_start } => {
1723                let rim = if *pole_at_start { above } else { below };
1724                let angles = rim_angles[&rim].clone();
1725                if angles.len() != 2 {
1726                    return Err(refuse("revolved_rims", "a hemisphere's rim is not split in two".into()));
1727                }
1728                let pole_side = w.scale(if *pole_at_start { m0[1] - m1[1] } else { m1[1] - m0[1] }.signum());
1729                let m = screw.velocity(*centre);
1730                let e1 = points[rim_points[&(rim, 0)]];
1731                let d = frag(e1.sub(*centre).normalized(), "lune_axis")?;
1732                let mut great: Option<usize> = None;
1733                for j in 0..2 {
1734                    let arc = rim_arcs[&(rim, j)];
1735                    let [a0, a1] = frag(curves[arc].curve.domain(), "domain")?;
1736                    let middle = frag(curves[arc].curve.evaluate(0.5 * (a0 + a1)), "middle")?;
1737                    let hv = middle.sub(*centre);
1738                    let da = if d.cross(hv).dot(pole_side) > 0.0 { d } else { d.scale(-1.0) };
1739                    // Turn the rim arc about da until its middle reaches K's plane.
1740                    let theta = (-m.dot(hv)).atan2(m.dot(da.cross(hv))).rem_euclid(TAU);
1741                    let theta = if theta > PI { theta - PI } else { theta };
1742                    if !(theta > 1e-9 && theta < PI - 1e-9) {
1743                        return Err(refuse("revolved_lune", "the great circle meets the rim's plane edge-on".into()));
1744                    }
1745                    let mut generatrix = curves[arc].curve.clone();
1746                    let mut surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1747                    // Outward: (x − centre) at the lune's middle.
1748                    let probe = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1749                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1750                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1751                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1752                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1753                    };
1754                    let mut forward = true;
1755                    if !probe(&surface)? {
1756                        generatrix = frag(generatrix.reversed(), "reversed")?;
1757                        surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1758                        forward = false;
1759                    }
1760                    let (start, end) = if forward { (curves[arc].start, curves[arc].end) } else { (curves[arc].end, curves[arc].start) };
1761                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1762                    // The great-circle half: the turned generatrix (u = 1), from
1763                    // `start` to `end`; made once, by the first lune.
1764                    let k_curve = match great {
1765                        Some(index) => index,
1766                        None => {
1767                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: None });
1768                            great = Some(curves.len() - 1);
1769                            curves.len() - 1
1770                        }
1771                    };
1772                    let k_forward = curves[k_curve].start == start;
1773                    let poles = [start, end].map(|p| {
1774                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1775                        curves.len() - 1
1776                    });
1777                    let k_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1778                    let coedges = vec![
1779                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1780                        (k_curve, k_forward, k_pcurve),
1781                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1782                        (arc, !forward, uv_line([0.0, g1], [0.0, g0])?),
1783                    ];
1784                    let mid_psi = if j == 0 { 0.5 * (angles[0] + angles[1]) } else { 0.5 * (angles[1] + angles[0] + TAU) };
1785                    let front = m.dot(at(1.0, 0.0, mid_psi).sub(origin)) > 0.0;
1786                    caps.push(Cap { surface, front, coedges, chart: None });
1787                }
1788            }
1789        }
1790    }
1791    Ok(Split {
1792        points,
1793        curves,
1794        caps,
1795        slides,
1796        slide_sides,
1797        scale,
1798        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
1799    })
1800}
1801
1802/// `BREP_SWEEP_RING_WINDING` (default off): a ring whose grazing curves wind
1803/// round its tube as they go once round the ring is split along their
1804/// continuous unwrapping, in six pieces, instead of refused.
1805fn ring_winding_on() -> bool {
1806    crate::switch!("BREP_SWEEP_RING_WINDING", false)
1807}
1808
1809/// A ring split by grazing curves that wind round its tube: the curves' angle
1810/// v on the tube, unwrapped continuously along ψ, gains a whole number of
1811/// turns going once round the ring. None where it gains none (the two-halves
1812/// split serves). Six pieces along ψ keep each band's stretch of v short of a
1813/// whole turn while the curves turn, and leave the tumble's eight trial seams
1814/// (π/4 apart) four distinct placements.
1815#[allow(clippy::too_many_arguments)]
1816fn split_torus_wound(
1817    screw: &Screw,
1818    origin: Vec3,
1819    w: Vec3,
1820    u1: Vec3,
1821    u2: Vec3,
1822    centre: [f64; 2],
1823    radius: f64,
1824    meridian: &[OutlinePiece],
1825) -> Result<Option<Split>, KernelRefusal> {
1826    const PIECES: usize = 6;
1827    let (rho_c, z_c) = (centre[0], centre[1]);
1828    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1829    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
1830    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
1831    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
1832    let n = screw.loop_samples;
1833    let total = PIECES * n;
1834    // (ψ, lower, upper) round the whole ring, each base angle the one nearest
1835    // the last.
1836    let mut round: Vec<(f64, f64, f64)> = Vec::with_capacity(total + 1);
1837    let mut near = {
1838        let (a, b, _) = harmonic(|v| g(0.0, v));
1839        b.atan2(a)
1840    };
1841    for i in 0..=total {
1842        let psi = TAU * i as f64 / total as f64;
1843        let (a, b, c) = harmonic(|v| g(psi, v));
1844        let r = a.hypot(b);
1845        if !(c.abs() < r * (1.0 - 1e-9)) {
1846            return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
1847        }
1848        let base = near + (b.atan2(a) - near + PI).rem_euclid(TAU) - PI;
1849        if i > 0 && (base - near).abs() > 0.5 {
1850            return Err(refuse("ring_grazing", "the ring's grazing curves turn too fast".into()));
1851        }
1852        near = base;
1853        let spread = (-c / r).acos();
1854        round.push((psi, base - spread, base + spread));
1855    }
1856    if ((round[total].1 - round[0].1) / TAU).round() == 0.0 {
1857        return Ok(None);
1858    }
1859    let samples: Vec<Vec<(f64, f64, f64)>> = (0..PIECES).map(|k| round[k * n..=(k + 1) * n].to_vec()).collect();
1860    let seam_psi = |k: usize| TAU * k as f64 / PIECES as f64;
1861    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1862    let mut points: Vec<Vec3> = Vec::new();
1863    let mut curves: Vec<ToolCurve> = Vec::new();
1864    // Points: at each seam, on each branch (the last piece ends on seam 0,
1865    // a whole number of turns round the tube on).
1866    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, branch)
1867    for (seam, piece) in samples.iter().enumerate() {
1868        let (psi, lower, upper) = piece[0];
1869        for (branch, v) in [(0, lower), (1, upper)] {
1870            points.push(point(psi, v));
1871            corner.insert((seam, branch), points.len() - 1);
1872        }
1873    }
1874    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (piece, branch)
1875    for (piece, list) in samples.iter().enumerate() {
1876        for branch in 0..2 {
1877            let mut xyz: Vec<Vec3> = list.iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
1878            let (start, end) = (corner[&(piece, branch)], corner[&((piece + 1) % PIECES, branch)]);
1879            xyz[0] = points[start];
1880            xyz[n] = points[end];
1881            curves.push(ToolCurve { curve: frag(crate::interpolate_curve(&xyz, 5, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
1882            branch_curve.insert((piece, branch), curves.len() - 1);
1883        }
1884    }
1885    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
1886        let start = point(psi, v0);
1887        let axis = radial(psi).cross(w);
1888        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
1889        frag(surface.iso_curve_v(0.0), "tube_arc")
1890    };
1891    // Seam arcs of each band: band 0 (front) from lower to upper, band 1
1892    // (back) from upper to lower + 2π.
1893    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
1894    for seam in 0..PIECES {
1895        let (psi, lower, upper) = samples[seam][0];
1896        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
1897        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
1898        seam_arc.insert((seam, 0), curves.len() - 1);
1899        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
1900        seam_arc.insert((seam, 1), curves.len() - 1);
1901    }
1902    let mut caps = Vec::new();
1903    for piece in 0..PIECES {
1904        let (psi_a, psi_b) = (seam_psi(piece), seam_psi(piece + 1));
1905        for band in 0..2 {
1906            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
1907            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
1908            // As in the two-halves split: a margin each side for end trims.
1909            let low = samples[piece].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
1910            let high = samples[piece].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
1911            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
1912            let (v_low, v_high) = (low - margin, high + margin);
1913            let theta_v = v_high - v_low;
1914            if theta_v >= TAU {
1915                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
1916            }
1917            let generatrix = tube_arc(psi_a, v_low, v_high)?;
1918            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
1919            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1920            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
1921            let uv_of = |psi: f64, v: f64| {
1922                Vec3::new(
1923                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
1924                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
1925                    0.0,
1926                )
1927            };
1928            let angles_of = |x: Vec3| -> (f64, f64) {
1929                let r = x.sub(origin);
1930                let psi = r.dot(u2).atan2(r.dot(u1));
1931                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
1932                let q = x.sub(tube_centre(psi));
1933                let v = q.dot(w).atan2(q.dot(radial(psi)));
1934                let mid = 0.5 * (v_low + v_high);
1935                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
1936            };
1937            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
1938                let [d0, d1] = frag(curve.domain(), "domain")?;
1939                let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
1940                let mut uv = Vec::with_capacity(ts.len());
1941                for &t in &ts {
1942                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1943                    uv.push(uv_of(psi, v));
1944                }
1945                frag(crate::interpolate_curve(&uv, 5, &ts), "ring_pcurve")
1946            };
1947            let lower_edge = branch_curve[&(piece, lo_branch)];
1948            let upper_edge = branch_curve[&(piece, hi_branch)];
1949            let right = seam_arc[&((piece + 1) % PIECES, band)];
1950            let left = seam_arc[&(piece, band)];
1951            let coedges = vec![
1952                (lower_edge, true, inverse_pcurve(&curves[lower_edge].curve)?),
1953                (right, true, inverse_pcurve(&curves[right].curve)?),
1954                (upper_edge, false, frag(inverse_pcurve(&curves[upper_edge].curve)?.reversed(), "reversed")?),
1955                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
1956            ];
1957            let mid = &samples[piece][n / 2];
1958            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
1959            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 } }) });
1960        }
1961    }
1962    Ok(Some(Split {
1963        points,
1964        curves,
1965        caps,
1966        slides: Vec::new(),
1967        slide_sides: Vec::new(),
1968        scale: rho_c + radius,
1969        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
1970    }))
1971}
1972
1973/// A ring (torus: the circle of `radius` about `centre` in (ρ, z), off the
1974/// axis), split by its two grazing curves. For each angle ψ about the ring's
1975/// axis the grazing value along the tube's circle is A cos v + B sin v + C, so
1976/// each curve is a graph v(ψ) round the ring; the front band lies between
1977/// them. Each band is built in two halves (ψ in [0, π] and [π, 2π]) so no face
1978/// closes on itself.
1979#[allow(clippy::too_many_arguments)]
1980fn split_torus(
1981    screw: &Screw,
1982    origin: Vec3,
1983    w: Vec3,
1984    u1: Vec3,
1985    u2: Vec3,
1986    centre: [f64; 2],
1987    radius: f64,
1988    meridian: &[OutlinePiece],
1989) -> Result<Split, KernelRefusal> {
1990    if ring_winding_on() {
1991        if let Some(split) = split_torus_wound(screw, origin, w, u1, u2, centre, radius, meridian)? {
1992            return Ok(split);
1993        }
1994    }
1995    let (rho_c, z_c) = (centre[0], centre[1]);
1996    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1997    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
1998    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
1999    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
2000    let reference = {
2001        let (a, b, _) = harmonic(|v| g(0.0, v));
2002        b.atan2(a)
2003    };
2004    // The lower and upper grazing angles v at ψ, unwrapped; the front between.
2005    let branches = |psi: f64| -> Option<(f64, f64)> {
2006        let (a, b, c) = harmonic(|v| g(psi, v));
2007        let r = a.hypot(b);
2008        if !(c.abs() < r * (1.0 - 1e-9)) {
2009            return None;
2010        }
2011        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
2012        let spread = (-c / r).acos();
2013        Some((base - spread, base + spread))
2014    };
2015    let n = screw.loop_samples;
2016    let halves = [(0.0, PI), (PI, TAU)];
2017    let mut samples: Vec<Vec<(f64, f64, f64)>> = Vec::new(); // per half: (ψ, lower, upper)
2018    for &(a, b) in &halves {
2019        let mut list = Vec::with_capacity(n + 1);
2020        let mut previous: Option<(f64, f64)> = None;
2021        for i in 0..=n {
2022            let psi = a + (b - a) * i as f64 / n as f64;
2023            let Some(pair) = branches(psi) else {
2024                return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
2025            };
2026            if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
2027                return Err(refuse("ring_grazing", "the ring's grazing curves turn too fast".into()));
2028            }
2029            previous = Some(pair);
2030            list.push((psi, pair.0, pair.1));
2031        }
2032        samples.push(list);
2033    }
2034    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
2035    let mut points: Vec<Vec3> = Vec::new();
2036    let mut curves: Vec<ToolCurve> = Vec::new();
2037    // Points: at ψ = 0 and π, on each branch.
2038    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam 0 | 1, branch)
2039    for seam in 0..2 {
2040        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)) };
2041        for (branch, v) in [(0, lower), (1, upper)] {
2042            points.push(point(psi, v));
2043            corner.insert((seam, branch), points.len() - 1);
2044        }
2045    }
2046    let seam_of_end = |half: usize, at_end: bool| -> usize { if at_end { 1 - half } else { half } };
2047    // K: each branch over each half.
2048    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (half, branch)
2049    for half in 0..2 {
2050        for branch in 0..2 {
2051            let mut xyz: Vec<Vec3> = samples[half].iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
2052            let (start, end) = (corner[&(seam_of_end(half, false), branch)], corner[&(seam_of_end(half, true), branch)]);
2053            xyz[0] = points[start];
2054            xyz[n] = points[end];
2055            curves.push(ToolCurve { curve: frag(crate::interpolate_curve(&xyz, 5, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
2056            branch_curve.insert((half, branch), curves.len() - 1);
2057        }
2058    }
2059    // Seam arcs of each band at ψ = 0 and π: band 0 (front) from lower to
2060    // upper, band 1 (back) from upper to lower + 2π.
2061    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
2062        let start = point(psi, v0);
2063        let axis = radial(psi).cross(w);
2064        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
2065        frag(surface.iso_curve_v(0.0), "tube_arc")
2066    };
2067    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
2068    for seam in 0..2 {
2069        let psi = if seam == 0 { 0.0 } else { PI };
2070        let (lower, upper) = (samples[seam][0].1, samples[seam][0].2);
2071        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
2072        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
2073        seam_arc.insert((seam, 0), curves.len() - 1);
2074        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
2075        seam_arc.insert((seam, 1), curves.len() - 1);
2076    }
2077    let mut caps = Vec::new();
2078    for half in 0..2 {
2079        let (psi_a, psi_b) = halves[half];
2080        for band in 0..2 {
2081            // The band's lower and upper edges (v), as branches.
2082            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
2083            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
2084            // A margin each side: an end cap may be carried a little across its
2085            // grazing curve (see `end_trim`), as far as the tube leaves room.
2086            let low = samples[half].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
2087            let high = samples[half].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
2088            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
2089            let (v_low, v_high) = (low - margin, high + margin);
2090            let theta_v = v_high - v_low;
2091            if theta_v >= TAU {
2092                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
2093            }
2094            let generatrix = tube_arc(psi_a, v_low, v_high)?;
2095            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
2096            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
2097            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
2098            let uv_of = |psi: f64, v: f64| {
2099                Vec3::new(
2100                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
2101                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
2102                    0.0,
2103                )
2104            };
2105            // (ψ, v) of a point, unwrapped near the patch.
2106            let angles_of = |x: Vec3| -> (f64, f64) {
2107                let r = x.sub(origin);
2108                let psi = r.dot(u2).atan2(r.dot(u1));
2109                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
2110                let q = x.sub(tube_centre(psi));
2111                let v = q.dot(w).atan2(q.dot(radial(psi)));
2112                let mid = 0.5 * (v_low + v_high);
2113                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
2114            };
2115            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
2116                let [d0, d1] = frag(curve.domain(), "domain")?;
2117                let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
2118                let mut uv = Vec::with_capacity(ts.len());
2119                for &t in &ts {
2120                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
2121                    uv.push(uv_of(psi, v));
2122                }
2123                frag(crate::interpolate_curve(&uv, 5, &ts), "ring_pcurve")
2124            };
2125            let branch_pcurve = |b: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> { inverse_pcurve(&curves[branch_curve[&(half, b)]].curve) };
2126            let lower_edge = branch_curve[&(half, lo_branch)];
2127            let upper_edge = branch_curve[&(half, hi_branch)];
2128            let right = seam_arc[&(seam_of_end(half, true), band)];
2129            let left = seam_arc[&(seam_of_end(half, false), band)];
2130            let coedges = vec![
2131                (lower_edge, true, branch_pcurve(lo_branch, 0.0)?),
2132                (right, true, inverse_pcurve(&curves[right].curve)?),
2133                (upper_edge, false, frag(branch_pcurve(hi_branch, hi_turn)?.reversed(), "reversed")?),
2134                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
2135            ];
2136            let mid = &samples[half][n / 2];
2137            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
2138            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 } }) });
2139        }
2140    }
2141    Ok(Split {
2142        points,
2143        curves,
2144        caps,
2145        slides: Vec::new(),
2146        slide_sides: Vec::new(),
2147        scale: rho_c + radius,
2148        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
2149    })
2150}
2151
2152/// Builder of a closed shell with shared vertices and edges.
2153struct Shell {
2154    vertices: Vec<VertexRecord>,
2155    edges: Vec<EdgeRecord>,
2156    faces: Vec<FaceRecord>,
2157    next: u64,
2158    /// Loops beyond each face's first (holes).
2159    holes: usize,
2160}
2161
2162impl Shell {
2163    fn new() -> Self {
2164        Self { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 1, holes: 0 }
2165    }
2166
2167    fn id(&mut self) -> u64 {
2168        self.next += 1;
2169        self.next
2170    }
2171
2172    fn vertex(&mut self, point: Vec3) -> u64 {
2173        let id = self.id();
2174        self.vertices.push(VertexRecord { id, point });
2175        id
2176    }
2177
2178    fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64, degenerate: bool) -> Result<u64, KernelRefusal> {
2179        let domain = frag(curve.domain(), "edge_domain")?;
2180        let id = self.id();
2181        self.edges.push(EdgeRecord { id, curve, t0: domain[0], t1: domain[1], start_vertex_id: start, end_vertex_id: end, degenerate, name: None });
2182        Ok(id)
2183    }
2184
2185    /// A face from its surface and its loop: (edge, traversed forward?, pcurve
2186    /// in the traversal direction).
2187    fn face(&mut self, surface: NurbsSurface, coedges: Vec<(u64, bool, NurbsCurve)>) -> u64 {
2188        let mut records = Vec::with_capacity(coedges.len());
2189        for (edge, forward, pcurve) in coedges {
2190            let id = self.id();
2191            records.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2192        }
2193        let loop_id = self.id();
2194        let id = self.id();
2195        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: vec![LoopRecord { id: loop_id, coedges: records }], name: None });
2196        id
2197    }
2198
2199    /// A face from its surface and its loops, the outer one first.
2200    fn face_loops(&mut self, surface: NurbsSurface, loops: Vec<Vec<(u64, bool, NurbsCurve)>>) -> u64 {
2201        let mut records = Vec::with_capacity(loops.len());
2202        for coedges in loops {
2203            let mut list = Vec::with_capacity(coedges.len());
2204            for (edge, forward, pcurve) in coedges {
2205                let id = self.id();
2206                list.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2207            }
2208            let id = self.id();
2209            records.push(LoopRecord { id, coedges: list });
2210        }
2211        self.holes += records.len().saturating_sub(1);
2212        let id = self.id();
2213        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: records, name: None });
2214        id
2215    }
2216
2217    fn solid(mut self) -> BrepSolid {
2218        let shell = self.id();
2219        let id = self.id();
2220        // One shell: V − E + F = 2 − 2g (every face one loop; a pole's
2221        // degenerate edge is not counted, as the validator counts).
2222        let edges = self.edges.iter().filter(|e| !e.degenerate).count() as i64;
2223        // A face with holes counts once for each loop beyond its first less.
2224        let euler = self.vertices.len() as i64 - edges + self.faces.len() as i64 - self.holes as i64;
2225        let genus = (2 - euler) / 2;
2226        BrepSolid {
2227            mass_properties_cache: Default::default(),
2228            id,
2229            vertices: self.vertices,
2230            edges: self.edges,
2231            shells: vec![ShellRecord { id: shell, faces: self.faces }],
2232            genus,
2233            kind: Default::default(),
2234            cells: Default::default(),
2235        }
2236    }
2237}
2238
2239/// The whole sweep of `tool` along `motion` (a single screw, turn or slide),
2240/// its two end positions included.
2241pub fn sweep_solid(tool: &SolidTool, motion: &SolidMotion) -> Result<BrepSolid, KernelRefusal> {
2242    sweep_with(&Screw::from_motion(motion)?, tool)
2243}
2244
2245fn sweep_with(screw: &Screw, tool: &SolidTool) -> Result<BrepSolid, KernelRefusal> {
2246    let screw = *screw;
2247    if let SolidTool::Revolved { meridian, .. } = tool {
2248        refuse_elliptic(meridian)?;
2249    }
2250    if let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool {
2251        if let Some(body) = ball_across_axis(&screw, *axis_origin, *axis_direction, meridian)? {
2252            return Ok(body);
2253        }
2254    }
2255    if let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool {
2256        if ring_fold::ring_fold_on() {
2257            if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() {
2258                if ((end - start).abs() - TAU).abs() < 1e-12 {
2259                    let w = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
2260                    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
2261                    if let Some(body) = ring_fold::ring_slid_past_fold(&screw, *axis_origin, w, u1, w.cross(u1), *centre, *radius)? {
2262                        return Ok(body);
2263                    }
2264                }
2265            }
2266        }
2267        if let Some(body) = flat_ring(&screw, *axis_origin, *axis_direction, *radial, meridian)? {
2268            return Ok(body);
2269        }
2270        if let Some(body) = rod_across_axis(&screw, *axis_origin, *axis_direction, meridian)? {
2271            return Ok(body);
2272        }
2273    }
2274    if let SolidTool::Polyhedron { vertices, faces } = tool {
2275        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);
2276        if whole {
2277            return whole_turn_shadow(&screw, vertices, faces);
2278        }
2279    }
2280    let split = match tool {
2281        SolidTool::Polyhedron { vertices, faces } => split_polyhedron(&screw, vertices, faces)?,
2282        SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } => {
2283            split_revolved(&screw, *axis_origin, *axis_direction, *radial, meridian)?
2284        }
2285    };
2286    let grazing = split.grazing()?;
2287    // A tool slid along its own axis has no grazing curve: its sliding sides
2288    // join its back at the start to its front at the end.
2289    if grazing.is_empty() && split.slide_sides.is_empty() {
2290        return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
2291    }
2292    let times = row_times(&screw);
2293    let last = times.len() - 1;
2294    let mut shell = Shell::new();
2295    // Vertices and edges at the row times (0 and `last` are the end positions),
2296    // made on demand.
2297    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
2298    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
2299    let mut at_time = |shell: &mut Shell, j: usize, p: usize| -> u64 {
2300        *vertex_at.entry((j, p)).or_insert_with(|| shell.vertex(screw.apply(times[j], split.points[p])))
2301    };
2302    let mut time_edge = |shell: &mut Shell, j: usize, c: usize, vertex: &mut dyn FnMut(&mut Shell, usize, usize) -> u64| -> Result<u64, KernelRefusal> {
2303        if let Some(&edge) = edge_at.get(&(j, c)) {
2304            return Ok(edge);
2305        }
2306        let curve = &split.curves[c];
2307        let (a, b) = (vertex(shell, j, curve.start), vertex(shell, j, curve.end));
2308        let edge = shell.edge(screw.move_curve(times[j], &curve.curve)?, a, b, curve.degenerate)?;
2309        edge_at.insert((j, c), edge);
2310        Ok(edge)
2311    };
2312    // Caps: the back at t0, the front at t1.
2313    for cap in &split.caps {
2314        let j = if cap.front { last } else { 0 };
2315        let surface = screw.move_surface(times[j], &cap.surface)?;
2316        let mut coedges = Vec::with_capacity(cap.coedges.len());
2317        for (c, forward, pcurve) in &cap.coedges {
2318            let edge = time_edge(&mut shell, j, *c, &mut at_time)?;
2319            coedges.push((edge, *forward, pcurve.clone()));
2320        }
2321        shell.face(surface, coedges);
2322    }
2323    // Walls, a row at a time. The back cap at t0 runs K's curve with the back
2324    // on its left, so the wall beside it runs the other way: u along the curve
2325    // that way, v from the row's start to its end, the loop (u0,0) (u1,0)
2326    // (u1,1) (u0,1).
2327    // The paths of K's corners, a row at a time: (row, point) -> edge.
2328    let mut orbit_at: HashMap<(usize, usize), u64> = HashMap::new();
2329    for row in 0..last {
2330        let (ta, tb) = (times[row], times[row + 1]);
2331        let segments = carry_segments(&screw, ta, tb);
2332        let knots_v = carry_knots(segments);
2333        let mut orbits: HashMap<usize, u64> = HashMap::new();
2334        for &(c, _) in &grazing {
2335            for r in [split.curves[c].start, split.curves[c].end] {
2336                if orbits.contains_key(&r) {
2337                    continue;
2338                }
2339                let (v0, v1) = (at_time(&mut shell, row, r), at_time(&mut shell, row + 1, r));
2340                let edge = shell.edge(carry_curve(&screw, split.points[r], ta, tb, segments)?, v0, v1, false)?;
2341                orbits.insert(r, edge);
2342                orbit_at.insert((row, r), edge);
2343            }
2344        }
2345        for &(c, back_forward) in &grazing {
2346            let tool_curve = &split.curves[c];
2347            let along = if back_forward { frag(tool_curve.curve.reversed(), "reversed")? } else { tool_curve.curve.clone() };
2348            let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
2349            let mut rows = Vec::with_capacity(along.control_points.len());
2350            for p in &along.control_points {
2351                let x = frag(p.point(), "control_point")?;
2352                rows.push(carry_points(&screw, x, ta, tb, segments).into_iter().map(|q| Vec4::from_point(q, p.w)).collect::<Vec<_>>());
2353            }
2354            let surface = frag(NurbsSurface::new(along.degree, 5, along.knots.clone(), knots_v.clone(), rows), "wall")?;
2355            let [u0, u1] = frag(along.domain(), "domain")?;
2356            let bottom = time_edge(&mut shell, row, c, &mut at_time)?;
2357            let top = time_edge(&mut shell, row + 1, c, &mut at_time)?;
2358            let coedges = vec![
2359                (bottom, !back_forward, uv_line([u0, 0.0], [u1, 0.0])?),
2360                (orbits[&to], true, uv_line([u1, 0.0], [u1, 1.0])?),
2361                (top, back_forward, uv_line([u1, 1.0], [u0, 1.0])?),
2362                (orbits[&from], false, uv_line([u0, 1.0], [u0, 0.0])?),
2363            ];
2364            shell.face(surface, coedges);
2365        }
2366    }
2367    // Sliding ends: each rim arc where its neighbour's cap sits (back at t0,
2368    // front at t1), joined by the paths of the points where that changes.
2369    // Faces the tool slides within: the one-pass probe stands further off them.
2370    let mut sliding: std::collections::HashSet<u64> = std::collections::HashSet::new();
2371    let side_of: HashMap<usize, bool> = split.caps.iter().flat_map(|cap| cap.coedges.iter().map(move |&(c, _, _)| (c, cap.front))).collect();
2372    for slide in &split.slides {
2373        let centre = screw.apply(times[0], slide.centre);
2374        let u = screw.apply(times[0], slide.centre.add(slide.u)).sub(centre);
2375        let v = screw.apply(times[0], slide.centre.add(slide.v)).sub(centre);
2376        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2377            match side_of.get(&c) {
2378                Some(true) => Ok(last),
2379                Some(false) => Ok(0),
2380                None => Err(refuse("revolved_grazing", "a sliding end has no face beside its rim".into())),
2381            }
2382        };
2383        let mut coedges = Vec::new();
2384        let mut corners: Vec<Vec3> = Vec::new();
2385        let push = |coedges: &mut Vec<(u64, bool, NurbsCurve)>, corners: &mut Vec<Vec3>, edge: u64, forward: bool, curve: &NurbsCurve| -> Result<(), KernelRefusal> {
2386            let [d0, d1] = frag(curve.domain(), "domain")?;
2387            for k in 0..=8 {
2388                corners.push(frag(curve.evaluate(d0 + (d1 - d0) * k as f64 / 8.0), "slide")?);
2389            }
2390            coedges.push((edge, forward, plane_pcurve(centre, u, v, curve, forward)?));
2391            Ok(())
2392        };
2393        for (index, &(c, forward)) in slide.rim.iter().enumerate() {
2394            let j = row_of(c)?;
2395            let edge = time_edge(&mut shell, j, c, &mut at_time)?;
2396            push(&mut coedges, &mut corners, edge, forward, &screw.move_curve(times[j], &split.curves[c].curve)?)?;
2397            // On to the next arc's time along the path of the point between them.
2398            let (next, _) = slide.rim[(index + 1) % slide.rim.len()];
2399            let next_j = row_of(next)?;
2400            if next_j == j {
2401                continue;
2402            }
2403            let point = if forward { split.curves[c].end } else { split.curves[c].start };
2404            let rows: Vec<usize> = if next_j > j { (j..next_j).collect() } else { (next_j..j).rev().collect() };
2405            for row in rows {
2406                let Some(&orbit) = orbit_at.get(&(row, point)) else {
2407                    return Err(refuse("revolved_grazing", "a sliding end's rim changes side where no grazing curve meets it".into()));
2408                };
2409                let (ta, tb) = (times[row], times[row + 1]);
2410                let curve = carry_curve(&screw, split.points[point], ta, tb, carry_segments(&screw, ta, tb))?;
2411                push(&mut coedges, &mut corners, orbit, next_j > j, &curve)?;
2412            }
2413        }
2414        sliding.insert(shell.face(plane_patch(centre, u, v, &corners)?, coedges));
2415    }
2416    // Sliding cylinders: from the start rim where its neighbour sits to the
2417    // end rim where its neighbour sits, in halves seamed along generators.
2418    for side in &split.slide_sides {
2419        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2420            match side_of.get(&c) {
2421                Some(true) => Ok(last),
2422                Some(false) => Ok(0),
2423                None => Err(refuse("revolved_grazing", "a sliding side has no face beside its rim".into())),
2424            }
2425        };
2426        let origin = screw.apply(times[0], side.origin);
2427        let w = screw.apply(times[0], side.origin.add(side.w)).sub(origin);
2428        let rows: Vec<[usize; 2]> = side.patches.iter().map(|patch| Ok([row_of(patch.2)?, row_of(patch.3)?])).collect::<Result<_, KernelRefusal>>()?;
2429        if rows.iter().any(|r| *r != rows[0]) {
2430            return Err(refuse("revolved_grazing", "a sliding side's rim changes side along it".into()));
2431        }
2432        let [jb, ja] = rows[0];
2433        // Seams: the generator at each patch's start angle, rim point to rim point.
2434        let mut seams = Vec::with_capacity(side.patches.len());
2435        for patch in &side.patches {
2436            let (a, b) = (at_time(&mut shell, jb, patch.4[0]), at_time(&mut shell, ja, patch.4[1]));
2437            let line = frag(make_line(screw.apply(times[jb], split.points[patch.4[0]]), screw.apply(times[ja], split.points[patch.4[1]])), "seam")?;
2438            seams.push((shell.edge(line.clone(), a, b, false)?, line));
2439        }
2440        for (k, patch) in side.patches.iter().enumerate() {
2441            let surface = frag(make_revolution(origin, w, &seams[k].1, patch.1), "slide_side")?;
2442            let lower = time_edge(&mut shell, jb, patch.2, &mut at_time)?;
2443            let upper = time_edge(&mut shell, ja, patch.3, &mut at_time)?;
2444            let next = (k + 1) % side.patches.len();
2445            let face = shell.face(
2446                surface,
2447                vec![
2448                    (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
2449                    (seams[next].0, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
2450                    (upper, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
2451                    (seams[k].0, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
2452                ],
2453            );
2454            sliding.insert(face);
2455        }
2456    }
2457    let body = shell.solid();
2458    let issues = body.validate();
2459    if !issues.is_empty() {
2460        return Err(refuse("assembly", format!("the assembled sweep is not valid: {:?}", issues.first())));
2461    }
2462    check_single_pass(&screw, &split, &body, &sliding)?;
2463    Ok(body)
2464}
2465
2466/// A rod (a cylinder with flat ends) TURNED about a line that crosses its
2467/// axis squarely between its ends, if `meridian` is one and the motion such.
2468///
2469/// Arm by arm: the rod is its arm one way from the turn's axis and its arm
2470/// the other way, and sweeps what they sweep. At a height z (half-width
2471/// w = √(r² − z²)) an arm of length L is the rectangle 0 ≤ x ≤ L, |y| ≤ w,
2472/// which a circle about the turn's axis of radius ρ ≤ L meets in one arc
2473/// holding the arm's own direction, and beyond, out to √(L² + w²), in two
2474/// arcs ±[a, b] with a ≤ acos(L / √(L² + r²)). Turned by more than 2a, the
2475/// two arcs sweep the same angles as the arc [−b, b] they leave a gap in:
2476/// the arm with the gap filled, its points beyond its end within
2477/// √(L² + r²) of the crossing point (a cap of that ball). The filled arm
2478/// meets every circle in one arc holding its direction, so it sweeps itself
2479/// where it starts and where it stops and, between, its section by the half
2480/// plane at its direction turned. So the sweep is the union of the filled rod
2481/// (one solid of revolution about the rod's axis) at both ends of the turn
2482/// and the two arms' sections turned.
2483fn rod_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2484    if screw.frame.is_some() || screw.turns.is_some() || screw.omega == 0.0 || screw.c != 0.0 || screw.c2 != 0.0 {
2485        return Ok(None);
2486    }
2487    let Ok(w) = axis.normalized() else { return Ok(None) };
2488    // A rectangle against the axis: radius r from z0 to z1.
2489    let mut corners: Vec<[f64; 2]> = Vec::new();
2490    for piece in meridian {
2491        let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
2492        corners.push(*from);
2493        corners.push(*to);
2494    }
2495    if meridian.len() != 4 {
2496        return Ok(None);
2497    }
2498    let r = corners.iter().map(|c| c[0]).fold(0.0f64, f64::max);
2499    let (z0, z1) = corners.iter().map(|c| c[1]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), z| (lo.min(z), hi.max(z)));
2500    let scale = r.max(z0.abs()).max(z1.abs());
2501    let on = |a: f64, b: f64| (a - b).abs() <= 1e-12 * scale;
2502    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))) {
2503        return Ok(None);
2504    }
2505    // The turn's axis squarely across the rod's, between its ends.
2506    if w.dot(screw.e).abs() > 1e-12 {
2507        return Ok(None);
2508    }
2509    let offset = screw.a.sub(origin);
2510    let along = offset.dot(w);
2511    let foot = origin.add(w.scale(along));
2512    let apart = screw.a.sub(foot);
2513    if apart.sub(screw.e.scale(apart.dot(screw.e))).length() > 1e-12 * (scale + offset.length()) {
2514        return Ok(None);
2515    }
2516    if !(along > z0 + 1e-9 * scale && along < z1 - 1e-9 * scale) {
2517        return Ok(None);
2518    }
2519    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
2520    let arms = [z1 - along, along - z0];
2521    let gap = arms.iter().map(|l| (l / l.hypot(r)).acos()).fold(0.0f64, f64::max);
2522    if !(theta > 2.0 * gap * (1.0 + 1e-9) && theta < TAU * (1.0 - 1e-9)) {
2523        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()));
2524    }
2525    let arc = |centre: Vec3, from: Vec3, normal: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
2526        let surface = frag(make_revolution(centre, normal, &frag(make_line(from, from.add(normal)), "line")?, angle), "rod_across")?;
2527        frag(surface.iso_curve_v(0.0), "rod_across")
2528    };
2529    let line = |a: Vec3, b: Vec3| frag(make_line(a, b), "rod_across");
2530    // At one time: the crossing point, the rod's direction and the turn's.
2531    let filled_at = |t: f64| -> Result<BrepSolid, KernelRefusal> {
2532        let o = screw.apply(t, foot);
2533        let x = screw.apply(t, foot.add(w)).sub(o);
2534        let up = screw.e;
2535        let at = |rho: f64, s: f64| o.add(up.scale(rho)).add(x.scale(s));
2536        let n = up.cross(x);
2537        let (far_plus, far_minus) = (arms[0].hypot(r), arms[1].hypot(r));
2538        let profile = [
2539            arc(o, at(0.0, -far_minus), n, r.atan2(arms[1]))?,
2540            line(at(r, -arms[1]), at(r, arms[0]))?,
2541            arc(o, at(r, arms[0]), n, r.atan2(arms[0]))?,
2542            line(at(0.0, far_plus), at(0.0, -far_minus))?,
2543        ];
2544        frag(crate::revolve_profile_brep(&profile, o, x, TAU), "rod_across")
2545    };
2546    let o = screw.apply(screw.t0, foot);
2547    let x = screw.apply(screw.t0, foot.add(w)).sub(o);
2548    let turn_axis = screw.e.scale(screw.omega.signum());
2549    let section = |direction: Vec3, length: f64| -> Result<BrepSolid, KernelRefusal> {
2550        let at = |rho: f64, z: f64| o.add(direction.scale(rho)).add(screw.e.scale(z));
2551        let half = (r / length.hypot(r)).asin();
2552        let profile = [
2553            line(at(0.0, -r), at(length, -r))?,
2554            arc(o, at(length, -r), direction.cross(screw.e), 2.0 * half)?,
2555            line(at(length, r), at(0.0, r))?,
2556            line(at(0.0, r), at(0.0, -r))?,
2557        ];
2558        frag(crate::revolve_profile_brep(&profile, o, turn_axis, theta), "rod_across")
2559    };
2560    let parts = [filled_at(screw.t0)?, filled_at(screw.t1)?, section(x, arms[0])?, section(x.scale(-1.0), arms[1])?];
2561    crate::boolean_operation_nary(&parts, crate::BooleanOperation::Union).map(Some)
2562}
2563
2564/// A ring (or another tool with a hole about its axis walled straight
2565/// through) lying flat to its motion (a turn about an axis parallel to the
2566/// tool's, a slide square to it), if `meridian` is one and the motion such.
2567///
2568/// Every point then moves in its own plane square to the ring's axis, where
2569/// the ring's section is an annulus. The tube passes over where the hole was,
2570/// so the sweep does not pass each point once; but an annulus sweeps what its
2571/// filled disc sweeps as soon as it travels far enough that no point stays in
2572/// the hole from start to end (the hole at the start and at the end share
2573/// nothing: travel beyond the hole's greatest width, the tube's centre
2574/// circle). So the ring sweeps what the FILLED ring sweeps: a tool with a
2575/// half-round rim and flat faces, which is swept whole. A whole turn sweeps
2576/// the solid of revolution of that tool's shadow about the turn's axis.
2577fn flat_ring(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2578    if screw.frame.is_some() || screw.turns.is_some() || screw.c2 != 0.0 {
2579        return Ok(None);
2580    }
2581    let Ok(w) = axis.normalized() else { return Ok(None) };
2582    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 };
2583    if !flat {
2584        return Ok(None);
2585    }
2586    // The holed tool: a torus (`torus`: its tube), or straight-sided pieces
2587    // whose hole is one upright wall from the tool's top to its bottom.
2588    // `big`: half the hole's greatest width. `filled_meridian`: the tool
2589    // with its hole closed, flat across at its top and bottom.
2590    let (big, level, torus, filled_meridian): (f64, f64, Option<f64>, Vec<OutlinePiece>) = match meridian {
2591        [OutlinePiece::Arc { centre, radius, start, end }] => {
2592            let (big, tube, level) = (centre[0], *radius, centre[1]);
2593            if ((end - start).abs() - TAU).abs() >= 1e-12 || big <= tube {
2594                return Ok(None);
2595            }
2596            (
2597                big,
2598                level,
2599                Some(tube),
2600                vec![
2601                    OutlinePiece::Line { from: [0.0, level - tube], to: [big, level - tube] },
2602                    OutlinePiece::Arc { centre: [big, level], radius: tube, start: -0.5 * PI, end: 0.5 * PI },
2603                    OutlinePiece::Line { from: [big, level + tube], to: [0.0, level + tube] },
2604                    OutlinePiece::Line { from: [0.0, level + tube], to: [0.0, level - tube] },
2605                ],
2606            )
2607        }
2608        pieces => {
2609            let mut ends: Vec<([f64; 2], [f64; 2])> = Vec::with_capacity(pieces.len());
2610            for piece in pieces {
2611                let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
2612                ends.push((*from, *to));
2613            }
2614            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);
2615            let inner = ends.iter().flat_map(|(a, b)| [a[0], b[0]]).fold(f64::INFINITY, f64::min);
2616            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)));
2617            if ends.len() < 3 || inner <= 1e-9 * scale {
2618                return Ok(None);
2619            }
2620            let walls: Vec<usize> = (0..ends.len())
2621                .filter(|&k| {
2622                    let (a, b) = ends[k];
2623                    (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
2624                })
2625                .collect();
2626            let [wall] = walls.as_slice() else { return Ok(None) };
2627            let (from, to) = ends[*wall];
2628            // From the wall's end round the outside back to its start, then
2629            // across to the axis and along it.
2630            let mut filled = vec![OutlinePiece::Line { from: [0.0, to[1]], to }];
2631            for k in 1..pieces.len() {
2632                filled.push(pieces[(wall + k) % pieces.len()].clone());
2633            }
2634            filled.push(OutlinePiece::Line { from, to: [0.0, from[1]] });
2635            filled.push(OutlinePiece::Line { from: [0.0, from[1]], to: [0.0, to[1]] });
2636            (inner, 0.5 * (low + high), None, filled)
2637        }
2638    };
2639    let centre0 = origin.add(w.scale(level));
2640    let filled = SolidTool::Revolved { axis_origin: origin, axis_direction: w, radial, meridian: filled_meridian };
2641    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());
2642    if screw.omega == 0.0 {
2643        if screw.c.abs() * (screw.t1 - screw.t0) <= 2.0 * big * (1.0 + 1e-9) {
2644            let Some(tube) = torus else { return Err(short()) };
2645            // Short of its hole: what stays open, all the way through, is the
2646            // lens the hole shares where the ring starts and where it stops.
2647            // The hole at one place: inside the ring's inner half, between
2648            // its top and bottom planes.
2649            let hole = |t: f64| -> Result<BrepSolid, KernelRefusal> {
2650                let o = screw.apply(t, centre0);
2651                let u = frag(radial.sub(w.scale(radial.dot(w))).normalized(), "ring_flat")?;
2652                let at = |rho: f64, z: f64| o.add(u.scale(rho)).add(w.scale(z));
2653                let n = w.cross(u);
2654                let from = at(big, -tube);
2655                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")?;
2656                let profile = [
2657                    frag(make_line(at(0.0, -tube), at(big, -tube)), "ring_flat")?,
2658                    inner,
2659                    frag(make_line(at(big, tube), at(0.0, tube)), "ring_flat")?,
2660                    frag(make_line(at(0.0, tube), at(0.0, -tube)), "ring_flat")?,
2661                ];
2662                frag(crate::revolve_profile_brep(&profile, o, w, TAU), "ring_flat")
2663            };
2664            let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
2665            let whole = sweep_with(screw, &filled)?;
2666            return crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract).map(Some);
2667        }
2668        return sweep_with(screw, &filled).map(Some);
2669    }
2670    // A turn: the ring's centre runs a circle of radius `reach` about the axis.
2671    let start_centre = screw.apply(screw.t0, centre0);
2672    let from_axis = start_centre.sub(screw.a);
2673    let across = from_axis.sub(screw.e.scale(from_axis.dot(screw.e)));
2674    let reach = across.length();
2675    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
2676    if theta >= TAU * (1.0 - 1e-12) {
2677        let Some(tube) = torus else {
2678            return Err(refuse("ring_flat", "a whole turn of a holed tool in its own plane is swept for a ring only".into()));
2679        };
2680        if reach <= (big + tube) * (1.0 + 1e-9) {
2681            return Err(refuse("ring_flat", "a ring turned a whole turn in its own plane reaches the turn's axis".into()));
2682        }
2683        let out = frag(across.normalized(), "ring_flat")?;
2684        let foot = start_centre.sub(across);
2685        let at = |rho: f64, z: f64| foot.add(out.scale(rho)).add(screw.e.scale(z));
2686        let half_round = |centre: Vec3, from: Vec3| -> Result<NurbsCurve, KernelRefusal> {
2687            let n = out.cross(screw.e);
2688            let surface = frag(make_revolution(centre, n, &frag(make_line(from, from.add(n)), "line")?, PI), "ring_flat")?;
2689            frag(surface.iso_curve_v(0.0), "ring_flat")
2690        };
2691        let profile = [
2692            frag(make_line(at(reach - big, -tube), at(reach + big, -tube)), "ring_flat")?,
2693            half_round(at(reach + big, 0.0), at(reach + big, -tube))?,
2694            frag(make_line(at(reach + big, tube), at(reach - big, tube)), "ring_flat")?,
2695            half_round(at(reach - big, 0.0), at(reach - big, tube))?,
2696        ];
2697        return frag(crate::revolve_profile_brep(&profile, foot, screw.e, TAU), "ring_flat").map(Some);
2698    }
2699    let covered = if theta >= PI { big < reach } else { reach * (0.5 * theta).sin() > big * (1.0 + 1e-9) };
2700    if !covered {
2701        return Err(short());
2702    }
2703    sweep_with(screw, &filled).map(Some)
2704}
2705
2706/// The sweep of `tool` along `motion`, where it lies in `clip` (the caller
2707/// cuts a workpiece inside that region). A TURN about the clip's own axis
2708/// whose two end positions stay outside the clip's wedge covers the wedge
2709/// wholly with the tool's shadow in (ρ, z): that shadow, turned over the wedge,
2710/// is the sweep there (a convex polyhedron's shadow is bounded by conic arcs
2711/// from its edges and straight lines from its faces, so every surface is
2712/// exact); a turn about that axis whose ends reach the wedge is refused. A
2713/// screw or turn about the region's axis whose tool reaches far past the
2714/// region's radius sweeps only the tool's part that can reach it (see
2715/// `trim_to_clip`). Any other motion gets the whole sweep ([`sweep_solid`]).
2716pub fn sweep_solid_clipped(tool: &SolidTool, motion: &SolidMotion, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
2717    let screw = Screw::from_motion(motion)?;
2718    if let (SolidTool::Polyhedron { vertices, faces }, Some(wedge)) = (tool, clip.angle) {
2719        let axis = clip.axis_direction.normalized().map_err(|_| input("clip_axis", "the clip's axis has no direction".into()))?;
2720        let same_axis = screw.c == 0.0 && screw.c2 == 0.0
2721            && screw.e.cross(axis).length() < 1e-12
2722            && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
2723        if same_axis {
2724            return turn_shadow(&screw, vertices, faces, clip, axis, wedge);
2725        }
2726    }
2727    if let SolidTool::Polyhedron { vertices, faces } = tool {
2728        if let Some((vertices, faces)) = trim_to_clip(&screw, vertices, faces, clip)? {
2729            return sweep_solid(&SolidTool::Polyhedron { vertices, faces }, motion);
2730        }
2731    }
2732    sweep_solid(tool, motion)
2733}
2734
2735/// The sweep of `tool` along a turn whose rise grows as it turns, where it lies
2736/// in `clip` (as [`sweep_solid_clipped`]). Its front and back are those at
2737/// the middle of the motion; a tool whose faces change side along it is refused.
2738pub fn sweep_solid_rising(tool: &SolidTool, motion: &RisingTurn, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
2739    let screw = Screw::from_rising(motion)?;
2740    let SolidTool::Polyhedron { vertices, faces } = tool else {
2741        return Err(refuse("rising_tool", "a growing rise sweeps a polyhedron only".into()));
2742    };
2743    let (vertices, faces) = trim_to_clip(&screw, vertices, faces, clip)?.unwrap_or_else(|| (vertices.clone(), faces.clone()));
2744    sweep_with(&screw, &SolidTool::Polyhedron { vertices, faces })
2745}
2746
2747/// The sweep of `tool` along `motion` as parts whose union it is (a caller cuts
2748/// a workpiece by all of them). One part where the whole sweep passes once. A
2749/// convex polyhedron whose sweep folds over itself (a face facing away from a
2750/// screw's or turn's axis grazes along a line inside it, and the faces beyond
2751/// that line are swept over again) is split by the plane through the axis and
2752/// that line: each half grazes that face only along its cut edge, and is swept
2753/// whole. The halves' walls share cylinders about the axis.
2754pub fn sweep_solid_parts(tool: &SolidTool, motion: &SolidMotion) -> Result<Vec<BrepSolid>, KernelRefusal> {
2755    let folded = match sweep_solid(tool, motion) {
2756        Ok(body) => return Ok(vec![body]),
2757        Err(error) if refused_as(&error) == Some("folds") => error,
2758        Err(error) => return Err(error),
2759    };
2760    let SolidTool::Polyhedron { vertices, faces } = tool else { return Err(folded) };
2761    let screw = Screw::from_motion(motion)?;
2762    if screw.omega == 0.0 {
2763        return Err(folded);
2764    }
2765    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);
2766    let mut planes: Vec<(Vec3, f64)> = Vec::new();
2767    for face in faces {
2768        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
2769        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
2770        if n.dot(p.sub(centroid)) < 0.0 {
2771            n = n.scale(-1.0);
2772        }
2773        planes.push((n, n.dot(p)));
2774    }
2775    // A face square to the axis' plane through it (its normal square to the
2776    // axis) graze along the line through its foot from the axis; it folds if
2777    // it faces away from the axis and that line crosses it.
2778    for (n, d) in planes.clone() {
2779        if n.dot(screw.e).abs() > 1e-12 {
2780            continue;
2781        }
2782        let foot = screw.a.add(n.scale(d - n.dot(screw.a)));
2783        let radial = foot.sub(screw.a).sub(screw.e.scale(foot.sub(screw.a).dot(screw.e)));
2784        if radial.dot(n) <= 0.0 {
2785            continue; // faces the axis: its grazing line is the sweep's inner wall
2786        }
2787        let cut = match screw.e.cross(radial).normalized() {
2788            Ok(m) => m,
2789            Err(_) => continue,
2790        };
2791        let offset = cut.dot(screw.a);
2792        let mut parts = Vec::with_capacity(2);
2793        for sense in [1.0, -1.0] {
2794            let mut half = planes.clone();
2795            half.push((cut.scale(sense), offset * sense));
2796            let (corners, loops) = polyhedron_of_planes(&half)?;
2797            if corners.len() < 4 || loops.len() < 4 {
2798                parts.clear();
2799                break;
2800            }
2801            match sweep_solid(&SolidTool::Polyhedron { vertices: corners, faces: loops }, motion) {
2802                Ok(body) => parts.push(body),
2803                Err(_) => {
2804                    parts.clear();
2805                    break;
2806                }
2807            }
2808        }
2809        if parts.len() == 2 {
2810            return Ok(parts);
2811        }
2812    }
2813    Err(folded)
2814}
2815
2816/// A screw or turn about the clip's axis maps the clip's cylinder (radius
2817/// ≤ R) onto itself, so inside it the sweep of the tool is the sweep of any
2818/// part of the tool holding the tool's part inside the cylinder. A tool
2819/// reaching far past it (a bar pointing at the axis) is replaced by its part
2820/// inside the prism over the shadow's piece of a slightly larger disc, with
2821/// that disc's arc replaced by the two tangents at its ends: those faces graze
2822/// only along their own end edges, where the far ends of a long tool would
2823/// fold the sweep over itself. None when the tool needs no trim.
2824fn trim_to_clip(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip) -> Result<Option<(Vec<Vec3>, Vec<Vec<usize>>)>, KernelRefusal> {
2825    let Ok(axis) = clip.axis_direction.normalized() else { return Ok(None) };
2826    let same_axis = screw.omega != 0.0
2827        && screw.e.cross(axis).length() < 1e-12
2828        && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
2829    if !same_axis || !clip.radius[1].is_finite() {
2830        return Ok(None);
2831    }
2832    let ez = axis;
2833    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))?;
2834    let ey = ez.cross(ex);
2835    let flat = |p: Vec3| {
2836        let r = p.sub(clip.axis_origin);
2837        [r.dot(ex), r.dot(ey)]
2838    };
2839    let radius = clip.radius[1] * 1.02;
2840    let shadow: Vec<[f64; 2]> = vertices.iter().map(|&p| flat(p)).collect();
2841    if shadow.iter().all(|q| q[0].hypot(q[1]) <= radius) {
2842        return Ok(None);
2843    }
2844    // The shadow's convex hull, counter-clockwise.
2845    let mut points = shadow.clone();
2846    points.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
2847    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]);
2848    let mut hull: Vec<[f64; 2]> = Vec::new();
2849    for pass in 0..2 {
2850        let start = hull.len();
2851        let ordered: Vec<[f64; 2]> = if pass == 0 { points.clone() } else { points.iter().rev().copied().collect() };
2852        for p in ordered {
2853            while hull.len() >= start + 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
2854                hull.pop();
2855            }
2856            hull.push(p);
2857        }
2858        hull.pop();
2859    }
2860    // Where the hull's boundary leaves and re-enters the disc.
2861    let m = hull.len();
2862    let inside = |q: [f64; 2]| q[0].hypot(q[1]) <= radius;
2863    // Leave a tool that does not reach the disc, or wraps the axis.
2864    let mut nearest = f64::INFINITY;
2865    let mut wraps = true;
2866    for k in 0..m {
2867        let (a, b) = (hull[k], hull[(k + 1) % m]);
2868        let d = [b[0] - a[0], b[1] - a[1]];
2869        let t = (-(a[0] * d[0] + a[1] * d[1]) / (d[0] * d[0] + d[1] * d[1])).clamp(0.0, 1.0);
2870        nearest = nearest.min((a[0] + d[0] * t).hypot(a[1] + d[1] * t));
2871        if cross(a, b, [0.0, 0.0]) < 0.0 {
2872            wraps = false;
2873        }
2874    }
2875    if wraps || nearest >= radius || (0..m).all(|k| inside(hull[k])) {
2876        return Ok(None);
2877    }
2878    let mut leave: Vec<f64> = Vec::new();
2879    let mut enter: Vec<f64> = Vec::new();
2880    for k in 0..m {
2881        let (a, b) = (hull[k], hull[(k + 1) % m]);
2882        let d = [b[0] - a[0], b[1] - a[1]];
2883        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);
2884        let disc = qb * qb - 4.0 * qa * qc;
2885        if disc <= 0.0 {
2886            continue;
2887        }
2888        for t in [(-qb - disc.sqrt()) / (2.0 * qa), (-qb + disc.sqrt()) / (2.0 * qa)] {
2889            if t > 0.0 && t < 1.0 {
2890                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
2891                let outward = 2.0 * (q[0] * d[0] + q[1] * d[1]) > 0.0;
2892                (if outward { &mut leave } else { &mut enter }).push(q[1].atan2(q[0]));
2893            }
2894        }
2895    }
2896    let ([a], [b]) = (leave.as_slice(), enter.as_slice()) else {
2897        return Err(refuse("clip_trim", "the tool's shadow leaves the clip's disc more than once".into()));
2898    };
2899    let width = (b - a).rem_euclid(TAU);
2900    if width >= 0.9 * PI {
2901        return Err(refuse("clip_trim", "the tool's shadow spans too much of the clip's circle to be trimmed".into()));
2902    }
2903    // Planes of the tool, and the two tangents (outward normals in the plane).
2904    let mut planes: Vec<(Vec3, f64)> = Vec::new();
2905    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);
2906    for face in faces {
2907        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
2908        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
2909        if n.dot(p.sub(centroid)) < 0.0 {
2910            n = n.scale(-1.0);
2911        }
2912        planes.push((n, n.dot(p)));
2913    }
2914    for angle in [*a, *b] {
2915        let n = ex.scale(angle.cos()).add(ey.scale(angle.sin()));
2916        planes.push((n, n.dot(clip.axis_origin) + radius));
2917    }
2918    Ok(Some(polyhedron_of_planes(&planes)?))
2919}
2920
2921/// The convex polyhedron {n · p ≤ d for every plane}: its corners (where three
2922/// planes meet inside all) and a face per plane that bounds it.
2923pub fn polyhedron_of_planes(planes: &[(Vec3, f64)]) -> Result<(Vec<Vec3>, Vec<Vec<usize>>), KernelRefusal> {
2924    let k = planes.len();
2925    let mut corners: Vec<Vec3> = Vec::new();
2926    let scale = planes.iter().map(|p| p.1.abs()).fold(1.0f64, f64::max);
2927    for i in 0..k {
2928        for j in i + 1..k {
2929            for l in j + 1..k {
2930                let (a, b, c) = (planes[i].0, planes[j].0, planes[l].0);
2931                let det = a.dot(b.cross(c));
2932                if det.abs() < 1e-12 {
2933                    continue;
2934                }
2935                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);
2936                if planes.iter().all(|(n, d)| n.dot(p) - d <= 1e-9 * scale) && !corners.iter().any(|q| q.sub(p).length() <= 1e-9 * scale) {
2937                    corners.push(p);
2938                }
2939            }
2940        }
2941    }
2942    let mut faces = Vec::new();
2943    for (n, d) in planes {
2944        let on: Vec<usize> = (0..corners.len()).filter(|&c| (n.dot(corners[c]) - d).abs() <= 1e-9 * scale).collect();
2945        if on.len() < 3 {
2946            continue;
2947        }
2948        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);
2949        let u = frag(corners[on[0]].sub(middle).normalized(), "face_axis")?;
2950        let v = n.cross(u);
2951        let mut ordered = on.clone();
2952        ordered.sort_by(|&p, &q| {
2953            let (rp, rq) = (corners[p].sub(middle), corners[q].sub(middle));
2954            rp.dot(v).atan2(rp.dot(u)).total_cmp(&rq.dot(v).atan2(rq.dot(u)))
2955        });
2956        faces.push(ordered);
2957    }
2958    Ok((corners, faces))
2959}
2960
2961fn turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip, axis: Vec3, wedge: [f64; 2]) -> Result<BrepSolid, KernelRefusal> {
2962    let ez = axis;
2963    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()))?;
2964    let ey = ez.cross(ex);
2965    // Turning by ω t about e = ±ez moves angles about ez by ±ω t.
2966    let rate = screw.omega * screw.e.dot(ez).signum();
2967    let local = |p: Vec3| {
2968        let r = p.sub(clip.axis_origin);
2969        [r.dot(ex), r.dot(ey), r.dot(ez)]
2970    };
2971    let corners: Vec<[f64; 3]> = vertices.iter().map(|&p| local(p)).collect();
2972    // The tool's angular extent about the axis (its corners'; the tool must
2973    // keep off the axis, so its shadow on the plane misses the origin).
2974    let mid = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
2975    let mid_angle = mid[1].atan2(mid[0]);
2976    let angles: Vec<f64> = corners.iter().map(|c| mid_angle + (c[1].atan2(c[0]) - mid_angle + PI).rem_euclid(TAU) - PI).collect();
2977    let (low, high) = (angles.iter().copied().fold(f64::INFINITY, f64::min), angles.iter().copied().fold(f64::NEG_INFINITY, f64::max));
2978    if high - low >= PI {
2979        return Err(refuse("turn_shadow", "the tool reaches round the turn's axis".into()));
2980    }
2981    let (start, end) = (rate * screw.t0, rate * screw.t1);
2982    let (first, last) = if rate > 0.0 { (start, end) } else { (end, start) };
2983    let reference = 0.5 * (wedge[0] + wedge[1]);
2984    let near = |a: f64| reference + (a - reference + PI).rem_euclid(TAU) - PI;
2985    // Before the wedge at one end, after it at the other (angles taken near the wedge).
2986    let clear = near(high + first) < wedge[0] - 1e-9 && near(low + last) > wedge[1] + 1e-9 && (last - first) < TAU;
2987    if !clear {
2988        return Err(refuse("turn_shadow", "the turned tool's ends reach the clip's wedge; its sweep there is not its turned shadow".into()));
2989    }
2990    let profile = polyhedron_shadow(&corners, faces, false)?;
2991    // The profile in the half-plane at the wedge's start angle.
2992    let (c0, s0) = (wedge[0].cos(), wedge[0].sin());
2993    let world = |rho: f64, z: f64| clip.axis_origin.add(ez.scale(z)).add(ex.scale(rho * c0)).add(ey.scale(rho * s0));
2994    let mut curves = Vec::with_capacity(profile.len());
2995    for piece in &profile {
2996        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
2997        let curve = if points.len() == 2 {
2998            frag(make_line(frag(points[0].point(), "point")?, frag(points[1].point(), "point")?), "line")?
2999        } else {
3000            frag(NurbsCurve::new(2, vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points), "conic")?
3001        };
3002        curves.push(curve);
3003    }
3004    frag(crate::revolve_profile_brep(&curves, clip.axis_origin, ez, wedge[1] - wedge[0]), "turn_shadow")
3005}
3006
3007/// A convex polyhedron turned a whole turn (no advance): the solid of
3008/// revolution of its shadow {(ρ, z)} about the turn's axis, which may pass
3009/// through it. Its corners' paths bound it only where an edge is farthest
3010/// from the axis; an edge skew to the axis turns a hyperboloid.
3011fn whole_turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
3012    let ez = screw.e;
3013    let ex = frag(ez.perpendicular(), "turn_shadow")?;
3014    let ex = frag(ex.sub(ez.scale(ex.dot(ez))).normalized(), "turn_shadow")?;
3015    let ey = ez.cross(ex);
3016    let corners: Vec<[f64; 3]> = vertices
3017        .iter()
3018        .map(|&p| {
3019            let r = screw.apply(screw.t0, p).sub(screw.a);
3020            [r.dot(ex), r.dot(ey), r.dot(ez)]
3021        })
3022        .collect();
3023    let profile = polyhedron_shadow(&corners, faces, true)?;
3024    // A point of the outline on the axis to round-off is on it.
3025    let reach = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(0.0f64, f64::max);
3026    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 }));
3027    let mut curves = Vec::with_capacity(profile.len());
3028    // The outline's stretch along the axis, as one edge (it comes a piece per
3029    // corner height).
3030    let on_axis = |piece: &ShadowPiece| piece.iter().all(|&(rho, _, _)| rho.abs() <= 1e-10 * reach);
3031    let mut along: Option<(f64, f64)> = None;
3032    for piece in &profile {
3033        if on_axis(piece) {
3034            let (za, zb) = (piece[0].1, piece[piece.len() - 1].1);
3035            along = Some(match along {
3036                Some((from, _)) => (from, zb),
3037                None => (za, zb),
3038            });
3039            continue;
3040        }
3041        if let Some((from, to)) = along.take() {
3042            curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3043        }
3044        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
3045        let (first, last) = (frag(points[0].point(), "point")?, frag(points[points.len() - 1].point(), "point")?);
3046        if first.sub(last).length() <= 1e-12 * (1.0 + first.length()) {
3047            continue;
3048        }
3049        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")? };
3050        curves.push(curve);
3051    }
3052    if let Some((from, to)) = along.take() {
3053        curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3054    }
3055    frag(crate::revolve_profile_brep(&curves, screw.a, ez, TAU), "turn_shadow")
3056}
3057
3058/// One piece of the shadow's outline: a segment (two points) or a rational
3059/// quadratic arc (three, the middle with its weight), as (ρ, z, weight).
3060type ShadowPiece = Vec<(f64, f64, f64)>;
3061
3062/// The shadow {(ρ, z)} of a convex polyhedron (corners in the axis frame):
3063/// at each z its section is a convex polygon, the ρ it reaches an interval
3064/// from the section's nearest point to its farthest corner. The farthest is
3065/// always on an edge (ρ² = quadratic in z: a conic arc); the nearest is on a
3066/// face (ρ linear in z: a segment) or an edge.
3067///
3068/// `through`: the axis may pass through the tool (its nearest ρ is then 0 and
3069/// the outline runs along the axis there); refused otherwise.
3070fn polyhedron_shadow(corners: &[[f64; 3]], faces: &[Vec<usize>], through: bool) -> Result<Vec<ShadowPiece>, KernelRefusal> {
3071    let zs: Vec<f64> = corners.iter().map(|c| c[2]).collect();
3072    let (z_low, z_high) = (zs.iter().copied().fold(f64::INFINITY, f64::min), zs.iter().copied().fold(f64::NEG_INFINITY, f64::max));
3073    let scale = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(1.0f64, f64::max);
3074    // The hull's edges (from the faces' loops) and the faces beside each.
3075    let mut edge_faces: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
3076    for (f, face) in faces.iter().enumerate() {
3077        for k in 0..face.len() {
3078            let (i, j) = (face[k], face[(k + 1) % face.len()]);
3079            edge_faces.entry((i.min(j), i.max(j))).or_default().push(f);
3080        }
3081    }
3082    let mut edges: Vec<(usize, usize)> = edge_faces.keys().copied().collect();
3083    edges.sort_unstable();
3084    // Each face's plane in the axis frame: n · p = d.
3085    let planes: Vec<([f64; 3], f64)> = faces
3086        .iter()
3087        .map(|face| {
3088            let (a, b, c) = (corners[face[0]], corners[face[1]], corners[face[2]]);
3089            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]]);
3090            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]];
3091            (n, n[0] * a[0] + n[1] * a[1] + n[2] * a[2])
3092        })
3093        .collect();
3094    #[derive(Clone, Copy, PartialEq, Debug)]
3095    enum Source {
3096        /// The crossing of edge k.
3097        Edge(usize),
3098        /// The nearest point of face f's section line.
3099        Face(usize),
3100        /// The axis itself, where it passes through the tool.
3101        Axis,
3102    }
3103    let edge_at = |k: usize, z: f64| -> [f64; 2] {
3104        let (a, b) = (corners[edges[k].0], corners[edges[k].1]);
3105        let t = (z - a[2]) / (b[2] - a[2]);
3106        [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
3107    };
3108    let crossing = |z: f64| -> Vec<usize> {
3109        (0..edges.len()).filter(|&k| (corners[edges[k].0][2] - z) * (corners[edges[k].1][2] - z) < 0.0).collect()
3110    };
3111    let farthest = |z: f64| -> (Source, f64) {
3112        let mut best = (Source::Edge(0), f64::NEG_INFINITY);
3113        for k in crossing(z) {
3114            let p = edge_at(k, z);
3115            let r = p[0].hypot(p[1]);
3116            if r > best.1 {
3117                best = (Source::Edge(k), r);
3118            }
3119        }
3120        best
3121    };
3122    // The section polygon: edge crossings ordered by angle about their mean.
3123    let nearest = |z: f64| -> Result<(Source, f64), KernelRefusal> {
3124        let list = crossing(z);
3125        let points: Vec<[f64; 2]> = list.iter().map(|&k| edge_at(k, z)).collect();
3126        let m = points.len();
3127        if m < 3 {
3128            return Err(refuse("turn_shadow", "a section of the tool is not a polygon".into()));
3129        }
3130        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]);
3131        let mut order: Vec<usize> = (0..m).collect();
3132        order.sort_by(|&a, &b| {
3133            let (pa, pb) = (points[a], points[b]);
3134            (pa[1] - centre[1]).atan2(pa[0] - centre[0]).total_cmp(&(pb[1] - centre[1]).atan2(pb[0] - centre[0]))
3135        });
3136        let mut inside = true;
3137        let mut best = (Source::Edge(0), f64::INFINITY);
3138        for k in 0..m {
3139            let (ia, ib) = (order[k], order[(k + 1) % m]);
3140            let (a, b) = (points[ia], points[ib]);
3141            let d = [b[0] - a[0], b[1] - a[1]];
3142            if d[0] * (0.0 - a[1]) - d[1] * (0.0 - a[0]) < 0.0 {
3143                inside = false;
3144            }
3145            let length2 = d[0] * d[0] + d[1] * d[1];
3146            let t = -(a[0] * d[0] + a[1] * d[1]) / length2;
3147            let (source, r) = if t > 0.0 && t < 1.0 {
3148                let (ea, eb) = (edges[list[ia]], edges[list[ib]]);
3149                let shared = edge_faces[&ea].iter().find(|f| edge_faces[&eb].contains(f)).copied();
3150                let Some(face) = shared else {
3151                    return Err(refuse("turn_shadow", "a section side does not lie on one face".into()));
3152                };
3153                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
3154                (Source::Face(face), q[0].hypot(q[1]))
3155            } else {
3156                let q = if t <= 0.0 { a } else { b };
3157                (Source::Edge(list[if t <= 0.0 { ia } else { ib }]), q[0].hypot(q[1]))
3158            };
3159            if r < best.1 {
3160                best = (source, r);
3161            }
3162        }
3163        if inside {
3164            if !through {
3165                return Err(refuse("turn_shadow", "the turn's axis passes through the tool".into()));
3166            }
3167            return Ok((Source::Axis, 0.0));
3168        }
3169        Ok(best)
3170    };
3171    // ρ of a source at z, from its own geometry (smooth across the piece).
3172    let value = |source: Source, z: f64| -> f64 {
3173        match source {
3174            Source::Edge(k) => {
3175                let p = edge_at(k, z);
3176                p[0].hypot(p[1])
3177            }
3178            Source::Face(f) => {
3179                let (n, d) = planes[f];
3180                (d - n[2] * z).abs() / n[0].hypot(n[1])
3181            }
3182            Source::Axis => 0.0,
3183        }
3184    };
3185    // Breaks: corner heights, and where the farthest or nearest source changes.
3186    let mut heights: Vec<f64> = zs.clone();
3187    heights.sort_by(|a, b| a.total_cmp(b));
3188    heights.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * scale);
3189    let mut pieces_far: Vec<(f64, f64, Source)> = Vec::new();
3190    let mut pieces_near: Vec<(f64, f64, Source)> = Vec::new();
3191    for window in heights.windows(2) {
3192        let (za, zb) = (window[0], window[1]);
3193        let samples = 400;
3194        let inner = |k: usize| za + (zb - za) * (k as f64 + 0.5) / samples as f64;
3195        for near in [false, true] {
3196            let source_at = |z: f64| -> Result<Source, KernelRefusal> { Ok(if near { nearest(z)?.0 } else { farthest(z).0 }) };
3197            let mut runs: Vec<(f64, Source)> = vec![(za, source_at(inner(0))?)];
3198            for k in 1..samples {
3199                let (z0, z1) = (inner(k - 1), inner(k));
3200                let (s0, s1) = (source_at(z0)?, source_at(z1)?);
3201                // Two sources tied over the stretch (edges equally far from
3202                // the axis) are one piece of the outline.
3203                let tied = [z0, 0.5 * (z0 + z1), z1].iter().all(|&z| (value(s0, z) - value(s1, z)).abs() <= 1e-12 * scale);
3204                if s0 == s1 || tied {
3205                    continue;
3206                }
3207                // Where the source changes, by bisection (a side handing over
3208                // to its corner touches it, so their values do not cross).
3209                let (mut lo, mut hi) = (z0, z1);
3210                for _ in 0..200 {
3211                    let midz = 0.5 * (lo + hi);
3212                    if source_at(midz)? == s0 { lo = midz } else { hi = midz }
3213                }
3214                runs.push((0.5 * (lo + hi), s1));
3215            }
3216            let list = if near { &mut pieces_near } else { &mut pieces_far };
3217            for k in 0..runs.len() {
3218                let z_end = if k + 1 < runs.len() { runs[k + 1].0 } else { zb };
3219                list.push((runs[k].0, z_end, runs[k].1));
3220            }
3221        }
3222    }
3223    // Exact pieces: a pair's ρ(z) is a conic arc, a side's a segment.
3224    let piece = |source: Source, za: f64, zb: f64| -> Vec<ShadowPiece> {
3225        let (ra, rb) = (value(source, za), value(source, zb));
3226        if matches!(source, Source::Face(..) | Source::Axis) {
3227            return vec![vec![(ra, za, 1.0), (rb, zb, 1.0)]];
3228        }
3229        // ρ² = α z² + β z + γ; split so each arc turns little.
3230        let rho = |z: f64| value(source, z);
3231        // Differences kept inside the piece (an edge through the axis has a
3232        // corner in ρ at its end there).
3233        let (z_min, z_max) = (za.min(zb), za.max(zb));
3234        let slope = |z: f64| {
3235            let h = 1e-6 * (zb - za).abs().max(1e-300);
3236            let (zp, zm) = ((z + h).min(z_max), (z - h).max(z_min));
3237            (rho(zp) - rho(zm)) / (zp - zm)
3238        };
3239        let parts = 4;
3240        let mut out = Vec::new();
3241        for k in 0..parts {
3242            let (z0, z1) = (za + (zb - za) * k as f64 / parts as f64, za + (zb - za) * (k + 1) as f64 / parts as f64);
3243            let (a, b) = ((rho(z0), z0), (rho(z1), z1));
3244            // Straight (an edge meeting the axis): a segment.
3245            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);
3246            if bend <= 1e-12 * scale {
3247                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3248                continue;
3249            }
3250            let (ta, tb) = ((slope(z0), 1.0), (slope(z1), 1.0));
3251            // Tangent lines' intersection.
3252            let det = ta.0 * (-tb.1) - ta.1 * (-tb.0);
3253            if det.abs() < 1e-12 {
3254                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3255                continue;
3256            }
3257            let rhs = (b.0 - a.0, b.1 - a.1);
3258            let s = (rhs.0 * (-tb.1) - rhs.1 * (-tb.0)) / det;
3259            let c = (a.0 + ta.0 * s, a.1 + ta.1 * s);
3260            // Shoulder: the conic's point on the line from the chord's middle to c.
3261            let m = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
3262            let on = |u: f64| {
3263                let p = (m.0 + (c.0 - m.0) * u, m.1 + (c.1 - m.1) * u);
3264                p.0 - rho(p.1)
3265            };
3266            let (mut lo, mut hi) = (0.0, 1.0);
3267            let sign_lo = on(lo);
3268            for _ in 0..200 {
3269                let mid = 0.5 * (lo + hi);
3270                if (on(mid) > 0.0) == (sign_lo > 0.0) { lo = mid } else { hi = mid }
3271            }
3272            let u = 0.5 * (lo + hi);
3273            let weight = u / (1.0 - u);
3274            out.push(vec![(a.0, a.1, 1.0), (c.0, c.1, weight), (b.0, b.1, 1.0)]);
3275        }
3276        out
3277    };
3278    // Outline: up the near side, across the top, down the far side, across the bottom.
3279    let mut outline: Vec<ShadowPiece> = Vec::new();
3280    for &(za, zb, source) in &pieces_near {
3281        outline.extend(piece(source, za, zb));
3282    }
3283    let (near_top, far_top) = (value(pieces_near.last().expect("near").2, z_high), value(pieces_far.last().expect("far").2, z_high));
3284    if far_top - near_top > 1e-12 * scale {
3285        outline.push(vec![(near_top, z_high, 1.0), (far_top, z_high, 1.0)]);
3286    }
3287    for &(za, zb, source) in pieces_far.iter().rev() {
3288        for mut arc in piece(source, za, zb).into_iter().rev() {
3289            arc.reverse();
3290            outline.push(arc);
3291        }
3292    }
3293    let (near_bottom, far_bottom) = (value(pieces_near[0].2, z_low), value(pieces_far[0].2, z_low));
3294    if far_bottom - near_bottom > 1e-12 * scale {
3295        outline.push(vec![(far_bottom, z_low, 1.0), (near_bottom, z_low, 1.0)]);
3296    }
3297    // Snap consecutive ends together.
3298    for k in 0..outline.len() {
3299        let next = (k + 1) % outline.len();
3300        let end = *outline[k].last().expect("piece");
3301        outline[next][0] = (end.0, end.1, 1.0);
3302    }
3303    Ok(outline)
3304}
3305
3306/// A ball TURNED about an axis that passes through it. Its grazing circle (in
3307/// the plane of the axis and the centre) crosses the axis at two poles N and S;
3308/// the part beyond the axis turns inside the sweep, and near the axis the ends
3309/// overlap. So the sweep has three faces: the wall, the outer arc of that
3310/// circle turned (a spindle torus's outer part, pinched at N and S); the
3311/// ball's back at the start less the ball at the end; and its front at the end
3312/// less the ball at the start. The two caps meet along the far arc, from S to
3313/// N, of the circle where the two spheres meet. None when the motion or tool
3314/// is not of that kind.
3315fn ball_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
3316    let [OutlinePiece::Arc { centre, radius, start, end }, OutlinePiece::Line { .. }] = meridian else { return Ok(None) };
3317    let (centre, r) = (*centre, *radius);
3318    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 {
3319        return Ok(None);
3320    }
3321    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
3322    let centre_tool = origin.add(w.scale(centre[1]));
3323    let turned = screw.omega * (screw.t1 - screw.t0);
3324    if turned.abs() >= TAU - 1e-9 {
3325        return Ok(None);
3326    }
3327    let e = screw.e.scale(screw.omega.signum()); // the sense the ball turns about
3328    let c0 = screw.apply(screw.t0, centre_tool);
3329    let c1 = screw.apply(screw.t1, centre_tool);
3330    let foot = |c: Vec3| screw.a.add(e.scale(c.sub(screw.a).dot(e)));
3331    let rho = c0.sub(foot(c0)).length();
3332    if rho >= r * (1.0 - 1e-9) || rho <= 1e-9 * r {
3333        return Ok(None);
3334    }
3335    let h0 = frag(c0.sub(foot(c0)).normalized(), "radial")?;
3336    let height = (r * r - rho * rho).sqrt();
3337    let (north, south) = (foot(c0).add(e.scale(height)), foot(c0).sub(e.scale(height)));
3338    // An arc from `from` turned about `axis` through `centre` by `angle`.
3339    let arc = |about: Vec3, k: Vec3, from: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
3340        let surface = frag(make_revolution(about, k, &frag(make_line(from, from.add(k)), "line")?, angle), "arc")?;
3341        frag(surface.iso_curve_v(0.0), "arc")
3342    };
3343    // The outer arc of the grazing circle, S -> N through c0 + r h0: in the
3344    // (h0, e) plane about c0, from angle -α to α through 0, α = atan2(height, -ρ).
3345    let alpha = height.atan2(-rho);
3346    let outer = arc(c0, h0.cross(e), south, 2.0 * alpha)?;
3347    let wall = frag(make_revolution(screw.a, e, &outer, turned.abs()), "wall")?;
3348    let outer_end = frag(wall.iso_curve_u(1.0), "wall_end")?;
3349    // The far arc where the spheres meet, S -> N beyond the axis.
3350    let mid = c0.add(c1).scale(0.5);
3351    let towards = frag(mid.sub(foot(mid)).normalized(), "bisector")?;
3352    let rho_mid = mid.sub(foot(mid)).length();
3353    let beta = height.atan2(rho_mid); // S and N seen from mid, off the far direction
3354    // From S at angle β − π (in the (towards, e) plane about mid) down through
3355    // π to N at π − β: the decreasing sense, about e × towards.
3356    let meet = arc(mid, e.cross(towards), south, 2.0 * beta)?;
3357    {
3358        // The arc must pass beyond the axis (its middle on the far side).
3359        let [d0, d1] = frag(meet.domain(), "domain")?;
3360        let middle = frag(meet.evaluate(0.5 * (d0 + d1)), "middle")?;
3361        if middle.sub(foot(middle)).dot(towards) > 0.0 {
3362            return Err(refuse("ball_across_axis", "the spheres' common circle runs the wrong way round".into()));
3363        }
3364    }
3365    // A trimmed sphere cap: a chart whose poles and seam lie where the cap is not.
3366    let cap = |c: Vec3, inward: Vec3, side: Vec3, other: Vec3| -> Result<(NurbsSurface, Box<dyn Fn(Vec3) -> Vec3>), KernelRefusal> {
3367        // South pole just off the far end of the grazing circle, on the removed
3368        // side (inside the other end's ball); the seam crosses the grazing
3369        // circle beyond the axis only.
3370        let toward_south = frag(inward.add(side.scale(-0.3)).normalized(), "pole")?;
3371        let polar = toward_south.scale(-1.0);
3372        let seam = frag(side.sub(polar.scale(side.dot(polar))).normalized(), "seam")?;
3373        for k in 0..=64 {
3374            // The seam's part on the cap's side of the grazing circle must lie
3375            // inside the other ball (where the cap is not).
3376            let a = PI * k as f64 / 64.0;
3377            let q = c.add(polar.scale(-r * a.cos())).add(seam.scale(r * a.sin()));
3378            if q.sub(c).dot(side) < 0.0 && q.sub(other).length() >= r * (1.0 - 1e-9) {
3379                return Err(refuse("ball_across_axis", "no seam place for a cap".into()));
3380            }
3381        }
3382        let south_pole = c.sub(polar.scale(r));
3383        if south_pole.sub(other).length() >= r * (1.0 - 1e-6) {
3384            return Err(refuse("ball_across_axis", "no pole place for a cap".into()));
3385        }
3386        let generatrix = arc(c, polar.scale(-1.0).cross(seam), south_pole, PI)?;
3387        let surface = frag(make_revolution(c, polar, &generatrix, TAU), "cap")?;
3388        let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
3389        let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
3390        let around = polar.cross(seam);
3391        let inverse = move |x: Vec3| -> Vec3 {
3392            let d = x.sub(c).scale(1.0 / r);
3393            let latitude = d.dot(polar).clamp(-1.0, 1.0).asin();
3394            let longitude = d.dot(around).atan2(d.dot(seam)).rem_euclid(TAU);
3395            Vec3::new(
3396                crate::circle_angle_to_parameter(spans_u, TAU, longitude),
3397                crate::circle_angle_to_parameter(spans_v, PI, latitude + 0.5 * PI),
3398                0.0,
3399            )
3400        };
3401        Ok((surface, Box::new(inverse)))
3402    };
3403    let moving0 = e.cross(h0);
3404    let h1 = frag(c1.sub(foot(c1)).normalized(), "radial")?;
3405    let moving1 = e.cross(h1);
3406    // The back cap at the start (its removed part near c0 − r h0 on the back);
3407    // the front cap at the end.
3408    let (back, back_inverse) = cap(c0, h0.scale(-1.0), moving0.scale(1.0), c1)?;
3409    let (front, front_inverse) = cap(c1, h1.scale(-1.0), moving1.scale(-1.0), c0)?;
3410    let pcurve = |inverse: &dyn Fn(Vec3) -> Vec3, curve: &NurbsCurve, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
3411        let [d0, d1] = frag(curve.domain(), "domain")?;
3412        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
3413        let uv: Vec<Vec3> = ts.iter().map(|&t| curve.evaluate(t).map(|x| inverse(x))).collect::<Result<_, _>>().map_err(|e| refuse("pcurve", e))?;
3414        let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "cap_pcurve")?;
3415        if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
3416    };
3417    let mut shell = Shell::new();
3418    let (vn, vs) = (shell.vertex(north), shell.vertex(south));
3419    let k0 = shell.edge(outer.clone(), vs, vn, false)?;
3420    let k1 = shell.edge(outer_end.clone(), vs, vn, false)?;
3421    let c = shell.edge(meet.clone(), vs, vn, false)?;
3422    let ds = shell.edge(frag(make_line(south, south), "point")?, vs, vs, true)?;
3423    let dn = shell.edge(frag(make_line(north, north), "point")?, vn, vn, true)?;
3424    // Wall: u turns, v runs S -> N; outward needs v the other way round the
3425    // circle's normal, so test and pick the loop's sense.
3426    let wall_outward = {
3427        let p = frag(wall.evaluate(0.5, 0.5), "probe")?;
3428        let su = frag(wall.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(wall.evaluate(0.5 - 1e-6, 0.5), "probe")?);
3429        let sv = frag(wall.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(wall.evaluate(0.5, 0.5 - 1e-6), "probe")?);
3430        su.cross(sv).dot(p.sub(foot(p))) > 0.0
3431    };
3432    let [g0, g1] = frag(outer.domain(), "domain")?;
3433    let wall_loop = vec![
3434        (ds, true, uv_line([0.0, g0], [1.0, g0])?),
3435        (k1, true, uv_line([1.0, g0], [1.0, g1])?),
3436        (dn, true, uv_line([1.0, g1], [0.0, g1])?),
3437        (k0, false, uv_line([0.0, g1], [0.0, g0])?),
3438    ];
3439    let reversed = |list: Vec<(u64, bool, NurbsCurve)>| -> Result<Vec<(u64, bool, NurbsCurve)>, KernelRefusal> {
3440        list.into_iter().rev().map(|(e, f, p)| Ok((e, !f, frag(p.reversed(), "reversed")?))).collect()
3441    };
3442    shell.face(wall.clone(), if wall_outward { wall_loop } else { reversed(wall_loop)? });
3443    // Caps: loop (grazing arc S -> N, then the meeting arc N -> S), sense by
3444    // the signed area of its parameters (the charts' u × v points outward).
3445    for (surface, inverse, k_edge, k_curve) in [(back, &back_inverse, k0, &outer), (front, &front_inverse, k1, &outer_end)] {
3446        let mut lp = vec![(k_edge, true, pcurve(inverse.as_ref(), k_curve, true)?), (c, false, pcurve(inverse.as_ref(), &meet, false)?)];
3447        let mut area = 0.0;
3448        for (_, _, pc) in &lp {
3449            let [d0, d1] = frag(pc.domain(), "domain")?;
3450            for j in 0..64 {
3451                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")?);
3452                area += a.x * b.y - b.x * a.y;
3453            }
3454        }
3455        if area < 0.0 {
3456            lp = reversed(lp)?;
3457        }
3458        shell.face(surface, lp);
3459    }
3460    let body = shell.solid();
3461    let issues = body.validate();
3462    if !issues.is_empty() {
3463        return Err(refuse("assembly", format!("the turned ball's sweep is not valid: {:?}", issues.first())));
3464    }
3465    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() } };
3466    check_single_pass(screw, &probe, &body, &std::collections::HashSet::new())?;
3467    Ok(Some(body))
3468}
3469
3470/// A frame riding a cubic Bézier curve (`control`, in a plane square to
3471/// `up`): its origin on the curve, its first axis along the curve's tangent,
3472/// `up` fixed. The tool is given in the frame at the curve's start and carried
3473/// by it over the whole curve.
3474#[derive(Clone, Copy, Debug)]
3475pub struct FrameCurve {
3476    pub control: [Vec3; 4],
3477    pub up: Vec3,
3478}
3479
3480/// The whole sweep of a solid of revolution carried by a frame along a
3481/// curve. In the riding frame the velocity field is the speed along the
3482/// tangent plus the turn about `up`, so the grazing loop moves on the tool with
3483/// the curve's curvature. It is split at sample times (its structure must not
3484/// change), each piece sampled exactly, and the walls lofted through those
3485/// samples (quintic both ways; the samples' count doubles until the wall is
3486/// within `LOFT_TARGET` of the exact loop at the times between). Caps are the tool's
3487/// back at the start and front at the end.
3488pub fn sweep_solid_along(tool: &SolidTool, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
3489    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
3490    let base = path.control[0];
3491    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
3492        return Err(input("plane", "the curve is not in a plane square to up".into()));
3493    }
3494    let tangent = path.control[1].sub(base);
3495    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
3496    let start_tangent = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
3497    let frame = Frame { control: path.control, up, start_tangent };
3498    let (mut speed, mut rate, mut extent) = (0.0f64, 0.0f64, 0.0f64);
3499    let mut previous = 0.0;
3500    for k in 0..=512 {
3501        let t = k as f64 / 512.0;
3502        let first = frame.first(t);
3503        if first.length() <= 1e-12 {
3504            return Err(input("tangent", "the curve stops (zero tangent)".into()));
3505        }
3506        speed = speed.max(first.length());
3507        rate = rate.max(frame.angle_rate(t).abs());
3508        extent = extent.max(frame.point(t).sub(base).length());
3509        let angle = frame.angle(t);
3510        if (angle - previous).abs() > 0.5 {
3511            return Err(refuse("frame_turns", "the frame turns half way round".into()));
3512        }
3513        previous = angle;
3514    }
3515    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,
3516        loop_samples: LOFT_SAMPLES, extent };
3517    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
3518        return Err(refuse("along_tool", "a frame along a curve carries a solid of revolution only".into()));
3519    };
3520    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
3521    // The splits name their pieces by angle about the tool's axis from its
3522    // radial direction: a grazing angle passing that reference renames them,
3523    // so try a few references.
3524    let mut last = None;
3525    for k in 0..8 {
3526        let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
3527        match lofted(&screw, *axis_origin, axis, reference, meridian) {
3528            Err(error) if refused_as(&error) == Some("loft_structure") => last = Some(error),
3529            other => return other,
3530        }
3531    }
3532    Err(last.expect("tried"))
3533}
3534
3535/// The whole sweep of a prism carried by a frame along a planar curve (its
3536/// axis along the frame's up): the prism `outline` (a convex polygon in the
3537/// start frame: first coordinate along the start tangent, second along
3538/// up × tangent) between `from` and `to` along up. The motion is planar, so the
3539/// sweep is the plane region the moving outline covers, extruded. That region
3540/// is found exactly: its boundary lies on the outline's corner paths, the paths
3541/// of each edge's grazing point (where the edge's normal is square to the
3542/// velocity), and the outline's edges at the two ends; these are split where
3543/// they meet, and a piece is kept where one side of it is covered and the other
3544/// not (folds, where a corner digs past a side, come out right).
3545pub fn sweep_prism_along(outline: &[[f64; 2]], from: f64, to: f64, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
3546    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
3547    let base = path.control[0];
3548    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
3549        return Err(input("plane", "the curve is not in a plane square to up".into()));
3550    }
3551    let tangent = path.control[1].sub(base);
3552    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
3553    let e1 = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
3554    let e2 = up.cross(e1);
3555    let frame = Frame { control: path.control, up, start_tangent: e1 };
3556    // The frame in plane coordinates: origin c(s), turned by φ(s).
3557    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
3558    let pose = |s: f64| (flat(frame.point(s)), frame.angle(s));
3559    let rates = |s: f64| {
3560        let first = frame.first(s);
3561        ([first.dot(e1), first.dot(e2)], frame.angle_rate(s))
3562    };
3563    prism_region_sweep(outline, from, to, base, e1, e2, up, &pose, &rates, false)
3564}
3565
3566/// The whole sweep of a prism (the convex polygon `outline` in the plane
3567/// through `base` spanned by `e1`, `e2`, between `from` and `to` along `up`)
3568/// under a planar rigid motion: at s ∈ [0, 1] a point q of the plane (in the
3569/// tool's own coordinates) is at origin(s) + R(angle(s)) q, `pose` giving
3570/// (origin, angle) and `rates` their derivatives in s. The sweep is the plane
3571/// region the moving outline covers, extruded. That region is found exactly:
3572/// its boundary lies on the outline's corner paths, the paths of each edge's
3573/// grazing point (where the edge's normal is square to the velocity), and,
3574/// unless the motion is `closed` (it ends where it starts), the outline's
3575/// edges at the two ends; these are split where they meet or cross
3576/// themselves, and a piece is kept where one side of it is covered and the
3577/// other not. The region may have holes.
3578#[allow(clippy::too_many_arguments)]
3579pub fn prism_region_sweep(
3580    outline: &[[f64; 2]],
3581    from: f64,
3582    to: f64,
3583    base: Vec3,
3584    e1: Vec3,
3585    e2: Vec3,
3586    up: Vec3,
3587    pose: &dyn Fn(f64) -> ([f64; 2], f64),
3588    rates: &dyn Fn(f64) -> ([f64; 2], f64),
3589    closed: bool,
3590) -> Result<BrepSolid, KernelRefusal> {
3591    if outline.len() < 3 || !(to > from) {
3592        return Err(input("prism", "a prism needs three corners and a positive height".into()));
3593    }
3594    // Counter-clockwise, convex.
3595    let n = outline.len();
3596    let mut corners = outline.to_vec();
3597    let area: f64 = (0..n).map(|k| corners[k][0] * corners[(k + 1) % n][1] - corners[(k + 1) % n][0] * corners[k][1]).sum();
3598    if area < 0.0 {
3599        corners.reverse();
3600    }
3601    for k in 0..n {
3602        let (a, b, c) = (corners[k], corners[(k + 1) % n], corners[(k + 2) % n]);
3603        if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) <= 0.0 {
3604            return Err(input("prism", "the outline is not convex".into()));
3605        }
3606    }
3607    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
3608    let place = |s: f64, q: [f64; 2]| -> [f64; 2] {
3609        let (o, angle) = pose(s);
3610        let (sn, cs) = angle.sin_cos();
3611        [o[0] + cs * q[0] - sn * q[1], o[1] + sn * q[0] + cs * q[1]]
3612    };
3613    let local = |s: f64, p: [f64; 2]| -> [f64; 2] {
3614        let (o, angle) = pose(s);
3615        let (sn, cs) = angle.sin_cos();
3616        let d = [p[0] - o[0], p[1] - o[1]];
3617        [cs * d[0] + sn * d[1], -sn * d[0] + cs * d[1]]
3618    };
3619    // Edges: outward normals and offsets in the start frame.
3620    let edges: Vec<([f64; 2], f64)> = (0..n)
3621        .map(|k| {
3622            let (a, b) = (corners[k], corners[(k + 1) % n]);
3623            let d = [b[0] - a[0], b[1] - a[1]];
3624            let length = d[0].hypot(d[1]);
3625            let normal = [d[1] / length, -d[0] / length];
3626            (normal, normal[0] * a[0] + normal[1] * a[1])
3627        })
3628        .collect();
3629    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);
3630    // Is p covered at some time? The least signed distance over the motion.
3631    let depth = |p: [f64; 2]| -> f64 {
3632        let samples = 2000;
3633        let f = |s: f64| inside(local(s, p));
3634        let mut best = (f64::INFINITY, 0usize);
3635        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
3636        for (k, &v) in values.iter().enumerate() {
3637            if v < best.0 {
3638                best = (v, k);
3639            }
3640        }
3641        // Refine every local minimum near the least.
3642        let mut least = best.0;
3643        for k in 0..=samples {
3644            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
3645            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
3646            if values[k] <= left && values[k] <= right && values[k] < best.0 + 1e-3 * scale {
3647                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);
3648                for _ in 0..80 {
3649                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
3650                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
3651                }
3652                least = least.min(f(0.5 * (lo + hi)));
3653            }
3654        }
3655        least
3656    };
3657    // Candidate boundary paths, each a map [0, 1] -> plane.
3658    #[derive(Clone, Copy)]
3659    enum Path {
3660        Corner(usize),
3661        /// Edge k's grazing point over the times [s0, s1].
3662        Graze(usize, f64, f64),
3663        /// Edge k at the start (false) or end (true).
3664        End(usize, bool),
3665    }
3666    // Where along edge k's line (0 at its start corner, 1 at its end) the
3667    // grazing point is at s, on the edge or beyond it.
3668    let graze_at = |k: usize, s: f64| -> Option<f64> {
3669        // Along edge k at x (in the tool's coordinates) the velocity's part
3670        // along the edge's normal n is w·n + φ' (ẑ × x)·n, w the origin's
3671        // velocity read in the tool's frame.
3672        let (a, b) = (corners[k], corners[(k + 1) % n]);
3673        let (nn, _) = edges[k];
3674        let (velocity, rate) = rates(s);
3675        let (sn, cs) = pose(s).1.sin_cos();
3676        let w = [cs * velocity[0] + sn * velocity[1], -sn * velocity[0] + cs * velocity[1]];
3677        let along = w[0] * nn[0] + w[1] * nn[1];
3678        let rot = |x: [f64; 2]| -x[1] * nn[0] + x[0] * nn[1]; // (ẑ × x)·n
3679        // An edge the origin moves along grazes where (ẑ × x)·n = 0 whatever
3680        // the turning rate (also where it is zero, at an inflection).
3681        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)) };
3682        if ga == gb {
3683            return None;
3684        }
3685        Some(ga / (ga - gb))
3686    };
3687    let graze_point = |k: usize, s: f64| -> Option<f64> { graze_at(k, s).filter(|&u| u > 0.0 && u < 1.0) };
3688    let mut paths: Vec<Path> = (0..n).map(Path::Corner).collect();
3689    // Where a grazing point enters or leaves its edge it is at a corner:
3690    // (that corner, the time), a place its path is split at.
3691    let mut junctions: Vec<(usize, f64)> = Vec::new();
3692    for k in 0..n {
3693        // Where along the motion edge k has a grazing point inside it, each
3694        // run's ends found where the point passes a corner.
3695        let steps = 2000;
3696        let mut run: Option<f64> = None;
3697        let mut passes = |inside: f64, outside: f64| -> f64 {
3698            let (mut a, mut b) = (inside, outside);
3699            for _ in 0..80 {
3700                let mid = 0.5 * (a + b);
3701                if graze_point(k, mid).is_some() { a = mid } else { b = mid }
3702            }
3703            let corner = if graze_at(k, a).is_some_and(|u| u < 0.5) { k } else { (k + 1) % n };
3704            junctions.push((corner, a));
3705            a
3706        };
3707        for j in 0..=steps {
3708            let s = j as f64 / steps as f64;
3709            let on = graze_point(k, s).is_some();
3710            match (on, run) {
3711                (true, None) => run = Some(if j == 0 { s } else { passes(s, s - 1.0 / steps as f64) }),
3712                (false, Some(s0)) => {
3713                    paths.push(Path::Graze(k, s0, passes(s - 1.0 / steps as f64, s)));
3714                    run = None;
3715                }
3716                _ => {}
3717            }
3718        }
3719        if let Some(s0) = run {
3720            paths.push(Path::Graze(k, s0, 1.0));
3721        }
3722        if !closed {
3723            paths.push(Path::End(k, false));
3724            paths.push(Path::End(k, true));
3725        }
3726    }
3727    let eval = |path: Path, t: f64| -> [f64; 2] {
3728        match path {
3729            Path::Corner(k) => place(t, corners[k]),
3730            Path::Graze(k, s0, s1) => {
3731                let s = s0 + (s1 - s0) * t;
3732                let u = graze_at(k, s).map_or(0.5, |u| u.clamp(0.0, 1.0));
3733                let (a, b) = (corners[k], corners[(k + 1) % n]);
3734                place(s, [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u])
3735            }
3736            Path::End(k, at_end) => {
3737                let (a, b) = (corners[k], corners[(k + 1) % n]);
3738                place(if at_end { 1.0 } else { 0.0 }, [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t])
3739            }
3740        }
3741    };
3742    let count = paths.len();
3743    region_from_paths(
3744        count,
3745        &|index: usize, t: f64| eval(paths[index], t),
3746        &|index: usize| matches!(paths[index], Path::End(..)),
3747        &|_: usize| closed,
3748        &junctions,
3749        &depth,
3750        scale,
3751        (base, e1, e2, up),
3752        (from, to),
3753    )
3754}
3755
3756/// Everything a tube (the ball of `radius` swept along the curve
3757/// `centreline(s)`, s ∈ [0, 1], its ends included) passes through as it slides
3758/// by `slide`, inside the slab `slab[0] ≤ (x − slab_origin)·n ≤ slab[1]` (`n` =
3759/// `slab_normal` normalised), which the tube must cross wholly: before the
3760/// slab at the start, past it at the end (checked at 8001 points of the
3761/// centreline, with a margin of the longest step between them). The
3762/// returned prism along the slide agrees with the sweep inside the slab; the
3763/// caller cuts a workpiece that lies within it.
3764///
3765/// The centreline must be resolved by its samples (as every path of the plane
3766/// region arrangement is): smooth, its height changing between two of the
3767/// 8001 checking samples by no more than the step between them, so that the
3768/// samples bound it. A curve that wanders between samples is outside this
3769/// contract.
3770///
3771/// Why a prism: a point x of the slab is in the sweep iff the line through x
3772/// along the slide meets the tube. If it does, `n·` grows along the line, so
3773/// its topmost point y of the starting tube lies before x, and y + slide (a
3774/// point of the final tube) past it: x − y is a multiple of the slide in
3775/// [0, 1). So the sweep in the slab is the slab's part of the prism over the
3776/// tube's shadow along the slide: in the plane square to it the union of the
3777/// discs of `radius` about the shadow γ of the centreline. That region is
3778/// bounded by γ's two offset curves (each disc's grazing points, γ ± radius
3779/// along its normal) and the end discs' circles, built exactly by the plane
3780/// region arrangement of [`sweep_prism_along`].
3781pub fn sweep_tube_slid_across(
3782    centreline: &dyn Fn(f64) -> Vec3,
3783    radius: f64,
3784    slide: Vec3,
3785    slab_origin: Vec3,
3786    slab_normal: Vec3,
3787    slab: [f64; 2],
3788) -> Result<BrepSolid, KernelRefusal> {
3789    if !(radius.is_finite() && radius > 0.0) {
3790        return Err(input("tube_radius", "the tube's radius must be positive".into()));
3791    }
3792    let up = slide.normalized().map_err(|_| input("slide", "the slide has no length".into()))?;
3793    let normal = slab_normal.normalized().map_err(|_| input("slab", "the slab's normal has no direction".into()))?;
3794    if !(slab[1] > slab[0]) || up.dot(normal).abs() < 1e-9 {
3795        return Err(input("slab", "the slab must have thickness and the slide must cross it".into()));
3796    }
3797    // Orient so the slide runs up the slab's normal.
3798    let (normal, slab) = if up.dot(normal) > 0.0 { (normal, slab) } else { (normal.scale(-1.0), [-slab[1], -slab[0]]) };
3799    let points: Vec<Vec3> = (0..=8000).map(|k| centreline(k as f64 / 8000.0)).collect();
3800    if points.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) {
3801        return Err(input("centreline", "the centreline has a point that is not finite".into()));
3802    }
3803    let step = points.windows(2).map(|w| w[1].sub(w[0]).length()).fold(0.0f64, f64::max);
3804    let heights: Vec<f64> = points.iter().map(|q| q.sub(slab_origin).dot(normal)).collect();
3805    let (low, high) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &h| (a.min(h), b.max(h)));
3806    let rise = slide.dot(normal);
3807    if !(high + radius + step < slab[0] && low - radius - step + rise > slab[1]) {
3808        return Err(refuse("tube_slab", "the tube does not pass wholly through the slab (it starts or ends within reach of it)".into()));
3809    }
3810    let e1 = {
3811        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) };
3812        seed.sub(up.scale(seed.dot(up))).normalized().map_err(|_| input("slide", "no frame".into()))?
3813    };
3814    let e2 = up.cross(e1);
3815    // The plane's origin on the centreline itself, so that every tolerance
3816    // reads the tube's own size, wherever it lies.
3817    let base = points[0];
3818    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
3819    let centre = |s: f64| -> [f64; 2] { flat(centreline(s)) };
3820    let velocity = |s: f64| -> [f64; 2] {
3821        let h = 1e-7;
3822        let (a, b) = ((s - h).max(0.0), (s + h).min(1.0));
3823        let (p, q) = (centre(a), centre(b));
3824        [(q[0] - p[0]) / (b - a), (q[1] - p[1]) / (b - a)]
3825    };
3826    // The shadow must keep moving (a disc standing still has no grazing points).
3827    for k in 0..=2000 {
3828        let w = velocity(k as f64 / 2000.0);
3829        if w[0].hypot(w[1]) < 1e-9 * (1.0 + radius) {
3830            return Err(refuse("tube_shadow", "the tube's shadow along the slide stops (its centreline runs along the slide)".into()));
3831        }
3832    }
3833    // Tolerances read the tube's radius (a probe beside a boundary must stay
3834    // within the tube), never more than its extent; a tube longer than 1e6
3835    // radii is beyond what the coordinates resolve at that size.
3836    let extent = (0..=64).map(|k| { let c = centre(k as f64 / 64.0); c[0].hypot(c[1]) }).fold(radius, f64::max);
3837    if extent > 1e6 * radius {
3838        return Err(refuse("tube_shadow", "the tube is too long for its radius (over a million radii)".into()));
3839    }
3840    let scale = extent.min(1e3 * radius);
3841    // Paths: the two offset curves, then the two end circles.
3842    let eval = |index: usize, t: f64| -> [f64; 2] {
3843        match index {
3844            0 | 1 => {
3845                let c = centre(t);
3846                let w = velocity(t);
3847                let length = w[0].hypot(w[1]);
3848                let side = if index == 0 { 1.0 } else { -1.0 };
3849                [c[0] - side * radius * w[1] / length, c[1] + side * radius * w[0] / length]
3850            }
3851            _ => {
3852                let c = centre(if index == 2 { 0.0 } else { 1.0 });
3853                let angle = TAU * t;
3854                [c[0] + radius * angle.cos(), c[1] + radius * angle.sin()]
3855            }
3856        }
3857    };
3858    // Inside: nearer than `radius` to the shadow at some time.
3859    let depth = |p: [f64; 2]| -> f64 {
3860        let samples = 4000;
3861        let f = |s: f64| { let c = centre(s); (p[0] - c[0]).hypot(p[1] - c[1]) - radius };
3862        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
3863        let mut least = values.iter().cloned().fold(f64::INFINITY, f64::min);
3864        for k in 0..=samples {
3865            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
3866            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
3867            if values[k] <= left && values[k] <= right && values[k] < least + 1e-3 * scale {
3868                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);
3869                for _ in 0..80 {
3870                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
3871                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
3872                }
3873                least = least.min(f(0.5 * (lo + hi)));
3874            }
3875        }
3876        least
3877    };
3878    // The prism spans the slab's crossing of every line through the region:
3879    // from below the starting tube to past the final one, along the slide.
3880    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)));
3881    let margin = radius + step + 1e-3 * scale;
3882    // Each offset curve ends on its end circle, tangent to it there (both run
3883    // along the velocity), which no crossing test finds: split the circles at
3884    // those points (the angles of ±the normal there).
3885    let mut touches: Vec<(usize, f64)> = Vec::new();
3886    for (circle, s) in [(2usize, 0.0f64), (3, 1.0)] {
3887        let w = velocity(s);
3888        for side in [1.0f64, -1.0] {
3889            let angle = (side * w[0]).atan2(-side * w[1]);
3890            touches.push((circle, angle.rem_euclid(TAU) / TAU));
3891        }
3892    }
3893    region_from_paths(
3894        4,
3895        &eval,
3896        &|_| false,
3897        &|index| index >= 2,
3898        &touches,
3899        &depth,
3900        scale,
3901        (base, e1, e2, up),
3902        (a0 - margin, a1 + slide.length() + margin),
3903    )
3904}
3905
3906/// The plane region bounded by pieces of the candidate `count` paths (each
3907/// `eval(index, t)`, t ∈ [0, 1]), extruded along `up` from `heights.0` to
3908/// `heights.1`: the paths are split where they cross each other or
3909/// themselves (and at `extra_cuts`), a piece is kept where `depth` (negative
3910/// inside the region) reads one side covered and the other not, and the kept
3911/// pieces chain into one outer loop and its holes. `straight_path(index)`: the
3912/// path is a segment (built as a line); `closed_path(index)`: its two ends
3913/// meet (neighbours for the self-crossing test).
3914#[allow(clippy::too_many_arguments)]
3915fn region_from_paths(
3916    count: usize,
3917    eval: &dyn Fn(usize, f64) -> [f64; 2],
3918    straight_path: &dyn Fn(usize) -> bool,
3919    closed_path: &dyn Fn(usize) -> bool,
3920    extra_cuts: &[(usize, f64)],
3921    depth: &dyn Fn([f64; 2]) -> f64,
3922    scale: f64,
3923    frame: (Vec3, Vec3, Vec3, Vec3),
3924    heights: (f64, f64),
3925) -> Result<BrepSolid, KernelRefusal> {
3926    let (base, e1, e2, up) = frame;
3927    let (from, to) = heights;
3928    // Split parameters: mutual crossings (polyline, then Newton), and each
3929    // path's ends lying on another.
3930    let m = 400;
3931    let polylines: Vec<Vec<[f64; 2]>> = (0..count).map(|p| (0..=m).map(|i| eval(p, i as f64 / m as f64)).collect()).collect();
3932    let mut cuts: Vec<Vec<f64>> = vec![vec![0.0, 1.0]; count];
3933    let tol = 1e-10 * scale;
3934    for a in 0..count {
3935        for b in a..count {
3936            for i in 0..m {
3937                for j in 0..m {
3938                    // A path against itself: only where it crosses over
3939                    // (stretches apart along it; a closed path's ends are
3940                    // neighbours too).
3941                    if a == b && (j < i + 3 || (closed_path(a) && i < 3 && j + 3 > m)) {
3942                        continue;
3943                    }
3944                    let (p0, p1, q0, q1) = (polylines[a][i], polylines[a][i + 1], polylines[b][j], polylines[b][j + 1]);
3945                    let d1 = [p1[0] - p0[0], p1[1] - p0[1]];
3946                    let d2 = [q1[0] - q0[0], q1[1] - q0[1]];
3947                    let det = d1[0] * d2[1] - d1[1] * d2[0];
3948                    if det.abs() < 1e-300 {
3949                        continue;
3950                    }
3951                    let r = [q0[0] - p0[0], q0[1] - p0[1]];
3952                    let (x, y) = ((r[0] * d2[1] - r[1] * d2[0]) / det, (r[0] * d1[1] - r[1] * d1[0]) / det);
3953                    if !(-1e-9..=1.0 + 1e-9).contains(&x) || !(-1e-9..=1.0 + 1e-9).contains(&y) {
3954                        continue;
3955                    }
3956                    // Newton on the exact paths.
3957                    let (mut ta, mut tb) = ((i as f64 + x) / m as f64, (j as f64 + y) / m as f64);
3958                    for _ in 0..50 {
3959                        let (pa, pb) = (eval(a, ta), eval(b, tb));
3960                        let h = 1e-7;
3961                        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] };
3962                        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] };
3963                        let f = [pa[0] - pb[0], pa[1] - pb[1]];
3964                        let det = -da[0] * db[1] + da[1] * db[0];
3965                        if det.abs() < 1e-300 {
3966                            break;
3967                        }
3968                        let dta = (-f[0] * db[1] + f[1] * db[0]) / det;
3969                        let dtb = (da[0] * f[1] - da[1] * f[0]) / det;
3970                        ta = (ta - dta).clamp(0.0, 1.0);
3971                        tb = (tb - dtb).clamp(0.0, 1.0);
3972                        if dta.abs() + dtb.abs() < 1e-15 {
3973                            break;
3974                        }
3975                    }
3976                    let (pa, pb) = (eval(a, ta), eval(b, tb));
3977                    if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < tol && !(a == b && (ta - tb).abs() < 1.0 / m as f64) {
3978                        cuts[a].push(ta);
3979                        cuts[b].push(tb);
3980                    }
3981                }
3982            }
3983        }
3984    }
3985    // Extra splits the caller names (a corner's path where a grazing point passes it).
3986    for &(path, t) in extra_cuts {
3987        cuts[path].push(t);
3988    }
3989    for c in &mut cuts {
3990        c.sort_by(|x, y| x.total_cmp(y));
3991        c.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
3992    }
3993    // Pieces on the boundary: covered on exactly one side.
3994    struct Piece {
3995        path: usize,
3996        t0: f64,
3997        t1: f64,
3998    }
3999    let eps = 1e-7 * scale;
4000    let mut pieces: Vec<Piece> = Vec::new();
4001    for (index, c) in cuts.iter().enumerate() {
4002        for w in c.windows(2) {
4003            let (t0, t1) = (w[0], w[1]);
4004            if t1 - t0 < 1e-9 {
4005                continue;
4006            }
4007            let (pa, pb) = (eval(index, t0), eval(index, t1));
4008            if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < 1e-9 * scale {
4009                continue;
4010            }
4011            let tm = 0.5 * (t0 + t1);
4012            let (p, q) = (eval(index, tm), eval(index, (tm + 1e-6).min(1.0)));
4013            let d = [q[0] - p[0], q[1] - p[1]];
4014            let length = d[0].hypot(d[1]);
4015            if length == 0.0 {
4016                continue;
4017            }
4018            let left = [p[0] - d[1] / length * eps, p[1] + d[0] / length * eps];
4019            let right = [p[0] + d[1] / length * eps, p[1] - d[0] / length * eps];
4020            let (l, r) = (depth(left) < -1e-12 * scale, depth(right) < -1e-12 * scale);
4021            match (l, r) {
4022                (true, false) => pieces.push(Piece { path: index, t0, t1 }),
4023                (false, true) => pieces.push(Piece { path: index, t0: t1, t1: t0 }),
4024                _ => {}
4025            }
4026        }
4027    }
4028    // Chain into loops, the region on their left (the outer one runs
4029    // counter-clockwise, a hole's clockwise).
4030    if pieces.is_empty() {
4031        return Err(refuse("prism_along", "no boundary found".into()));
4032    }
4033    let mut used = vec![false; pieces.len()];
4034    let mut loops: Vec<Vec<usize>> = Vec::new();
4035    while let Some(first) = (0..pieces.len()).find(|&k| !used[k]) {
4036        let mut order = vec![first];
4037        used[first] = true;
4038        loop {
4039            let last = &pieces[*order.last().expect("order")];
4040            let end = eval(last.path, last.t1);
4041            let start = eval(pieces[order[0]].path, pieces[order[0]].t0);
4042            if (end[0] - start[0]).hypot(end[1] - start[1]) < 1e-8 * scale {
4043                break;
4044            }
4045            let next = (0..pieces.len()).filter(|&k| !used[k]).min_by(|&x, &y| {
4046                let (px, py) = (eval(pieces[x].path, pieces[x].t0), eval(pieces[y].path, pieces[y].t0));
4047                (px[0] - end[0]).hypot(px[1] - end[1]).total_cmp(&(py[0] - end[0]).hypot(py[1] - end[1]))
4048            });
4049            let Some(next) = next else {
4050                return Err(refuse("prism_along", "the boundary does not close".into()));
4051            };
4052            let p = eval(pieces[next].path, pieces[next].t0);
4053            if (p[0] - end[0]).hypot(p[1] - end[1]) > 1e-8 * scale {
4054                return Err(refuse("prism_along", format!("the boundary does not close (gap {:e})", (p[0] - end[0]).hypot(p[1] - end[1]))));
4055            }
4056            used[next] = true;
4057            order.push(next);
4058        }
4059        loops.push(order);
4060    }
4061    // The outer loop first: the one of greatest area.
4062    let area_of = |order: &Vec<usize>| -> f64 {
4063        let mut points: Vec<[f64; 2]> = Vec::new();
4064        for &k in order {
4065            let piece = &pieces[k];
4066            for i in 0..32 {
4067                points.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 32.0));
4068            }
4069        }
4070        (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
4071    };
4072    let areas: Vec<f64> = loops.iter().map(area_of).collect();
4073    let outer = (0..loops.len()).max_by(|&x, &y| areas[x].abs().total_cmp(&areas[y].abs())).expect("loops");
4074    if areas[outer] <= 0.0 || (0..loops.len()).any(|k| k != outer && areas[k] >= 0.0) {
4075        return Err(refuse("prism_along", "the swept region is not one region with holes".into()));
4076    }
4077    loops.swap(0, outer);
4078    // Plane curves of the loops, then the extrusion.
4079    let world = |q: [f64; 2], h: f64| base.add(e1.scale(q[0])).add(e2.scale(q[1])).add(up.scale(h));
4080    let mut shell = Shell::new();
4081    let mut top_loops = Vec::with_capacity(loops.len());
4082    let mut bottom_loops = Vec::with_capacity(loops.len());
4083    let mut extent: Vec<[f64; 2]> = Vec::new();
4084    for order in &loops {
4085        let mut loop_points: Vec<[f64; 2]> = order.iter().map(|&k| eval(pieces[k].path, pieces[k].t0)).collect();
4086        loop_points.push(loop_points[0]);
4087        let count = order.len();
4088        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();
4089        let mut bottom_e = Vec::with_capacity(count);
4090        let mut top_e = Vec::with_capacity(count);
4091        let mut curves2d = Vec::with_capacity(count);
4092        for (slot, &k) in order.iter().enumerate() {
4093            let piece = &pieces[k];
4094            let straight = straight_path(piece.path);
4095            let next = (slot + 1) % count;
4096            for i in 0..=16 {
4097                extent.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 16.0));
4098            }
4099            let curve_at = |h: f64| -> Result<NurbsCurve, KernelRefusal> {
4100                if straight {
4101                    return frag(make_line(world(loop_points[slot], h), world(loop_points[next], h)), "line");
4102                }
4103                let samples = 192;
4104                let ts: Vec<f64> = (0..=samples).map(|i| i as f64 / samples as f64).collect();
4105                let mut points: Vec<Vec3> = ts.iter().map(|&t| world(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * t), h)).collect();
4106                points[0] = world(loop_points[slot], h);
4107                points[samples] = world(loop_points[next], h);
4108                frag(crate::interpolate_curve(&points, 5, &ts), "plane_path")
4109            };
4110            let (cb, ct) = (curve_at(from)?, curve_at(to)?);
4111            bottom_e.push(shell.edge(cb.clone(), bottom_v[slot], bottom_v[next], false)?);
4112            top_e.push(shell.edge(ct.clone(), top_v[slot], top_v[next], false)?);
4113            curves2d.push((cb, ct));
4114        }
4115        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<_, _>>()?;
4116        // Top (outward up) and bottom (outward down) loops.
4117        let mut coedges = Vec::with_capacity(count);
4118        for k in 0..count {
4119            coedges.push((top_e[k], true, plane_pcurve(world([0.0, 0.0], to), e1, e2, &curves2d[k].1, true)?));
4120        }
4121        top_loops.push(coedges);
4122        let mut coedges = Vec::with_capacity(count);
4123        for k in (0..count).rev() {
4124            coedges.push((bottom_e[k], false, plane_pcurve(world([0.0, 0.0], from), e2, e1, &curves2d[k].0, false)?));
4125        }
4126        bottom_loops.push(coedges);
4127        // Sides: the bottom curve extruded (u along it, v up), outward on its right.
4128        for k in 0..count {
4129            let next = (k + 1) % count;
4130            let (cb, _) = &curves2d[k];
4131            let rows: Vec<Vec<Vec4>> = cb
4132                .control_points
4133                .iter()
4134                .map(|p| {
4135                    let x = p.point().expect("point");
4136                    vec![Vec4::from_point(x, p.w), Vec4::from_point(x.add(up.scale(to - from)), p.w)]
4137                })
4138                .collect();
4139            let surface = frag(NurbsSurface::new(cb.degree, 1, cb.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows), "side")?;
4140            let [u0, u1] = frag(cb.domain(), "domain")?;
4141            let coedges = vec![
4142                (bottom_e[k], true, uv_line([u0, 0.0], [u1, 0.0])?),
4143                (verticals[next], true, uv_line([u1, 0.0], [u1, 1.0])?),
4144                (top_e[k], false, uv_line([u1, 1.0], [u0, 1.0])?),
4145                (verticals[k], false, uv_line([u0, 1.0], [u0, 0.0])?),
4146            ];
4147            shell.face(surface, coedges);
4148        }
4149    }
4150    let top_points: Vec<Vec3> = extent.iter().map(|&q| world(q, to)).collect();
4151    shell.face_loops(plane_patch(world([0.0, 0.0], to), e1, e2, &top_points)?, top_loops);
4152    let bottom_points: Vec<Vec3> = extent.iter().map(|&q| world(q, from)).collect();
4153    shell.face_loops(plane_patch(world([0.0, 0.0], from), e2, e1, &bottom_points)?, bottom_loops);
4154    let body = shell.solid();
4155    let issues = body.validate();
4156    if !issues.is_empty() {
4157        return Err(refuse("assembly", format!("the swept prism is not valid: {:?}", issues.first())));
4158    }
4159    Ok(body)
4160}
4161
4162/// A prism whose section is a convex polygon, carried by turns about axes
4163/// all along its own (a planar motion: a planet on its carrier) that ends
4164/// where it starts: its whole sweep (`prism_region_sweep`), or None when the
4165/// tool or motion is not of that kind. `steps`: each turn's axis point,
4166/// direction and rate, applied in order at every t ∈ [t0, t1].
4167#[allow(clippy::too_many_arguments)]
4168pub fn closed_planar_prism(
4169    origin: Vec3,
4170    normal: Vec3,
4171    x_axis: Vec3,
4172    outline: &[OutlinePiece],
4173    from: f64,
4174    to: f64,
4175    steps: &[(Vec3, Vec3, f64, f64)],
4176    t0: f64,
4177    t1: f64,
4178) -> Result<Option<BrepSolid>, KernelRefusal> {
4179    let Ok(up) = normal.normalized() else { return Ok(None) };
4180    let Ok(e1) = x_axis.sub(up.scale(x_axis.dot(up))).normalized() else { return Ok(None) };
4181    let e2 = up.cross(e1);
4182    // A polygon of straight sides, in order.
4183    let mut corners: Vec<[f64; 2]> = Vec::with_capacity(outline.len());
4184    for (k, piece) in outline.iter().enumerate() {
4185        let OutlinePiece::Line { from: a, to: b } = piece else { return Ok(None) };
4186        let OutlinePiece::Line { from: next, .. } = &outline[(k + 1) % outline.len()] else { return Ok(None) };
4187        if (b[0] - next[0]).hypot(b[1] - next[1]) > 1e-9 * (1.0 + b[0].hypot(b[1])) {
4188            return Ok(None);
4189        }
4190        corners.push(*a);
4191    }
4192    if corners.len() < 3 || steps.is_empty() || !(t1 > t0) {
4193        return Ok(None);
4194    }
4195    // Convex (either way round), or it is another engine's.
4196    let turn_of = |k: usize| {
4197        let (a, b, c) = (corners[k], corners[(k + 1) % corners.len()], corners[(k + 2) % corners.len()]);
4198        (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
4199    };
4200    let first_turn = turn_of(0);
4201    if first_turn == 0.0 || (1..corners.len()).any(|k| turn_of(k) * first_turn <= 0.0) {
4202        return Ok(None);
4203    }
4204    // Turns only, about axes along the prism's own: (centre in the plane, rate about +up).
4205    let mut turns: Vec<([f64; 2], f64)> = Vec::with_capacity(steps.len());
4206    for &(point, direction, turn, advance) in steps {
4207        let Ok(axis) = direction.normalized() else { return Ok(None) };
4208        if advance != 0.0 || axis.cross(up).length() > 1e-12 {
4209            return Ok(None);
4210        }
4211        let r = point.sub(origin);
4212        turns.push(([r.dot(e1), r.dot(e2)], turn * axis.dot(up).signum()));
4213    }
4214    let moved = |t: f64, q: [f64; 2]| -> [f64; 2] {
4215        let mut x = q;
4216        for &(c, rate) in &turns {
4217            let (sn, cs) = (rate * t).sin_cos();
4218            let d = [x[0] - c[0], x[1] - c[1]];
4219            x = [c[0] + cs * d[0] - sn * d[1], c[1] + sn * d[0] + cs * d[1]];
4220        }
4221        x
4222    };
4223    let total: f64 = turns.iter().map(|t| t.1).sum();
4224    // The turns compose to one rigid motion of the plane: a point q (where
4225    // it stands before any motion) is at moved(t, 0) + R(total t) q.
4226    let pose = |s: f64| -> ([f64; 2], f64) {
4227        let t = t0 + (t1 - t0) * s;
4228        (moved(t, [0.0, 0.0]), total * t)
4229    };
4230    // The turns are defined at every t, so the origin's velocity is a
4231    // centred difference at the motion's ends too.
4232    let rates = |s: f64| -> ([f64; 2], f64) {
4233        let h = 1e-6;
4234        let (pa, pb) = (pose(s - h).0, pose(s + h).0);
4235        ([(pb[0] - pa[0]) / (2.0 * h), (pb[1] - pa[1]) / (2.0 * h)], total * (t1 - t0))
4236    };
4237    // Ends where it starts: the same turn (mod 2π) and place.
4238    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
4239    let closes = corners.iter().all(|&c| {
4240        let (a, b) = (moved(t0, c), moved(t1, c));
4241        (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-9 * scale
4242    });
4243    if !closes {
4244        return Ok(None);
4245    }
4246    prism_region_sweep(&corners, from, to, origin, e1, e2, up, &pose, &rates, true).map(Some)
4247}
4248
4249/// Two turns driven by one parameter t: first by `rates[0]·t` about the
4250/// first axis (point, direction), then by `rates[1]·t` about the second; both
4251/// axes fixed in the world; t from `from` to `to`.
4252#[derive(Clone, Copy, Debug)]
4253pub struct TwoTurns {
4254    pub axes: [(Vec3, Vec3); 2],
4255    pub rates: [f64; 2],
4256    pub from: f64,
4257    pub to: f64,
4258}
4259
4260/// The whole sweep of a solid of revolution tumbled by two turns about skew
4261/// axes. The grazing loop moves on the tool (the instantaneous screw changes
4262/// with t), so the walls are lofted through exact samples. Where the tumble
4263/// passes over a point twice (the one-pass probe), the time is bisected into
4264/// spans each passing once, and the spans' sweeps are joined (consecutive
4265/// spans meet along a grazing loop; distant ones overlap).
4266pub fn sweep_solid_tumbled(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
4267    let lofted = sweep_solid_tumbled_lofted(tool, motion);
4268    // A ring (a whole circle off its axis) the lofted walls refuse, by the
4269    // trim engine (BREP_SWEEP_RING_TRIM); the lofted refusal stands where it
4270    // refuses too. Rows the walls build are left to them.
4271    let Err(refusal) = lofted else { return lofted };
4272    // A wall whose double curve reaches a corner: the trim route meets that
4273    // double curve's tip, which it does not yet write so a reader integrates
4274    // round it, and refuses after the work; declined before it.
4275    if !crate::solid_sweep_trim::ring_trim_on() || refusal.to_string().contains(DOUBLE_CURVE_CORNER) {
4276        return Err(refusal);
4277    }
4278    let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool else { return Err(refusal) };
4279    let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() else { return Err(refusal) };
4280    if !(((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius) {
4281        return Err(refusal);
4282    }
4283    let (Ok(axis), Ok(d0), Ok(d1)) = (axis_direction.normalized(), motion.axes[0].1.normalized(), motion.axes[1].1.normalized()) else { return Err(refusal) };
4284    let two = crate::solid_sweep_trim::TwoTurnMotion { points: [motion.axes[0].0, motion.axes[1].0], directions: [d0, d1], rates: motion.rates };
4285    let ring_centre = axis_origin.add(axis.scale(centre[1]));
4286    crate::solid_sweep_trim::sweep_ring_tumbled(ring_centre, axis, centre[0], *radius, &two, motion.from, motion.to).or(Err(refusal))
4287}
4288
4289/// The lofted walls' refusal where a wall's double curve reaches a corner of
4290/// its grazing loop (the tumbled sweep reads it to skip the ring's trim route).
4291#[doc(hidden)]
4292pub const DOUBLE_CURVE_CORNER: &str = "the double curve of a wall reaches a corner of its grazing loop";
4293
4294/// The tumbled sweep by the lofted walls (a polyhedron by the trim engine).
4295fn sweep_solid_tumbled_lofted(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
4296    if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
4297        return Err(input("range", "the motion's range must run forward".into()));
4298    }
4299    let mut points = [Vec3::new(0.0, 0.0, 0.0); 2];
4300    let mut directions = [Vec3::new(0.0, 0.0, 1.0); 2];
4301    for k in 0..2 {
4302        points[k] = motion.axes[k].0;
4303        directions[k] = motion.axes[k].1.normalized().map_err(|_| input("axis", "a turn's axis has no direction".into()))?;
4304    }
4305    let turns = Turns { points, directions, rates: motion.rates };
4306    // A convex polyhedron, by the trim engine (default off).
4307    if let SolidTool::Polyhedron { vertices, faces } = tool {
4308        if crate::solid_sweep_trim::trim_engine_on() {
4309            let two = crate::solid_sweep_trim::TwoTurnMotion { points, directions, rates: motion.rates };
4310            return crate::solid_sweep_trim::sweep_convex_tumbled(vertices, faces, &two, motion.from, motion.to);
4311        }
4312    }
4313    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
4314        return Err(refuse("tumble_tool", "a tumble sweeps a solid of revolution only".into()));
4315    };
4316    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
4317    let base = Screw {
4318        a: points[0],
4319        e: directions[0],
4320        omega: motion.rates[0].abs() + motion.rates[1].abs(),
4321        c: 0.0,
4322        c2: 0.0,
4323        t0: motion.from,
4324        t1: motion.to,
4325        frame: None,
4326        turns: Some(turns),
4327        frozen: None,
4328        loop_samples: LOFT_SAMPLES,
4329        extent: points[1].sub(points[0]).length(),
4330    };
4331    let span = |t0: f64, t1: f64| -> Result<BrepSolid, KernelRefusal> {
4332        let mut screw = base;
4333        screw.t0 = t0;
4334        screw.t1 = t1;
4335        let mut last = None;
4336        // The loop's sampling doubles while the walls' rows miss between
4337        // samples (a thin ring's loop bends sharply before it folds).
4338        'samples: while screw.loop_samples <= 16 * LOFT_SAMPLES {
4339            for k in 0..8 {
4340                let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
4341                match lofted(&screw, *axis_origin, axis, reference, meridian) {
4342                    // A bulge that crosses a seam high up reads on the next
4343                    // wall as a part held away from its end: other seams too.
4344                    Err(error) if matches!(refused_as(&error), Some("loft_structure") | Some("end_trim_corner") | Some("end_trim_deep")) => last = Some(error),
4345                    Err(error) if refused_as(&error) == Some("loft_rows") => {
4346                        last = Some(error);
4347                        screw.loop_samples *= 2;
4348                        continue 'samples;
4349                    }
4350                    other => return other,
4351                }
4352            }
4353            break;
4354        }
4355        Err(last.expect("tried"))
4356    };
4357    // Bisect where the sweep folds over itself.
4358    let mut pending = vec![(motion.from, motion.to, 0usize)];
4359    let mut spans: Vec<(f64, BrepSolid)> = Vec::new();
4360    while let Some((t0, t1, depth)) = pending.pop() {
4361        match span(t0, t1) {
4362            Ok(body) => spans.push((t0, body)),
4363            Err(error) if refused_as(&error) == Some("folds") && depth < 6 => {
4364                let middle = 0.5 * (t0 + t1);
4365                pending.push((middle, t1, depth + 1));
4366                pending.push((t0, middle, depth + 1));
4367            }
4368            Err(error) => return Err(error),
4369        }
4370    }
4371    spans.sort_by(|a, b| a.0.total_cmp(&b.0));
4372    let mut bodies: Vec<BrepSolid> = spans.into_iter().map(|(_, body)| body).collect();
4373    if bodies.len() == 1 {
4374        return Ok(bodies.pop().expect("one"));
4375    }
4376    crate::boolean_operation_nary(&bodies, crate::BooleanOperation::Union)
4377}
4378
4379/// A cap's pcurve for a lofted edge through the cap's exact chart (the edge
4380/// read back into the tool's frame at the cap's time).
4381fn charted_pcurve(chart: &Chart, screw: &Screw, t: f64, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
4382    let [d0, d1] = frag(curve.domain(), "domain")?;
4383    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
4384    let mut uv = Vec::with_capacity(ts.len());
4385    let mut poles = Vec::with_capacity(ts.len());
4386    for &tt in &ts {
4387        let x = screw.invert(t, frag(curve.evaluate(tt), "point")?);
4388        let [u, v] = chart.invert(x);
4389        uv.push(Vec3::new(u, v, 0.0));
4390        poles.push(chart.at_pole(x));
4391    }
4392    continue_pole_angles(&mut uv, &ts, &poles)?;
4393    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "charted_pcurve")?;
4394    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
4395}
4396
4397/// An edge through its surface's pole (a ball carried square to its own
4398/// axis: every grazing circle runs pole to pole) has no angle there, and the
4399/// inverse returns any. Each sample at a pole (`poles`) takes the first
4400/// parameter its neighbours run to, continued in a line.
4401fn continue_pole_angles(uv: &mut [Vec3], ts: &[f64], poles: &[bool]) -> Result<(), KernelRefusal> {
4402    for j in 0..uv.len() {
4403        if !poles[j] {
4404            continue;
4405        }
4406        let near = if j + 2 < uv.len() && !poles[j + 1] && !poles[j + 2] {
4407            [j + 1, j + 2]
4408        } else if j >= 2 && !poles[j - 1] && !poles[j - 2] {
4409            [j - 1, j - 2]
4410        } else {
4411            return Err(refuse("cap_pole", "a lofted edge stays on its cap's pole".into()));
4412        };
4413        let (a, b) = (uv[near[0]].x, uv[near[1]].x);
4414        uv[j].x = a + (a - b) * (ts[j] - ts[near[0]]) / (ts[near[0]] - ts[near[1]]);
4415    }
4416    Ok(())
4417}
4418
4419/// A cap's pcurve for a lofted edge: its dense image on the cap's surface.
4420fn projected_pcurve(surface: &NurbsSurface, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
4421    let [d0, d1] = frag(curve.domain(), "domain")?;
4422    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
4423    let mut uv = Vec::with_capacity(ts.len());
4424    let mut poles = Vec::with_capacity(ts.len());
4425    let [u0, u1] = frag(surface.domain_u(), "domain")?;
4426    let step = 1e-3 * (u1 - u0);
4427    for &t in &ts {
4428        let x = frag(curve.evaluate(t), "point")?;
4429        let foot = frag(crate::project_point_to_surface(surface, x), "project")?;
4430        if foot.distance > 1e-6 * (1.0 + x.length()) {
4431            return Err(refuse("loft_cap", format!("a lofted edge leaves its cap by {} at {x:?}", foot.distance)));
4432        }
4433        uv.push(Vec3::new(foot.u, foot.v, 0.0));
4434        // A pole of the surface: its points do not move with the first
4435        // parameter there.
4436        let aside = if foot.u + step <= u1 { foot.u + step } else { foot.u - step };
4437        let moved = frag(surface.evaluate(aside, foot.v), "point")?.sub(frag(surface.evaluate(foot.u, foot.v), "point")?).length();
4438        poles.push(moved <= 1e-9 * (1.0 + x.length()));
4439    }
4440    continue_pole_angles(&mut uv, &ts, &poles)?;
4441    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "projected_pcurve")?;
4442    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
4443}
4444
4445type Signature = (Vec<(usize, usize, bool)>, Vec<(bool, Vec<(usize, bool)>)>, Vec<(usize, bool)>);
4446
4447fn signature(split: &Split) -> Result<Signature, KernelRefusal> {
4448    Ok((
4449        split.curves.iter().map(|c| (c.start, c.end, c.degenerate)).collect(),
4450        split.caps.iter().map(|cap| (cap.front, cap.coedges.iter().map(|&(c, f, _)| (c, f)).collect())).collect(),
4451        split.grazing()?,
4452    ))
4453}
4454
4455fn lofted(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<BrepSolid, KernelRefusal> {
4456    let split_at = |t: f64| -> Result<Split, KernelRefusal> {
4457        let mut frozen = *screw;
4458        frozen.frozen = Some(t);
4459        split_revolved(&frozen, origin, axis, radial, meridian)
4460    };
4461    let mut lambdas: Vec<f64> = (0..=LOFT_SAMPLES).map(|i| i as f64 / LOFT_SAMPLES as f64).collect();
4462    // World samples of grazing curve c at time t, in the wall's direction.
4463    let samples_of = |split: &Split, c: usize, back_forward: bool, t: f64| -> Result<Vec<Vec3>, KernelRefusal> {
4464        let Some(list) = &split.curves[c].samples else {
4465            return Err(refuse("loft_samples", "a grazing curve has no exact samples to loft".into()));
4466        };
4467        let mut world: Vec<Vec3> = list.iter().map(|&x| screw.apply(t, x)).collect();
4468        if back_forward {
4469            world.reverse();
4470        }
4471        Ok(world)
4472    };
4473    // Time breaks start even and are refined only in the spans whose middle
4474    // misses, by the quintic's h^6 error: a smooth stretch of the motion keeps
4475    // its long spans (doubling everywhere tripled the wall for one bend).
4476    let mut fractions: Vec<f64> = (0..=15).map(|j| j as f64 / 15.0).collect();
4477    loop {
4478        let count = fractions.len() - 1;
4479        // The walls' second parameter runs 0 -> 1 over the motion.
4480        let times: Vec<f64> = fractions.iter().map(|&f| if f == 1.0 { screw.t1 } else { screw.t0 + (screw.t1 - screw.t0) * f }).collect();
4481        let splits: Vec<Split> = times.iter().map(|&t| split_at(t)).collect::<Result<_, _>>()?;
4482        if splits.iter().any(|split| !split.slides.is_empty() || !split.slide_sides.is_empty()) {
4483            return Err(refuse("loft_structure", "a flat end that slides within its own plane is not lofted".into()));
4484        }
4485        let shape = signature(&splits[0])?;
4486        for split in &splits[1..] {
4487            if signature(split)? != shape {
4488                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
4489            }
4490        }
4491        let grazing = shape.2.clone();
4492        if grazing.is_empty() {
4493            return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
4494        }
4495        let scale = splits[0].scale + screw.extent;
4496        let target = LOFT_TARGET * scale;
4497        // Walls: per grazing curve, rows along it at each time, then across time.
4498        let mut walls = Vec::with_capacity(grazing.len());
4499        // Every wall's exact samples at every time.
4500        let mut sampled: Vec<Vec<Vec<Vec3>>> = Vec::with_capacity(grazing.len());
4501        for &(c, back_forward) in &grazing {
4502            let mut at_times = Vec::with_capacity(times.len());
4503            for (j, split) in splits.iter().enumerate() {
4504                let points = samples_of(split, c, back_forward, times[j])?;
4505                if points.len() != lambdas.len() {
4506                    if points.len() < 13 || points.len() % 2 == 0 {
4507                        return Err(refuse("loft_samples", "a grazing curve's exact samples cannot be lofted".into()));
4508                    }
4509                    lambdas = (0..points.len()).map(|i| i as f64 / (points.len() - 1) as f64).collect();
4510                }
4511                at_times.push(points);
4512            }
4513            sampled.push(at_times);
4514        }
4515        // A row through every `stride`-th sample: its worst miss at the
4516        // samples it leaves out, over every wall and time.
4517        let thinned = |stride: usize| -> Result<f64, KernelRefusal> {
4518            let coarse_lambdas: Vec<f64> = lambdas.iter().step_by(stride).copied().collect();
4519            let mut worst = 0.0f64;
4520            for at_times in &sampled {
4521                for points in at_times {
4522                    let coarse_points: Vec<Vec3> = points.iter().step_by(stride).copied().collect();
4523                    let coarse = frag(crate::interpolate_curve(&coarse_points, 5, &coarse_lambdas), "loft_row")?;
4524                    for (i, x) in points.iter().enumerate().filter(|(i, _)| i % stride != 0) {
4525                        worst = worst.max(frag(coarse.evaluate(lambdas[i]), "loft_row")?.sub(*x).length());
4526                    }
4527                }
4528            }
4529            Ok(worst)
4530        };
4531        // Each wall's rows pass through as few of its samples as hold every
4532        // exact sample within a quarter of the target, at every time (a loop
4533        // smooth but for one sharp bend needs its samples only there, and the
4534        // wall's size is what the solid's users pay for): from every 16th,
4535        // a stretch that misses at a sample it leaves out gets its middle one.
4536        let spans = lambdas.len() - 1;
4537        let mut kept: Vec<Vec<usize>> = Vec::with_capacity(sampled.len());
4538        for at_times in &sampled {
4539            let coarsest = if spans % 16 == 0 && spans >= 96 { 16 } else { 1 };
4540            let mut subset: Vec<usize> = (0..=spans).step_by(coarsest).collect();
4541            loop {
4542                let subset_lambdas: Vec<f64> = subset.iter().map(|&i| lambdas[i]).collect();
4543                let mut misses = vec![0.0f64; subset.len() - 1];
4544                for points in at_times {
4545                    let row_points: Vec<Vec3> = subset.iter().map(|&i| points[i]).collect();
4546                    let row = frag(crate::interpolate_curve(&row_points, 5, &subset_lambdas), "loft_row")?;
4547                    for k in 0..subset.len() - 1 {
4548                        for i in subset[k] + 1..subset[k + 1] {
4549                            misses[k] = misses[k].max(frag(row.evaluate(lambdas[i]), "loft_row")?.sub(points[i]).length());
4550                        }
4551                    }
4552                }
4553                let mut refined = Vec::with_capacity(2 * subset.len());
4554                for k in 0..subset.len() - 1 {
4555                    refined.push(subset[k]);
4556                    if misses[k] > 0.25 * target {
4557                        refined.push((subset[k] + subset[k + 1]) / 2);
4558                    }
4559                }
4560                refined.push(spans);
4561                if refined.len() == subset.len() {
4562                    break;
4563                }
4564                subset = refined;
4565            }
4566            kept.push(subset);
4567        }
4568        // Where a wall keeps neighbouring samples there is none left out
4569        // between them to measure at: a row passes through its samples, and
4570        // between them it is as good as the loop is smooth at that spacing.
4571        // Its miss there is estimated from the rows through every other
4572        // sample, scaled by the quintic's 2^-6.
4573        let dense = kept.iter().any(|subset| subset.windows(2).any(|pair| pair[1] == pair[0] + 1));
4574        let between = if dense { thinned(2)? / 64.0 } else { 0.0 };
4575        for (index, &(c, back_forward)) in grazing.iter().enumerate() {
4576            let row_lambdas: Vec<f64> = kept[index].iter().map(|&i| lambdas[i]).collect();
4577            let mut rows: Vec<NurbsCurve> = Vec::with_capacity(times.len());
4578            for points in &sampled[index] {
4579                let row_points: Vec<Vec3> = kept[index].iter().map(|&i| points[i]).collect();
4580                rows.push(frag(crate::interpolate_curve(&row_points, 5, &row_lambdas), "loft_row")?);
4581            }
4582            let knots_u = rows[0].knots.clone();
4583            let mut net: Vec<Vec<Vec4>> = Vec::with_capacity(rows[0].control_points.len());
4584            let mut knots_v = Vec::new();
4585            for k in 0..rows[0].control_points.len() {
4586                let column: Vec<Vec3> = rows.iter().map(|row| row.control_points[k].point()).collect::<Result<_, _>>().map_err(|e| refuse("loft", e))?;
4587                let across = frag(crate::interpolate_curve(&column, 5, &fractions), "loft_column")?;
4588                knots_v = across.knots.clone();
4589                net.push(across.control_points.clone());
4590            }
4591            let surface = frag(NurbsSurface::new(5, 5, knots_u, knots_v, net), "loft_wall")?;
4592            walls.push((c, back_forward, surface, rows.first().cloned().expect("rows"), rows.last().cloned().expect("rows")));
4593        }
4594        if between > target {
4595            return Err(refuse("loft_rows", format!("the lofted wall's rows stay about {between:e} off the grazing loop between its samples")));
4596        }
4597        // Against the exact loop in the middle of each span, every sample.
4598        let mut misses = vec![0.0f64; count];
4599        for j in 0..count {
4600            let t = 0.5 * (times[j] + times[j + 1]);
4601            let fraction = 0.5 * (fractions[j] + fractions[j + 1]);
4602            let split = split_at(t)?;
4603            if signature(&split)? != shape {
4604                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
4605            }
4606            for (c, back_forward, surface, _, _) in &walls {
4607                let exact = samples_of(&split, *c, *back_forward, t)?;
4608                for (i, x) in exact.iter().enumerate() {
4609                    misses[j] = misses[j].max(frag(surface.evaluate(lambdas[i], fraction), "loft_check")?.sub(*x).length());
4610                }
4611            }
4612        }
4613        let worst = misses.iter().copied().fold(0.0f64, f64::max);
4614        if worst > target {
4615            if count > 2000 {
4616                return Err(refuse("loft_accuracy", format!("the lofted wall stays {worst:e} off the grazing loop")));
4617            }
4618            // A span missing by more than half the target is cut into
4619            // ceil((e / (target / 4))^(1/6)) pieces; the rest stay.
4620            let mut refined = Vec::with_capacity(2 * fractions.len());
4621            for j in 0..count {
4622                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 };
4623                for k in 0..pieces {
4624                    refined.push(fractions[j] + (fractions[j + 1] - fractions[j]) * k as f64 / pieces as f64);
4625                }
4626            }
4627            refined.push(1.0);
4628            fractions = refined;
4629            continue;
4630        }
4631        // Each K corner's path through the sample times.
4632        let mut paths: HashMap<usize, Vec<Vec3>> = HashMap::new();
4633        for &(c, _) in &grazing {
4634            for r in [splits[0].curves[c].start, splits[0].curves[c].end] {
4635                paths.entry(r).or_insert_with(|| splits.iter().zip(&times).map(|(split, &t)| screw.apply(t, split.points[r])).collect());
4636            }
4637        }
4638        return assemble_lofted(screw, &splits[0], &splits[count], &walls, &fractions, &paths, target);
4639    }
4640}
4641
4642/// Refuse a lofted wall with an edge of regression: across one the wall's
4643/// normal turns over, and the band beside it lies inside nearby poses (the
4644/// sweep folds within a few degrees of the motion, which no probe walk is
4645/// dense enough to be sure of seeing). Normals are compared between
4646/// neighbours on every time row and between rows, outside what the end trims
4647/// take away (`removed`, chart rings) and a few columns off its edge (a fold
4648/// line meets the end at the cut's own ends). `fit`: how near the wall keeps
4649/// to its exact loop (a length).
4650fn wall_regular(surface: &NurbsSurface, fractions: &[f64], removed: &[&[[f64; 2]]], fit: f64) -> Result<(), KernelRefusal> {
4651    const COLUMNS: usize = 4 * LOFT_SAMPLES;
4652    let mut rows: Vec<f64> = Vec::with_capacity(2 * fractions.len());
4653    for j in 0..fractions.len() {
4654        rows.push(fractions[j]);
4655        if j + 1 < fractions.len() {
4656            rows.push(0.5 * (fractions[j] + fractions[j + 1]));
4657        }
4658    }
4659    let normal = |u: f64, v: f64| -> Result<Option<Vec3>, KernelRefusal> {
4660        let h = 1e-6;
4661        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));
4662        let du = frag(surface.evaluate(ub, v), "regular")?.sub(frag(surface.evaluate(ua, v), "regular")?).scale(1.0 / (ub - ua));
4663        let dv = frag(surface.evaluate(u, vb), "regular")?.sub(frag(surface.evaluate(u, va), "regular")?).scale(1.0 / (vb - va));
4664        // Where the wall's two directions all but line up, or it is no
4665        // wider than its own fit's ripple (a corner it pinches to), it has
4666        // no normal to speak of: the fit's noise would turn it.
4667        let cross = du.cross(dv);
4668        if cross.length() <= 1e-6 * du.length() * dv.length() || du.length().min(dv.length()) <= 1e3 * fit {
4669            return Ok(None);
4670        }
4671        Ok(cross.normalized().ok())
4672    };
4673    let mut previous: Option<Vec<Option<Vec3>>> = None;
4674    for &v in &rows {
4675        // What a trim takes away is not part of the body.
4676        let row: Vec<Option<Vec3>> = (0..=COLUMNS)
4677            .map(|i| {
4678                let u = i as f64 / COLUMNS as f64;
4679                if removed.iter().any(|ring| inside_ring(ring, [u, v]) || near_ring(ring, [u, v], 4.0 / COLUMNS as f64)) { Ok(None) } else { normal(u, v) }
4680            })
4681            .collect::<Result<_, _>>()?;
4682        for i in 0..COLUMNS {
4683            if let (Some(a), Some(b)) = (row[i], row[i + 1]) {
4684                if a.dot(b) < -0.5 {
4685                    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)));
4686                }
4687            }
4688            if let Some(Some(Some(a))) = previous.as_ref().map(|p| p.get(i).copied()) {
4689                if let Some(b) = row[i] {
4690                    if a.dot(b) < -0.5 {
4691                        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)));
4692                    }
4693                }
4694            }
4695        }
4696        previous = Some(row);
4697    }
4698    Ok(())
4699}
4700
4701/// A stretch of a wall's row at v, from u = a to u = b, as an edge's curve.
4702fn row_piece(wall: &NurbsSurface, v: f64, a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
4703    let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
4704    let along: Vec<Vec3> = ts.iter().map(|&s| frag(wall.evaluate((a + (b - a) * s).clamp(0.0, 1.0), v), "wall")).collect::<Result<_, _>>()?;
4705    frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
4706}
4707
4708/// A wall's end row in pieces around its trims and breaks (one more than the
4709/// spans), at v.
4710fn row_pieces(wall: &NurbsSurface, v: f64, spans: &[TrimSpan]) -> Result<Vec<NurbsCurve>, KernelRefusal> {
4711    let mut pieces = Vec::with_capacity(spans.len() + 1);
4712    let mut from = 0.0;
4713    for span in spans {
4714        pieces.push(row_piece(wall, v, from, span.lambdas[0])?);
4715        from = span.lambdas[1];
4716    }
4717    pieces.push(row_piece(wall, v, from, 1.0)?);
4718    Ok(pieces)
4719}
4720
4721/// The wall over u ∈ [a, b] only, in the same parameters.
4722/// Can `pcurve` (in a wall's chart) meet the split segment u = tip.u, v in
4723/// [v_lo, v_hi], anywhere but at the tip itself? A pcurve that ENDS at the
4724/// tip (a side of the double curve) touches it there: a short stub at that end
4725/// must leave the tip into one side of the line or away from the segment, and
4726/// the rest is tested. Every other piece is decided on the convex hull of its
4727/// control points (positive weights), halved where a hull straddles the
4728/// segment; one still straddling after 24 halvings counts as meeting it.
4729fn hull_meets_segment(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64) -> Result<bool, KernelRefusal> {
4730    let uv = |p: &Vec4| [p.x / p.w, p.y / p.w];
4731    let near_tip = |p: [f64; 2]| (p[0] - tip[0]).abs() <= 1e-9 && (p[1] - tip[1]).abs() <= 1e-9;
4732    let (first, last) = (uv(&pcurve.control_points[0]), uv(&pcurve.control_points[pcurve.control_points.len() - 1]));
4733    if !(near_tip(first) || near_tip(last)) {
4734        return hull_straddles(pcurve, tip, v_lo, v_hi, 0);
4735    }
4736    if near_tip(first) && near_tip(last) {
4737        return Ok(true);
4738    }
4739    let [d0, d1] = frag(pcurve.domain(), "domain")?;
4740    let at = if near_tip(first) { d0 + 1e-3 * (d1 - d0) } else { d1 - 1e-3 * (d1 - d0) };
4741    let (a, b) = frag(pcurve.split(at), "split")?;
4742    let (stub, rest) = if near_tip(first) { (a, b) } else { (b, a) };
4743    let side: Vec<f64> = stub.control_points.iter().map(|p| uv(p)[0] - tip[0]).collect();
4744    let one_side = side.iter().all(|d| *d >= -1e-12) || side.iter().all(|d| *d <= 1e-12);
4745    // The segment runs from the tip towards the far row: away is the other way.
4746    let segment_below = v_lo < tip[1] - 1e-12;
4747    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 });
4748    if !(one_side || away) {
4749        return Ok(true);
4750    }
4751    hull_straddles(&rest, tip, v_lo, v_hi, 0)
4752}
4753
4754fn hull_straddles(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64, depth: usize) -> Result<bool, KernelRefusal> {
4755    let points: Vec<[f64; 2]> = pcurve.control_points.iter().map(|p| [p.x / p.w, p.y / p.w]).collect();
4756    let (u_min, u_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[0]), hi.max(p[0])));
4757    let (w_min, w_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[1]), hi.max(p[1])));
4758    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 {
4759        return Ok(false);
4760    }
4761    if depth >= 24 {
4762        return Ok(true);
4763    }
4764    let [d0, d1] = frag(pcurve.domain(), "domain")?;
4765    match pcurve.split(0.5 * (d0 + d1)) {
4766        Ok((a, b)) => Ok(hull_straddles(&a, tip, v_lo, v_hi, depth + 1)? || hull_straddles(&b, tip, v_lo, v_hi, depth + 1)?),
4767        // Too short to halve: count it as meeting the segment.
4768        Err(_) => Ok(true),
4769    }
4770}
4771
4772/// `BREP_SWEEP_SPLIT_CROSSING` (default on; `=0` off): a lofted wall that
4773/// turns over near one end is split at its swallowtail's point whenever the
4774/// split segment to the far row crosses no trim curve, not only where the
4775/// trimmed row keeps to its side of the tip's u; otherwise the wall stays one
4776/// face carrying its double curve as a slot (one edge used twice), which
4777/// meshes poorly at the slot's tip.
4778fn split_crossing_on() -> bool {
4779    crate::switch!("BREP_SWEEP_SPLIT_CROSSING", true)
4780}
4781
4782fn restrict_u(surface: &NurbsSurface, a: f64, b: f64) -> Result<NurbsSurface, KernelRefusal> {
4783    let [u0, u1] = frag(surface.domain_u(), "domain")?;
4784    if a <= u0 + 1e-12 && b >= u1 - 1e-12 {
4785        return Ok(surface.clone());
4786    }
4787    let columns = surface.control_points[0].len();
4788    let mut knots = Vec::new();
4789    let mut net: Vec<Vec<Vec4>> = Vec::new();
4790    for j in 0..columns {
4791        let line: Vec<Vec4> = surface.control_points.iter().map(|row| row[j]).collect();
4792        let mut curve = frag(NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), line), "restrict")?;
4793        if b < u1 - 1e-12 {
4794            curve = frag(curve.split(b), "restrict")?.0;
4795        }
4796        if a > u0 + 1e-12 {
4797            curve = frag(curve.split(a), "restrict")?.1;
4798        }
4799        if j == 0 {
4800            knots = curve.knots.clone();
4801            net = vec![Vec::with_capacity(columns); curve.control_points.len()];
4802        }
4803        for (i, point) in curve.control_points.iter().enumerate() {
4804            net[i].push(*point);
4805        }
4806    }
4807    frag(NurbsSurface::new(surface.degree_u, surface.degree_v, knots, surface.knots_v.clone(), net), "restrict")
4808}
4809
4810/// One place a wall is cut back where an end pose bulges past it: the wall
4811/// parameter range [λa, λb] along the grazing loop where the trim leaves and
4812/// rejoins it, the cut (from the point at λa to the point at λb, on both the
4813/// wall and the pose), the wall's side of the trim from λa to λb (`chain`),
4814/// the double curve and its swallowtail point if the trim follows one, and
4815/// the part of the wall's chart it takes away (`removed`, (u, v) points
4816/// around it).
4817struct TrimSpan {
4818    lambdas: [f64; 2],
4819    points: [Vec3; 2],
4820    /// None: no cut at all, only a break in the end's row at λa = λb (where
4821    /// a line splitting the wall lands on it).
4822    cut: Option<NurbsCurve>,
4823    chain: Vec<(TrimPiece, bool, NurbsCurve)>,
4824    slot: Option<(NurbsCurve, Vec3)>,
4825    /// The swallowtail's point in the wall's chart (u, v), where the trim
4826    /// follows a double curve.
4827    tip: Option<[f64; 2]>,
4828    removed: Vec<[f64; 2]>,
4829}
4830
4831/// Every place an end pose bulges past one wall, in order along the loop, and
4832/// the loop's pieces around them (one more than the spans).
4833struct EndTrim {
4834    spans: Vec<TrimSpan>,
4835    pieces: Vec<NurbsCurve>,
4836}
4837
4838/// Which edge a piece of a trimmed wall's end runs on: the cut it shares with
4839/// the cap, or the wall's own double curve (both of the slot's sides).
4840#[derive(Clone, Copy, PartialEq, Eq, Debug)]
4841enum TrimPiece {
4842    Cut,
4843    Slot,
4844}
4845
4846/// The cut of a lofted wall (u along the grazing loop, v the motion's time
4847/// fraction) by the pose at its end (`end` 0: v = 0, 1: v = 1), if the pose
4848/// bulges past it, else None.
4849///
4850/// The wall meets the pose along K and leaves it to second order (K grazes),
4851/// so with ε the time fraction from the end, f = d / ε² (d the pose's signed
4852/// distance) is smooth up to the end. The part of the wall inside the pose is
4853/// where f < 0; its boundary is traced as the curve f = 0 from the end and back
4854/// to it. It need not be a graph over u: a tongue of it may run on past where
4855/// it left the end.
4856///
4857/// `fit`: how near the wall keeps to the exact loop (a length).
4858fn end_trim(screw: &Screw, split: &Split, t: f64, wall: &NurbsSurface, end: usize, fit: f64) -> Result<Option<EndTrim>, KernelRefusal> {
4859    let v_of = |e: f64| if end == 1 { 1.0 - e } else { e };
4860    let at = |u: f64, e: f64| -> Result<Vec3, KernelRefusal> { frag(wall.evaluate(u.clamp(0.0, 1.0), v_of(e)), "wall") };
4861    let f = |u: f64, e: f64| -> Result<f64, KernelRefusal> { Ok(split.distance(screw.invert(t, at(u, e)?)) / (e * e)) };
4862    // Below `floor` the walls' fit swamps d / ε².
4863    let floor = 1e-3;
4864    // How far into the motion (as a fraction of it) a trim may reach (a fold
4865    // band can run most of a span); past that the end pose meets a distant
4866    // part of the sweep (`end_trim_deep`).
4867    let window = 0.6;
4868    let noise = 2.0 * fit / (floor * floor);
4869    // Where the wall dips into the pose just off the end.
4870    let n = 2000;
4871    let edge: Vec<f64> = (0..=n).map(|i| f(i as f64 / n as f64, floor)).collect::<Result<_, _>>()?;
4872    // Inside: the stretches where f is negative, those that dip below the
4873    // fit's noise somewhere (a stretch that never does is the fit's own).
4874    let mut inside: Vec<bool> = edge.iter().map(|&x| x < 0.0).collect();
4875    let mut i = 0;
4876    while i <= n {
4877        if !inside[i] {
4878            i += 1;
4879            continue;
4880        }
4881        let mut j = i;
4882        while j < n && inside[j + 1] {
4883            j += 1;
4884        }
4885        if edge[i..=j].iter().all(|&x| x >= -noise) {
4886            for flag in &mut inside[i..=j] {
4887                *flag = false;
4888            }
4889        }
4890        i = j + 1;
4891    }
4892    if !inside.iter().any(|&x| x) {
4893        // Nothing near the end; a pocket deeper in is caught below.
4894        return pierced(&f, floor, window, noise, &[]);
4895    }
4896    if inside[0] || inside[n] || inside[1] || inside[n - 1] {
4897        return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
4898    }
4899    // Crossings of the floor line, by bisection between samples of either sign.
4900    let mut crossings: Vec<f64> = Vec::new();
4901    for i in 0..n {
4902        if inside[i] != inside[i + 1] {
4903            let (mut a, mut b) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
4904            let a_inside = inside[i];
4905            for _ in 0..60 {
4906                let mid = 0.5 * (a + b);
4907                if (f(mid, floor)? < 0.0) == a_inside { a = mid } else { b = mid }
4908            }
4909            crossings.push(0.5 * (a + b));
4910        }
4911    }
4912    if crossings.len() % 2 != 0 || crossings.is_empty() {
4913        return Err(refuse("end_trim", "an end pose's bulges past a wall do not pair up".into()));
4914    }
4915    // Trace f = 0 from the first crossing of each pair into the wall until it
4916    // returns to the floor; it must come back at the pair's other crossing.
4917    let gradient = |u: f64, e: f64| -> Result<[f64; 2], KernelRefusal> {
4918        let h = 1e-6;
4919        Ok([(f(u + h, e)? - f(u - h, e)?) / (2.0 * h), (f(u, e + h)? - f(u, e - h)?) / (2.0 * h)])
4920    };
4921    let settle = |mut p: [f64; 2]| -> Result<[f64; 2], KernelRefusal> {
4922        for _ in 0..30 {
4923            let value = f(p[0], p[1])?;
4924            let g = gradient(p[0], p[1])?;
4925            let norm = g[0] * g[0] + g[1] * g[1];
4926            if norm == 0.0 {
4927                return Err(refuse("end_trim", "the cut of an end pose has a flat point".into()));
4928            }
4929            p = [p[0] - value * g[0] / norm, p[1] - value * g[1] / norm];
4930            if value.abs() * p[1] * p[1] < 1e-14 * split.scale {
4931                break;
4932            }
4933        }
4934        Ok(p)
4935    };
4936    let step = 1e-3;
4937    let mut cuts: Vec<Vec<[f64; 2]>> = Vec::new();
4938    // Each cut starts at the lowest crossing not yet used and ends at the
4939    // unused one it comes back to.
4940    let mut unused: Vec<f64> = crossings.clone();
4941    while !unused.is_empty() {
4942        let start = unused.remove(0);
4943        let mut points: Vec<[f64; 2]> = vec![[start, floor]];
4944        let mut heading = [0.0, 1.0];
4945        loop {
4946            let last = *points.last().expect("points");
4947            let g = gradient(last[0], last[1])?;
4948            let length = g[0].hypot(g[1]);
4949            let mut tangent = [-g[1] / length, g[0] / length];
4950            if tangent[0] * heading[0] + tangent[1] * heading[1] < 0.0 {
4951                tangent = [-tangent[0], -tangent[1]];
4952            }
4953            let next = settle([last[0] + step * tangent[0], last[1] + step * tangent[1]])?;
4954            if next[1] < floor {
4955                break;
4956            }
4957            if next[0] <= 1e-3 || next[0] >= 1.0 - 1e-3 {
4958                return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
4959            }
4960            if next[1] > window {
4961                return Err(refuse("end_trim_deep", "an end pose holds a deep part of a wall".into()));
4962            }
4963            if points.len() > 20_000 {
4964                return Err(refuse("end_trim", "the cut of an end pose does not close".into()));
4965            }
4966            heading = [next[0] - last[0], next[1] - last[1]];
4967            points.push(next);
4968        }
4969        let back = *points.last().expect("points");
4970        let Some(at_end) = unused.iter().position(|&c| (back[0] - c).abs() <= 2.0 * step) else {
4971            return Err(refuse("end_trim", "the cut of an end pose does not come back where it should".into()));
4972        };
4973        let back_at = unused.remove(at_end);
4974        // A dip that never rises off the floor and comes straight back is
4975        // the fit's noise at the end, not a bulge.
4976        if points.len() == 1 && (back_at - start).abs() <= step {
4977            continue;
4978        }
4979        points.push([back_at, floor]);
4980        // Down to the end itself along the cut's direction at the floor (taken
4981        // from the first point clearly above it).
4982        let to_end = |p: [f64; 2], rest: &[[f64; 2]], reversed: bool| -> Result<[f64; 2], KernelRefusal> {
4983            // Along the cut's own tangent there (across the gradient of f), so
4984            // the run to the end continues it smoothly.
4985            let g = gradient(p[0], p[1])?;
4986            if g[0].abs() > 1e-3 * g[1].abs() {
4987                return Ok([p[0] + g[1] / g[0] * p[1], 0.0]);
4988            }
4989            let clear = |q: &&[f64; 2]| q[1] - p[1] > 0.25 * step;
4990            let found = if reversed { rest.iter().rev().find(clear) } else { rest.iter().find(clear) };
4991            Ok(match found {
4992                Some(q) => [p[0] - (q[0] - p[0]) / (q[1] - p[1]) * p[1], 0.0],
4993                None => [p[0], 0.0],
4994            })
4995        };
4996        let count = points.len();
4997        let (first, last) = (to_end(points[0], &points[1..], false)?, to_end(points[count - 1], &points[..count - 1], true)?);
4998        if [first[0], last[0]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
4999            return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
5000        }
5001        points.insert(0, first);
5002        points.push(last);
5003        if points[0][0] > points[points.len() - 1][0] {
5004            points.reverse();
5005        }
5006        cuts.push(points);
5007    }
5008    let rings: Vec<&[[f64; 2]]> = cuts.iter().map(|c| c.as_slice()).collect();
5009    pierced(&f, floor, window, noise, &rings)?;
5010    let chart = |p: [f64; 2]| [p[0], v_of(p[1])];
5011    // A curve on the wall through chart points and its pcurve, both on the
5012    // given parameters (normalized to [0, 1]); chart-length parameters by
5013    // default (the wall's own speed collapses near an edge of regression, so
5014    // 3D chord lengths would bunch them).
5015    let chart_lengths = |chart_points: &[[f64; 2]]| -> Vec<f64> {
5016        let mut params = vec![0.0];
5017        for k in 1..chart_points.len() {
5018            let gap = (chart_points[k][0] - chart_points[k - 1][0]).hypot(chart_points[k][1] - chart_points[k - 1][1]);
5019            params.push(params[k - 1] + gap.max(1e-15));
5020        }
5021        params
5022    };
5023    // Returns the curve, its pcurve, and how far the pcurve's image strays
5024    // from the curve between the points.
5025    let curve_through = |chart_points: &[[f64; 2]], params: &[f64], what: &'static str| -> Result<(NurbsCurve, NurbsCurve, f64), KernelRefusal> {
5026        let total = *params.last().expect("params");
5027        let params: Vec<f64> = params.iter().map(|x| x / total).collect();
5028        let world: Vec<Vec3> = chart_points.iter().map(|p| at(p[0], p[1])).collect::<Result<_, _>>()?;
5029        let uv: Vec<Vec3> = chart_points.iter().map(|p| Vec3::new(p[0], v_of(p[1]), 0.0)).collect();
5030        let (curve, pcurve) = (frag(crate::interpolate_curve(&world, 5, &params), what)?, frag(crate::interpolate_curve(&uv, 5, &params), what)?);
5031        // Between the points too: the pcurve's image stays on the curve.
5032        let mut worst = 0.0f64;
5033        for k in 0..params.len() - 1 {
5034            let s = 0.5 * (params[k] + params[k + 1]);
5035            let q = frag(pcurve.evaluate(s), "pcurve")?;
5036            let e = if end == 1 { 1.0 - q.y } else { q.y };
5037            worst = worst.max(at(q.x, e)?.sub(frag(curve.evaluate(s), "curve")?).length());
5038        }
5039        Ok((curve, pcurve, worst))
5040    };
5041    // A trim curve is refined until its pcurve's image is within `fine` of
5042    // it, and taken as near as it gets if within `loose` (a double curve has
5043    // a cusp at its swallowtail's point, where no finer trace helps; a
5044    // tighter bar costs a thin tool many rounds and buys no reader anything).
5045    let (fine, loose) = (1e-7 * split.scale, 1e-7 * split.scale);
5046    let missed = |what: &str| refuse("end_trim", format!("the {what}'s pcurve leaves it between its points however finely it is traced"));
5047    // The cut, refined where its fit misses: a settled point between each
5048    // pair of traced ones (on the stretches run straight to the end, their
5049    // middles).
5050    let cut_through = |mut chart_points: Vec<[f64; 2]>| -> Result<(NurbsCurve, NurbsCurve), KernelRefusal> {
5051        let mut best: Option<(NurbsCurve, NurbsCurve, f64)> = None;
5052        for _ in 0..7 {
5053            let fitted = curve_through(&chart_points, &chart_lengths(&chart_points), "cut")?;
5054            let done = fitted.2 <= fine;
5055            if best.as_ref().map_or(true, |b| fitted.2 < b.2) {
5056                best = Some(fitted);
5057            }
5058            if done {
5059                break;
5060            }
5061            let mut finer = Vec::with_capacity(2 * chart_points.len());
5062            for k in 0..chart_points.len() - 1 {
5063                finer.push(chart_points[k]);
5064                let (p, q) = (chart_points[k], chart_points[k + 1]);
5065                let middle = [0.5 * (p[0] + q[0]), 0.5 * (p[1] + q[1])];
5066                // Below the floor the cut runs straight to the end: split it there as a line.
5067                finer.push(if p[1] >= floor && q[1] >= floor { settle(middle)? } else { middle });
5068            }
5069            finer.push(chart_points[chart_points.len() - 1]);
5070            chart_points = finer;
5071        }
5072        match best {
5073            Some((curve, pcurve, worst)) if worst <= loose => Ok((curve, pcurve)),
5074            _ => Err(missed("cut")),
5075        }
5076    };
5077    let piece = |a: f64, b: f64| -> Result<NurbsCurve, KernelRefusal> {
5078        let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
5079        let along: Vec<Vec3> = ts.iter().map(|&s| at(a + (b - a) * s, 0.0)).collect::<Result<_, _>>()?;
5080        frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
5081    };
5082    // Where the wall turns over near the end (a swallowtail), the cut passes
5083    // through a point of the end's own loop K a second time, on the wall's far
5084    // sheet: there the wall's double curve starts, and the trim follows it to
5085    // the swallowtail's point and back instead of the cut's first stretch.
5086    let span_of = |points: &Vec<[f64; 2]>| -> Result<TrimSpan, KernelRefusal> {
5087        if let Some((k, ua, b)) = double_start(&at, points, floor)? {
5088            // The double curve, traced more finely while its fit misses.
5089            let mut traced: Option<(Vec<[f64; 2]>, Vec<[f64; 2]>, NurbsCurve, NurbsCurve, NurbsCurve, f64)> = None;
5090            for round in 0..5 {
5091                let (a_side, b_side) = double_curve(&at, [ua, 0.0], b, window, 2e-3 / f64::from(1u32 << round))?;
5092                // Both sides on the continuation's own arc length, so the double
5093                // curve and its two pcurves share one parameter.
5094                let mut sigma = vec![0.0];
5095                for k in 1..a_side.len() {
5096                    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]));
5097                    sigma.push(sigma[k - 1] + step.max(1e-15));
5098                }
5099                let ((slot, pa, miss_a), (_, pb, miss_b)) = (curve_through(&a_side, &sigma, "double_curve")?, curve_through(&b_side, &sigma, "double_curve")?);
5100                let worst = miss_a.max(miss_b);
5101                if traced.as_ref().map_or(true, |t| worst < t.5) {
5102                    traced = Some((a_side, b_side, slot, pa, pb, worst));
5103                }
5104                if worst <= fine {
5105                    break;
5106                }
5107            }
5108            let Some((a_side, b_side, slot, pa, pb, _)) = traced.filter(|t| t.5 <= loose) else { return Err(missed("double curve")) };
5109            // The cut keeps the stretch from the far sheet's point to its end away
5110            // from where the double curve leaves K.
5111            let low = ua < points[0][0];
5112            if !low && ua <= points[points.len() - 1][0] {
5113                return Err(refuse("end_trim", "the double curve of a wall leaves its end inside the cut".into()));
5114            }
5115            let mut kept: Vec<[f64; 2]> = if low { points[k..].to_vec() } else { points[..=k].to_vec() };
5116            if low { kept[0] = b } else { *kept.last_mut().expect("kept") = b }
5117            let (cut, cut_pcurve) = cut_through(kept.clone())?;
5118            let tip = at(a_side[a_side.len() - 1][0], a_side[a_side.len() - 1][1])?;
5119            // The wall's side of the trim from the low end to the high one.
5120            let chain = if low {
5121                vec![(TrimPiece::Slot, true, pa), (TrimPiece::Slot, false, frag(pb.reversed(), "reversed")?), (TrimPiece::Cut, true, cut_pcurve)]
5122            } else {
5123                vec![(TrimPiece::Cut, true, cut_pcurve), (TrimPiece::Slot, true, pb), (TrimPiece::Slot, false, frag(pa.reversed(), "reversed")?)]
5124            };
5125            let lambdas = if low { [ua, points[points.len() - 1][0]] } else { [points[0][0], ua] };
5126            let mut removed: Vec<[f64; 2]> = Vec::new();
5127            if low {
5128                removed.extend(a_side.iter().map(|&p| chart(p)));
5129                removed.extend(b_side.iter().rev().map(|&p| chart(p)));
5130                removed.extend(kept.iter().map(|&p| chart(p)));
5131            } else {
5132                removed.extend(kept.iter().map(|&p| chart(p)));
5133                removed.extend(b_side.iter().map(|&p| chart(p)));
5134                removed.extend(a_side.iter().rev().map(|&p| chart(p)));
5135            }
5136            // Everything the end pose holds must be in what goes.
5137            let dropped: Vec<[f64; 2]> = if low { points[..k].to_vec() } else { points[k + 1..].to_vec() };
5138            for p in dropped.iter().filter(|p| p[1] > 2.0 * floor && (p[0] - b[0]).hypot(p[1] - b[1]) > 5e-3) {
5139                if !inside_ring(&removed, chart(*p)) {
5140                    return Err(refuse("end_trim", "the cut of an end pose leaves the part of the wall its double curve takes away".into()));
5141                }
5142            }
5143            let points3 = [at(lambdas[0], 0.0)?, at(lambdas[1], 0.0)?];
5144            // The double curve's sides part about its end: one keeps to
5145            // each side of the swallowtail's point along the loop, so a
5146            // line through that point splits the wall between them.
5147            let tip_chart = chart(a_side[a_side.len() - 1]);
5148            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)));
5149            let ((a_lo, a_hi), (b_lo, b_hi)) = (side(&a_side), side(&b_side));
5150            let parted = (a_lo >= -1e-9 && b_hi <= 1e-9) || (a_hi <= 1e-9 && b_lo >= -1e-9);
5151            if !parted {
5152                return Err(refuse("end_trim", "the two sides of a wall's double curve do not keep to either side of its end".into()));
5153            }
5154            return Ok(TrimSpan { lambdas, points: points3, cut: Some(cut), chain, slot: Some((slot, tip)), tip: Some(tip_chart), removed });
5155        }
5156        let (cut, wall_pcurve) = cut_through(points.clone())?;
5157        let (la, lb) = (points[0][0], points[points.len() - 1][0]);
5158        let removed: Vec<[f64; 2]> = points.iter().map(|&p| chart(p)).collect();
5159        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 })
5160    };
5161    if cuts.is_empty() {
5162        return pierced(&f, floor, window, noise, &[]);
5163    }
5164    let mut spans = Vec::with_capacity(cuts.len());
5165    for points in &cuts {
5166        spans.push(span_of(points)?);
5167    }
5168    spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
5169    // A trim wholly inside what another takes away adds nothing (a bulge of
5170    // the end pose inside a swallowtail's slot).
5171    let edge_row = v_of(0.0);
5172    let within = |inner: &TrimSpan, outer: &TrimSpan| -> bool {
5173        inner.lambdas[0] >= outer.lambdas[0]
5174            && inner.lambdas[1] <= outer.lambdas[1]
5175            && 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))
5176    };
5177    let mut k = 0;
5178    while k < spans.len() {
5179        if (0..spans.len()).any(|j| j != k && within(&spans[k], &spans[j])) {
5180            spans.remove(k);
5181        } else {
5182            k += 1;
5183        }
5184    }
5185    for pair in spans.windows(2) {
5186        if pair[0].lambdas[1] >= pair[1].lambdas[0] {
5187            return Err(refuse("end_trim", "an end pose's trims of a wall overlap".into()));
5188        }
5189    }
5190    let mut pieces = Vec::with_capacity(spans.len() + 1);
5191    let mut from = 0.0;
5192    for span in &spans {
5193        pieces.push(piece(from, span.lambdas[0])?);
5194        from = span.lambdas[1];
5195    }
5196    pieces.push(piece(from, 1.0)?);
5197    Ok(Some(EndTrim { spans, pieces }))
5198}
5199
5200
5201
5202/// Is q within `reach` of the closed polygon `ring`'s sides?
5203fn near_ring(ring: &[[f64; 2]], q: [f64; 2], reach: f64) -> bool {
5204    (0..ring.len()).any(|k| {
5205        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
5206        let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
5207        let length = dx * dx + dy * dy;
5208        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 };
5209        (q[0] - a[0] - s * dx).hypot(q[1] - a[1] - s * dy) < reach
5210    })
5211}
5212
5213/// Is q inside the closed polygon `ring` (its last point joins its first)?
5214fn inside_ring(ring: &[[f64; 2]], q: [f64; 2]) -> bool {
5215    let mut crossings = 0;
5216    for k in 0..ring.len() {
5217        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
5218        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]) {
5219            crossings += 1;
5220        }
5221    }
5222    crossings % 2 == 1
5223}
5224
5225/// The point of an end pose's cut (chart points (u, ε), ε the time fraction
5226/// from the end) that lies on the end's own loop K a second time, away from
5227/// the cut's ends: (its index along the cut, the loop parameter u of the point
5228/// of K it meets, and the refined (u, ε) on the cut), if there is one.
5229fn double_start(at: &dyn Fn(f64, f64) -> Result<Vec3, KernelRefusal>, points: &[[f64; 2]], floor: f64) -> Result<Option<(usize, f64, [f64; 2])>, KernelRefusal> {
5230    let n = 4000;
5231    let row: Vec<Vec3> = (0..=n).map(|i| at(i as f64 / n as f64, 0.0)).collect::<Result<_, _>>()?;
5232    let scale = row.iter().fold(0.0f64, |m, p| m.max(p.sub(row[0]).length())).max(1e-300);
5233    let mut best: Option<(f64, usize, usize)> = None;
5234    for (k, p) in points.iter().enumerate() {
5235        if p[1] < 4.0 * floor {
5236            continue;
5237        }
5238        let x = at(p[0], p[1])?;
5239        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 });
5240        // The cut nears K at its own ends in proportion to ε; the second
5241        // meeting is where that ratio drops to nothing.
5242        if best.map_or(true, |b| d / p[1] < b.0 / points[b.1][1]) {
5243            best = Some((d, k, i));
5244        }
5245    }
5246    let Some((distance, k, i)) = best else { return Ok(None) };
5247    // Coarse: the cut's points are a few thousandths of the chart apart.
5248    if distance > 5e-3 * scale {
5249        return Ok(None);
5250    }
5251    // Newton on at(b) = at(u, 0) for (b_u, b_ε, u).
5252    let mut x = [points[k][0], points[k][1], i as f64 / n as f64];
5253    let h = 1e-7;
5254    for _ in 0..40 {
5255        let g = at(x[0], x[1])?.sub(at(x[2], 0.0)?);
5256        if g.length() < 1e-13 * scale {
5257            // Not the trivial meeting of the end row with itself.
5258            if x[1] < 2.0 * floor || !(0.0..=1.0).contains(&x[0]) || !(0.0..=1.0).contains(&x[2]) {
5259                return Ok(None);
5260            }
5261            return Ok(Some((k, x[2], [x[0], x[1]])));
5262        }
5263        let c0 = at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h);
5264        let c1 = at(x[0], x[1] + h)?.sub(at(x[0], x[1] - h)?).scale(0.5 / h);
5265        let c2 = at(x[2] + h, 0.0)?.sub(at(x[2] - h, 0.0)?).scale(-0.5 / h);
5266        let det = c0.dot(c1.cross(c2));
5267        if det.abs() < 1e-300 {
5268            break;
5269        }
5270        // Cramer's rule for [c0 c1 c2] d = -g.
5271        let r = g.scale(-1.0);
5272        let d = [r.dot(c1.cross(c2)) / det, c0.dot(r.cross(c2)) / det, c0.dot(c1.cross(r)) / det];
5273        x = [x[0] + d[0], x[1] + d[1], x[2] + d[2]];
5274    }
5275    if distance < 1e-6 * scale {
5276        return Err(refuse("end_trim", "an end pose's cut meets its own loop, but not exactly enough to follow".into()));
5277    }
5278    Ok(None)
5279}
5280
5281/// The double curve of a wall from where it leaves the end (a, on the end's
5282/// loop) and its partner b on the far sheet, traced by continuation of
5283/// at(a) = at(b) in (u, ε) for both, to the swallowtail point where the two
5284/// sides meet. Returns both sides' chart points, ending at the same point.
5285fn 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> {
5286    let h = 1e-7;
5287    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);
5288    let jacobian = |x: [f64; 4]| -> Result<[Vec3; 4], KernelRefusal> {
5289        Ok([
5290            at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h),
5291            at(x[0], x[1] + h)?.sub(at(x[0], (x[1] - h).max(0.0))?).scale(1.0 / (h + x[1].min(h))),
5292            at(x[2] + h, x[3])?.sub(at(x[2] - h, x[3])?).scale(-0.5 / h),
5293            at(x[2], x[3] + h)?.sub(at(x[2], (x[3] - h).max(0.0))?).scale(-1.0 / (h + x[3].min(h))),
5294        ])
5295    };
5296    let residual = |x: [f64; 4]| -> Result<Vec3, KernelRefusal> { Ok(at(x[0], x[1])?.sub(at(x[2], x[3])?)) };
5297    // The null direction of the 3x4 Jacobian: its signed 3x3 minors.
5298    let null = |j: &[Vec3; 4]| -> [f64; 4] {
5299        let minor = |p: usize, q: usize, r: usize| j[p].dot(j[q].cross(j[r]));
5300        let n = [minor(1, 2, 3), -minor(0, 2, 3), minor(0, 1, 3), -minor(0, 1, 2)];
5301        let length = n.iter().map(|x| x * x).sum::<f64>().sqrt().max(1e-300);
5302        [n[0] / length, n[1] / length, n[2] / length, n[3] / length]
5303    };
5304    // Minimum-norm Newton back onto at(a) = at(b).
5305    let correct = |mut x: [f64; 4]| -> Result<Option<[f64; 4]>, KernelRefusal> {
5306        for _ in 0..30 {
5307            let g = residual(x)?;
5308            if g.length() < 1e-13 * scale {
5309                return Ok(Some(x));
5310            }
5311            let j = jacobian(x)?;
5312            // J Jᵀ y = -g, step = Jᵀ y.
5313            let mut m = [[0.0; 3]; 3];
5314            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]];
5315            for p in 0..3 {
5316                for q in 0..3 {
5317                    m[p][q] = (0..4).map(|c| rows[p][c] * rows[q][c]).sum();
5318                }
5319            }
5320            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]);
5321            if det.abs() < 1e-300 {
5322                return Ok(None);
5323            }
5324            let r = [-g.x, -g.y, -g.z];
5325            let solve = |col: usize| -> f64 {
5326                let mut a = m;
5327                for p in 0..3 {
5328                    a[p][col] = r[p];
5329                }
5330                (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
5331            };
5332            let y = [solve(0), solve(1), solve(2)];
5333            for c in 0..4 {
5334                x[c] += (0..3).map(|p| rows[p][c] * y[p]).sum::<f64>();
5335            }
5336        }
5337        Ok(None)
5338    };
5339    let mut x = [a[0], a[1], b[0], b[1]];
5340    let mut a_side = vec![a];
5341    let mut b_side = vec![b];
5342    let mut heading: Option<[f64; 4]> = None;
5343    loop {
5344        let separation = (x[0] - x[2]).hypot(x[1] - x[3]);
5345        if separation < 3.0 * step && a_side.len() > 2 {
5346            let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
5347            a_side.push(tip);
5348            b_side.push(tip);
5349            return Ok((a_side, b_side));
5350        }
5351        let mut t = null(&jacobian(x)?);
5352        let reference = heading.unwrap_or([0.0, 1.0, 0.0, 0.0]);
5353        if (0..4).map(|c| t[c] * reference[c]).sum::<f64>() < 0.0 {
5354            t = [-t[0], -t[1], -t[2], -t[3]];
5355        }
5356        let mut next = None;
5357        let mut length = step;
5358        for _ in 0..6 {
5359            let guess = [x[0] + length * t[0], x[1] + length * t[1], x[2] + length * t[2], x[3] + length * t[3]];
5360            if let Some(y) = correct(guess)? {
5361                next = Some(y);
5362                break;
5363            }
5364            length *= 0.5;
5365        }
5366        let Some(y) = next else {
5367            // Near the swallowtail's point the two sheets turn tangent and
5368            // Newton gives out; close there if the sides are that near.
5369            if separation < 2e-2 && a_side.len() > 2 {
5370                let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
5371                a_side.push(tip);
5372                b_side.push(tip);
5373                return Ok((a_side, b_side));
5374            }
5375            return Err(refuse("end_trim", format!("the double curve of a wall cannot be followed (sides {separation:e} apart)")));
5376        };
5377        if [y[0], y[2]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
5378            return Err(refuse("end_trim_corner", DOUBLE_CURVE_CORNER.into()));
5379        }
5380        if y[1] > window || y[3] > window || y[1] < 0.0 || y[3] < 0.0 {
5381            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())));
5382        }
5383        if a_side.len() > 20_000 {
5384            return Err(refuse("end_trim", "the double curve of a wall does not close".into()));
5385        }
5386        heading = Some([y[0] - x[0], y[1] - x[1], y[2] - x[2], y[3] - x[3]]);
5387        x = y;
5388        a_side.push([x[0], x[1]]);
5389        b_side.push([x[2], x[3]]);
5390    }
5391}
5392
5393/// Refuse a wall the end pose holds a part of that no cut encloses: a pocket
5394/// of the wall inside the pose away from the end.
5395fn pierced(
5396    f: &dyn Fn(f64, f64) -> Result<f64, KernelRefusal>,
5397    floor: f64,
5398    window: f64,
5399    noise: f64,
5400    cuts: &[&[[f64; 2]]],
5401) -> Result<Option<EndTrim>, KernelRefusal> {
5402    let enclosed = |q: [f64; 2]| -> bool { cuts.iter().any(|ring| inside_ring(ring, q)) };
5403    for i in 1..200 {
5404        for j in 1..=40 {
5405            let (u, e) = (i as f64 / 200.0, floor + (window - floor) * (j as f64 / 40.0).powi(2));
5406            // d itself against the fit's noise: f grows as 1 / ε² near the end.
5407            if f(u, e)? * e * e < -noise * floor * floor && !enclosed([u, e]) {
5408                return Err(refuse("end_trim_deep", "an end pose holds a part of a wall away from its end".into()));
5409            }
5410        }
5411    }
5412    Ok(None)
5413}
5414
5415#[allow(clippy::too_many_arguments)]
5416fn assemble_lofted(
5417    screw: &Screw,
5418    first: &Split,
5419    last: &Split,
5420    walls: &[(usize, bool, NurbsSurface, NurbsCurve, NurbsCurve)],
5421    times: &[f64],
5422    paths: &HashMap<usize, Vec<Vec3>>,
5423    fit: f64,
5424) -> Result<BrepSolid, KernelRefusal> {
5425    let mut shell = Shell::new();
5426    let ends = [(first, screw.t0), (last, screw.t1)];
5427    // Where an end pose bulges past a wall near its grazing loop (a saddle side
5428    // curving past the wall it touches), cut the wall back to where it
5429    // re-enters the pose and carry the end cap across the loop to there.
5430    let mut trims: HashMap<(usize, usize), EndTrim> = HashMap::new();
5431    // Walls split into strips along lines through their swallowtails' points.
5432    let mut split_walls: std::collections::HashSet<usize> = std::collections::HashSet::new();
5433    for (index, (_, _, surface, _, _)) in walls.iter().enumerate() {
5434        for end in 0..2 {
5435            if let Some(trim) = end_trim(screw, ends[end].0, ends[end].1, surface, end, fit)? {
5436                trims.insert((index, end), trim);
5437            }
5438        }
5439        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();
5440        wall_regular(surface, times, &removed, fit)?;
5441        // A trim along a double curve has that curve as one edge on both its
5442        // sides: on one face its two uses could not be told apart from its
5443        // 3D curve alone (the wall passes through it twice). The wall is split
5444        // along the parameter line from each swallowtail's point to the far
5445        // end's row, which that row is broken at.
5446        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() };
5447        let (tips0, tips1) = (tips_at(0), tips_at(1));
5448        if !tips0.is_empty() && !tips1.is_empty() {
5449            return Err(refuse("wall_split", "a wall turns over near both its ends".into()));
5450        }
5451        let (far, tips) = if tips0.is_empty() { (0usize, tips1) } else { (1usize, tips0) };
5452        // A straight split line serves only where the trimmed row keeps to
5453        // its own side of it: all that comes before the swallowtail's point
5454        // along the row at or below its u, all after at or above. (A cut
5455        // that bulges across it would be crossed by the line; such a wall
5456        // stays one face.)
5457        let straight = |trim: &EndTrim| -> Result<bool, KernelRefusal> {
5458            for (k, span) in trim.spans.iter().enumerate() {
5459                let Some(tip) = span.tip else { continue };
5460                let first_slot = span.chain.iter().position(|piece| piece.0 == TrimPiece::Slot).unwrap_or(0);
5461                for (j, other) in trim.spans.iter().enumerate() {
5462                    for (n, (_, _, pcurve)) in other.chain.iter().enumerate() {
5463                        let before = j < k || (j == k && n <= first_slot);
5464                        let [d0, d1] = frag(pcurve.domain(), "domain")?;
5465                        for i in 0..=32 {
5466                            let u = frag(pcurve.evaluate(d0 + (d1 - d0) * i as f64 / 32.0), "pcurve")?.x;
5467                            if (before && u > tip[0] + 1e-9) || (!before && u < tip[0] - 1e-9) {
5468                                return Ok(false);
5469                            }
5470                        }
5471                    }
5472                }
5473            }
5474            Ok(true)
5475        };
5476        // Or, where the trimmed row strays across the tip's u only beyond the
5477        // tip (near its own end), the split segment itself: from the tip to
5478        // the far row, crossed by none of either end's trim curves. Each strip
5479        // then lies on the wall over the u its own pcurves span.
5480        let crossing_free = |trim_near: &EndTrim| -> Result<bool, KernelRefusal> {
5481            let v_far = far as f64;
5482            for tip in &tips {
5483                let (v_lo, v_hi) = if v_far < tip[1] { (v_far, tip[1]) } else { (tip[1], v_far) };
5484                let ends = [Some(trim_near), trims.get(&(index, far))];
5485                for trim in ends.into_iter().flatten() {
5486                    for span in &trim.spans {
5487                        for (_, _, pcurve) in &span.chain {
5488                            if hull_meets_segment(pcurve, tip, v_lo, v_hi)? {
5489                                return Ok(false);
5490                            }
5491                        }
5492                    }
5493                }
5494            }
5495            Ok(true)
5496        };
5497        let split_here = !tips.is_empty()
5498            && match trims.get(&(index, 1 - far)) {
5499                Some(trim) => straight(trim)? || (split_crossing_on() && crossing_free(trim)?),
5500                None => false,
5501            };
5502        if split_here {
5503            split_walls.insert(index);
5504            let v_far = far as f64;
5505            let mut spans = trims.remove(&(index, far)).map(|trim| trim.spans).unwrap_or_default();
5506            for tip in &tips {
5507                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 {
5508                    return Err(refuse("wall_split", "a wall's split line lands in a trim of its far end".into()));
5509                }
5510                let point = frag(surface.evaluate(tip[0], v_far), "wall")?;
5511                spans.push(TrimSpan { lambdas: [tip[0], tip[0]], points: [point, point], cut: None, chain: Vec::new(), slot: None, tip: None, removed: Vec::new() });
5512            }
5513            spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
5514            let pieces = row_pieces(surface, v_far, &spans)?;
5515            trims.insert((index, far), EndTrim { spans, pieces });
5516        }
5517    }
5518    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
5519    let mut vertex = |shell: &mut Shell, end: usize, p: usize| -> u64 {
5520        *vertex_at.entry((end, p)).or_insert_with(|| shell.vertex(screw.apply(ends[end].1, ends[end].0.points[p])))
5521    };
5522    let grazing: HashMap<usize, usize> = walls.iter().enumerate().map(|(index, w)| (w.0, index)).collect();
5523    // Edges at each end: K curves from the walls' end rows (in the tool
5524    // curve's direction), the rest the end split's own curves moved.
5525    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
5526    let mut edge_curve: HashMap<(usize, usize), NurbsCurve> = HashMap::new();
5527    // Per trimmed wall end: the loop's piece edges, and each span's cut and
5528    // double-curve edges (u64::MAX where a span has none).
5529    let mut trim_edges: HashMap<(usize, usize), (Vec<u64>, Vec<[u64; 2]>)> = HashMap::new();
5530    // Per trimmed wall end and span: the vertex at its low end, and at the
5531    // swallowtail's point where it has one.
5532    let mut trim_vertices: HashMap<(usize, usize), Vec<(u64, Option<u64>)>> = HashMap::new();
5533    for end in 0..2 {
5534        let (split, t) = ends[end];
5535        for (c, tool_curve) in split.curves.iter().enumerate() {
5536            let used = split.caps.iter().any(|cap| cap.front == (end == 1) && cap.coedges.iter().any(|e| e.0 == c));
5537            if !used {
5538                continue;
5539            }
5540            if let Some(&index) = grazing.get(&c) {
5541                if let Some(trim) = trims.get(&(index, end)) {
5542                    // Pieces in the wall's direction: K up to the cut, the cut, K after it.
5543                    let back_forward = walls[index].1;
5544                    let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
5545                    let (vf, vt) = (vertex(&mut shell, end, from), vertex(&mut shell, end, to));
5546                    let mut piece_edges = Vec::with_capacity(trim.pieces.len());
5547                    let mut span_edges = Vec::with_capacity(trim.spans.len());
5548                    let mut start = vf;
5549                    let mut span_vertices = Vec::with_capacity(trim.spans.len());
5550                    for (span, piece) in trim.spans.iter().zip(&trim.pieces) {
5551                        let va = shell.vertex(span.points[0]);
5552                        piece_edges.push(shell.edge(piece.clone(), start, va, false)?);
5553                        let Some(cut_curve) = &span.cut else {
5554                            // A break only: the row goes on from the same vertex.
5555                            span_edges.push([u64::MAX, u64::MAX]);
5556                            span_vertices.push((va, None));
5557                            start = va;
5558                            continue;
5559                        };
5560                        let vb = shell.vertex(span.points[1]);
5561                        let cut = shell.edge(cut_curve.clone(), va, vb, false)?;
5562                        // The double curve runs from where it leaves K (at
5563                        // the low end of the span if its chain starts with
5564                        // it) to the swallowtail's point.
5565                        let (slot, tip_vertex) = match &span.slot {
5566                            Some((curve, tip)) => {
5567                                let from = if span.chain[0].0 == TrimPiece::Slot { va } else { vb };
5568                                let tip = shell.vertex(*tip);
5569                                (shell.edge(curve.clone(), from, tip, false)?, Some(tip))
5570                            }
5571                            None => (u64::MAX, None),
5572                        };
5573                        span_edges.push([cut, slot]);
5574                        span_vertices.push((va, tip_vertex));
5575                        start = vb;
5576                    }
5577                    trim_vertices.insert((index, end), span_vertices);
5578                    piece_edges.push(shell.edge(trim.pieces[trim.pieces.len() - 1].clone(), start, vt, false)?);
5579                    trim_edges.insert((index, end), (piece_edges, span_edges));
5580                    continue;
5581                }
5582            }
5583            let curve = match grazing.get(&c) {
5584                Some(&index) => {
5585                    let (_, back_forward, _, row0, row1) = &walls[index];
5586                    let row = if end == 0 { row0 } else { row1 };
5587                    if *back_forward { frag(row.reversed(), "reversed")? } else { row.clone() }
5588                }
5589                None => screw.move_curve(t, &tool_curve.curve)?,
5590            };
5591            let (a, b) = (vertex(&mut shell, end, tool_curve.start), vertex(&mut shell, end, tool_curve.end));
5592            let edge = shell.edge(curve.clone(), a, b, tool_curve.degenerate)?;
5593            edge_at.insert((end, c), edge);
5594            edge_curve.insert((end, c), curve);
5595        }
5596    }
5597    for end in 0..2 {
5598        let (split, t) = ends[end];
5599        for cap in split.caps.iter().filter(|cap| cap.front == (end == 1)) {
5600            let surface = screw.move_surface(t, &cap.surface)?;
5601            let mut coedges = Vec::with_capacity(cap.coedges.len());
5602            for (c, forward, pcurve) in &cap.coedges {
5603                if let Some(&index) = grazing.get(c) {
5604                    if let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) {
5605                        let Some(chart) = cap.chart.as_ref() else {
5606                            return Err(refuse("end_trim", "an end pose bulges past a wall beside a cap without a chart".into()));
5607                        };
5608                        // The cap runs the tool's curve forward or back; the
5609                        // pieces run the wall's way: loop piece, cut, loop
5610                        // piece, ... loop piece.
5611                        let along = *forward != walls[index].1;
5612                        let mut pieces: Vec<(u64, &NurbsCurve)> = Vec::with_capacity(2 * trim.pieces.len());
5613                        for (k, piece) in trim.pieces.iter().enumerate() {
5614                            pieces.push((piece_edges[k], piece));
5615                            if let Some(cut) = trim.spans.get(k).and_then(|span| span.cut.as_ref()) {
5616                                pieces.push((span_edges[k][0], cut));
5617                            }
5618                        }
5619                        if !along {
5620                            pieces.reverse();
5621                        }
5622                        for (edge, curve) in pieces {
5623                            coedges.push((edge, along, charted_pcurve(chart, screw, t, curve, along)?));
5624                        }
5625                        continue;
5626                    }
5627                }
5628                let pcurve = if grazing.contains_key(c) && cap.chart.is_some() {
5629                    charted_pcurve(cap.chart.as_ref().expect("chart"), screw, t, &edge_curve[&(end, *c)], *forward)?
5630                } else if grazing.contains_key(c) {
5631                    match projected_pcurve(&surface, &edge_curve[&(end, *c)], *forward) {
5632                        Ok(p) => p,
5633                        Err(error) => {
5634                            // Which: the exact samples themselves, or the row between them?
5635                            let samples = split.curves[*c].samples.as_ref().map(|list| {
5636                                list.iter()
5637                                    .map(|&x| crate::project_point_to_surface(&surface, screw.apply(t, x)).map(|f| f.distance).unwrap_or(f64::NAN))
5638                                    .fold(0.0f64, f64::max)
5639                            });
5640                            let line = split.curves[*c].curve.degree;
5641                            return Err(KernelRefusal::unsupported(
5642                                KernelStage::Classify,
5643                                "loft_cap",
5644                                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),
5645                            ));
5646                        }
5647                    }
5648                } else {
5649                    pcurve.clone()
5650                };
5651                coedges.push((edge_at[&(end, *c)], *forward, pcurve));
5652            }
5653            shell.face(surface, coedges);
5654        }
5655    }
5656    // Orbits of K's corners: interpolated through the sample times as the
5657    // walls' end columns are.
5658    let mut orbits: HashMap<usize, u64> = HashMap::new();
5659    let mut keys: Vec<usize> = paths.keys().copied().collect();
5660    keys.sort_unstable();
5661    for r in keys {
5662        let curve = frag(crate::interpolate_curve(&paths[&r], 5, times), "orbit")?;
5663        let (a, b) = (vertex(&mut shell, 0, r), vertex(&mut shell, 1, r));
5664        orbits.insert(r, shell.edge(curve, a, b, false)?);
5665    }
5666    // One piece of a wall's end row in the direction of u: (edge, traversed
5667    // forward?, pcurve that way), and where a split line meets the row right
5668    // after it: (u, v, vertex).
5669    type RowPiece = (u64, bool, NurbsCurve, Option<(f64, f64, u64)>);
5670    for (index, (c, back_forward, surface, _, _)) in walls.iter().enumerate() {
5671        let tool_curve = &first.curves[*c];
5672        let (from, to) = if *back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
5673        let row = |end: usize| -> Result<Vec<RowPiece>, KernelRefusal> {
5674            let v = end as f64;
5675            let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) else {
5676                return Ok(vec![(edge_at[&(end, *c)], !*back_forward, uv_line([0.0, v], [1.0, v])?, None)]);
5677            };
5678            let vertices = &trim_vertices[&(index, end)];
5679            let mut list: Vec<RowPiece> = Vec::new();
5680            let mut at = 0.0;
5681            for (k, span) in trim.spans.iter().enumerate() {
5682                let broken = if span.cut.is_none() { Some((span.lambdas[0], v, vertices[k].0)) } else { None };
5683                list.push((piece_edges[k], true, uv_line([at, v], [span.lambdas[0], v])?, broken));
5684                for (n, (piece, forward, pcurve)) in span.chain.iter().enumerate() {
5685                    let edge = if *piece == TrimPiece::Cut { span_edges[k][0] } else { span_edges[k][1] };
5686                    // The swallowtail's point lies between the double curve's two uses.
5687                    let between = *piece == TrimPiece::Slot && span.chain.get(n + 1).is_some_and(|next| next.0 == TrimPiece::Slot);
5688                    let tip = match (span.tip, vertices[k].1) {
5689                        (Some(tip), Some(vertex)) if between && split_walls.contains(&index) => Some((tip[0], tip[1], vertex)),
5690                        _ => None,
5691                    };
5692                    list.push((edge, *forward, pcurve.clone(), tip));
5693                }
5694                at = span.lambdas[1];
5695            }
5696            list.push((piece_edges[trim.spans.len()], true, uv_line([at, v], [1.0, v])?, None));
5697            Ok(list)
5698        };
5699        let (bottom, top) = (row(0)?, row(1)?);
5700        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());
5701        if low.len() != high.len() || low.iter().zip(&high).any(|(a, b)| (a.0 - b.0).abs() > 1e-9) {
5702            return Err(refuse("wall_split", "a wall's split lines do not run from one end's row to the other's".into()));
5703        }
5704        // The split lines, each from its lower point to its upper.
5705        let mut lines: Vec<(u64, f64, f64, f64)> = Vec::with_capacity(low.len());
5706        for (below, above) in low.iter().zip(&high) {
5707            let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
5708            let along: Vec<Vec3> = ts.iter().map(|&s| frag(surface.evaluate(below.0, below.1 + (above.1 - below.1) * s), "wall")).collect::<Result<_, _>>()?;
5709            let edge = shell.edge(frag(crate::interpolate_curve(&along, 5, &ts), "split_line")?, below.2, above.2, false)?;
5710            lines.push((edge, below.0, below.1, above.1));
5711        }
5712        // Each row in the stretches between the split lines.
5713        let stretches = |list: Vec<RowPiece>| -> Vec<Vec<(u64, bool, NurbsCurve)>> {
5714            let mut out = vec![Vec::new()];
5715            for (edge, forward, pcurve, cut) in list {
5716                out.last_mut().expect("stretch").push((edge, forward, pcurve));
5717                if cut.is_some() {
5718                    out.push(Vec::new());
5719                }
5720            }
5721            out
5722        };
5723        let (bottoms, tops) = (stretches(bottom), stretches(top));
5724        // A strip between two split lines (or the wall's sides): along the
5725        // start row, up its far side, back along the end row, down its near
5726        // side; on the wall over its own stretch of u only.
5727        for j in 0..=lines.len() {
5728            let mut coedges = bottoms[j].clone();
5729            match lines.get(j) {
5730                Some(&(edge, u, v0, v1)) => coedges.push((edge, true, uv_line([u, v0], [u, v1])?)),
5731                None => coedges.push((orbits[&to], true, uv_line([1.0, 0.0], [1.0, 1.0])?)),
5732            }
5733            for (edge, forward, pcurve) in tops[j].iter().rev() {
5734                coedges.push((*edge, !*forward, frag(pcurve.reversed(), "reversed")?));
5735            }
5736            match j.checked_sub(1).map(|k| lines[k]) {
5737                Some((edge, u, v0, v1)) => coedges.push((edge, false, uv_line([u, v1], [u, v0])?)),
5738                None => coedges.push((orbits[&from], false, uv_line([0.0, 1.0], [0.0, 0.0])?)),
5739            }
5740            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));
5741            // A strip whose trim strays past its split line (beyond the tip)
5742            // takes the wall over that u too: the parameters are the wall's.
5743            if lines.len() > 0 && split_crossing_on() {
5744                // Its control points bound each pcurve (positive weights).
5745                for (_, _, pcurve) in &coedges {
5746                    for point in &pcurve.control_points {
5747                        let u = point.x / point.w;
5748                        if u < ua - 1e-9 {
5749                            ua = u.max(0.0);
5750                        }
5751                        if u > ub + 1e-9 {
5752                            ub = u.min(1.0);
5753                        }
5754                    }
5755                }
5756            }
5757            shell.face(restrict_u(surface, ua, ub)?, coedges);
5758        }
5759    }
5760    let body = shell.solid();
5761    let issues = body.validate();
5762    if !issues.is_empty() {
5763        // Name the faces whose coedges stray: their pcurves' ends on the surface
5764        // against their edges' ends.
5765        let mut notes = Vec::new();
5766        for face in body.shells.iter().flat_map(|s| &s.faces) {
5767            for coedge in &face.loops[0].coedges {
5768                let edge = body.edges.iter().find(|e| e.id == coedge.edge_id).expect("edge");
5769                let [p0, p1] = frag(coedge.pcurve.domain(), "domain")?;
5770                let a = frag(coedge.pcurve.evaluate(p0), "uv")?;
5771                let on = frag(face.surface.evaluate_extended(a.x, a.y), "on")?;
5772                let at = frag(edge.curve.evaluate(if coedge.forward { edge.t0 } else { edge.t1 }), "at")?;
5773                if on.sub(at).length() > 1e-6 {
5774                    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));
5775                }
5776                let _ = p1;
5777            }
5778        }
5779        return Err(refuse("assembly", format!("the lofted sweep is not valid: {:?}; {}", issues.first(), notes.iter().take(4).cloned().collect::<Vec<_>>().join("; "))));
5780    }
5781    check_single_pass(screw, first, &body, &std::collections::HashSet::new())?;
5782    Ok(body)
5783}
5784
5785/// Is the world point y inside the moving tool at some time of the motion?
5786/// Steps t by the distance over a bound on the speed of any tool point near y.
5787fn covered(screw: &Screw, split: &Split, reach: Option<&ToolReach>, y: Vec3, normal: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
5788    if reach.is_some_and(|reach| reach.never_inside(screw, y, normal, margin)) {
5789        return Ok(false);
5790    }
5791    if let Some(found) = reach.and_then(|reach| reach.turn_about_parallel_axis(screw, y, margin)) {
5792        return found;
5793    }
5794    let speed = preimage_speed_bound(screw, split, y);
5795    let floor = (screw.t1 - screw.t0) * 1e-7;
5796    let glide = Glide::of(screw, y);
5797    let mut t = screw.t0;
5798    let mut steps = 0usize;
5799    loop {
5800        let p = screw.invert(t, y);
5801        let d = split.distance(p);
5802        if d < -margin {
5803            return Ok(true);
5804        }
5805        if t >= screw.t1 {
5806            return Ok(false);
5807        }
5808        if steps > 2_000_000 {
5809            return Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into()));
5810        }
5811        let first = (d.abs() + margin) / speed;
5812        let second = glide.as_ref().map_or(0.0, |glide| glide.step(split, p, t, d, margin, speed, screw.t1 - t));
5813        let second = if second.is_finite() { second } else { 0.0 };
5814        t = (t + first.max(second).max(floor)).min(screw.t1);
5815        steps += 1;
5816    }
5817}
5818
5819/// The preimage of a probe under a plain screw, as an explicit curve: with
5820/// `u` the probe's offset from the axis square to it and `v = e × u`,
5821/// `p(t) = a + (e·(y − a) − advance(t))·e + cos(ωt)·u − sin(ωt)·v`. Its
5822/// second derivative is no longer than `ω²·|u| + 2|c₂|` (`curve`).
5823///
5824/// The walk in time steps by the tool's distance over the preimage's speed:
5825/// beside a wall the tool grazes (a thread's flank, a ball's groove) the
5826/// distance stays the probe's tiny offset through the whole contact and the
5827/// walk crawls, some π·√(2R/δ) steps a probe. Where the path runs along the
5828/// tool rather than into it, its tangent line stays clear of the tool for
5829/// far longer, and the path leaves that line by no more than `curve·h²/2`:
5830/// the second-order step is the longest `h` the tool's distance from the
5831/// tangent segment, less that, keeps above −margin. It is never shorter than
5832/// the first-order step, and skips no time the probe is deeper than the margin.
5833struct Glide {
5834    e: Vec3,
5835    u: Vec3,
5836    v: Vec3,
5837    omega: f64,
5838    c: f64,
5839    c2: f64,
5840    curve: f64,
5841    /// Under `frame_glide_on`, a frame riding a curve: the probe's preimage
5842    /// `a + R(−θ(t))(y − P(t))` read through the frame (frame, y).
5843    riding: Option<(Frame, Vec3)>,
5844}
5845
5846/// The second-order step for frames riding a curve (default on; `=0` restores the first-order walk).
5847fn frame_glide_on() -> bool {
5848    crate::switch!("BREP_SWEEP_FRAME_GLIDE", true)
5849}
5850
5851impl Glide {
5852    fn of(screw: &Screw, y: Vec3) -> Option<Glide> {
5853        if let (Some(frame), None, true) = (&screw.frame, &screw.turns, frame_glide_on()) {
5854            return Glide::riding(screw, frame, y);
5855        }
5856        if screw.frame.is_some() || screw.turns.is_some() {
5857            return None;
5858        }
5859        let r = y.sub(screw.a);
5860        let u = r.sub(screw.e.scale(r.dot(screw.e)));
5861        let curve = screw.omega * screw.omega * u.length() + 2.0 * screw.c2.abs();
5862        // A bound rounded to nothing, or below the normal range, is not one:
5863        // only a slide (no turn, no rise) is straight.
5864        let straight = screw.omega == 0.0 && screw.c2 == 0.0;
5865        if !straight && !(curve >= f64::MIN_POSITIVE && curve.is_finite()) {
5866            return None;
5867        }
5868        Some(Glide { e: screw.e, u, v: screw.e.cross(u), omega: screw.omega, c: screw.c, c2: screw.c2, curve, riding: None })
5869    }
5870
5871    /// A frame riding a planar cubic: the preimage `p = a + R(−θ) q`,
5872    /// `q = y − P(t)`, turns about `up`, and its second derivative is
5873    /// `R(−θ)(θ'² up×(up×q) − θ'' up×q + 2θ' up×P' − P'')`, so
5874    /// `|p''| ≤ (θ'² + |θ''|)·|q| + 2|θ'|·|P'| + |P''|`. Over the motion's
5875    /// span |P'| and |P''| are bounded by their control polygons and |P'''|
5876    /// is a constant; `θ' = up·(P'×P'')/|P'|²` and θ'' are bounded through a
5877    /// lower bound on |P'| (its samples less |P''| times half their spacing;
5878    /// no glide where that is not positive); `|q| ≤ |y − P(t₀)| + |P'|·span`.
5879    fn riding(screw: &Screw, frame: &Frame, y: Vec3) -> Option<Glide> {
5880        let [p0, p1, p2, p3] = frame.control;
5881        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);
5882        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);
5883        let third = p3.sub(p2.scale(3.0)).add(p1.scale(3.0)).sub(p0).scale(6.0).length();
5884        let (t0, t1) = (screw.t0, screw.t1);
5885        let n = 256;
5886        let slowest = (0..=n).map(|k| frame.first(t0 + (t1 - t0) * k as f64 / n as f64).length()).fold(f64::INFINITY, f64::min);
5887        let floor = slowest - second * 0.5 * (t1 - t0) / n as f64;
5888        if !(floor > 0.0) {
5889            return None;
5890        }
5891        let w1 = first * second / (floor * floor);
5892        let w2 = third * first / (floor * floor) + 2.0 * first * first * second * second / floor.powi(4);
5893        let q = y.sub(frame.point(t0)).length() + first * (t1 - t0);
5894        let curve = (w1 * w1 + w2) * q + 2.0 * w1 * first + second;
5895        if !(curve.is_finite() && curve >= f64::MIN_POSITIVE) {
5896            return None;
5897        }
5898        let zero = Vec3::new(0.0, 0.0, 0.0);
5899        Some(Glide { e: frame.up, u: zero, v: zero, omega: 0.0, c: 0.0, c2: 0.0, curve, riding: Some((*frame, y)) })
5900    }
5901
5902    /// `p'(t)`.
5903    fn velocity(&self, t: f64) -> Vec3 {
5904        if let Some((frame, y)) = &self.riding {
5905            // p' = R(−θ)(−θ' up×q − P'), q = y − P(t).
5906            let q = y.sub(frame.point(t));
5907            let inner = frame.up.cross(q).scale(-frame.angle_rate(t)).sub(frame.first(t));
5908            return inner.rotate_about(frame.up, -frame.angle(t));
5909        }
5910        let (sin, cos) = (self.omega * t).sin_cos();
5911        self.e
5912            .scale(-(self.c + 2.0 * self.c2 * t))
5913            .sub(self.u.scale(self.omega * sin))
5914            .sub(self.v.scale(self.omega * cos))
5915    }
5916
5917    /// The second-order step from `t`, where the preimage is `p` at the
5918    /// tool's distance `d` (at most `left`; 0 when it finds none).
5919    #[allow(clippy::too_many_arguments)]
5920    fn step(&self, split: &Split, p: Vec3, t: f64, d: f64, margin: f64, speed: f64, left: f64) -> f64 {
5921        let velocity = self.velocity(t);
5922        let m = self.curve;
5923        match &split.shape {
5924            // Each face's plane alone bounds the distance from below:
5925            // g(t + h) ≥ g + g'·h − m·h²/2, held above −margin up to the root.
5926            Shape::Planes(planes) => {
5927                let mut best = 0.0f64;
5928                for (n, offset) in planes {
5929                    let g = n.dot(p) - offset;
5930                    if g + margin <= 0.0 {
5931                        continue;
5932                    }
5933                    let slope = n.dot(velocity);
5934                    // The root, in the form that neither overflows nor cancels.
5935                    let h = if m > 0.0 {
5936                        let root = slope.hypot((2.0 * m * (g + margin)).sqrt());
5937                        if slope >= 0.0 { (slope + root) / m } else { 2.0 * (g + margin) / (root - slope) }
5938                    } else if slope >= 0.0 {
5939                        left
5940                    } else {
5941                        (g + margin) / -slope
5942                    };
5943                    if h.is_finite() {
5944                        best = best.max(h);
5945                    }
5946                }
5947                best.min(left)
5948            }
5949            // In the meridian plane: the path (ρ, z) about the tool's axis and
5950            // its tangent segment, whose distance from the outline is bounded
5951            // below piece by piece; the path leaves the segment by at most
5952            // m₂·h²/2, m₂ = 2m + speed²/ρ_min (the radius' bend), ρ_min > 0.
5953            Shape::Revolved { origin, axis, meridian } => {
5954                if d < 0.0 {
5955                    return 0.0;
5956                }
5957                let r = p.sub(*origin);
5958                let z = r.dot(*axis);
5959                let flat = r.sub(axis.scale(z));
5960                let rho = flat.length();
5961                if rho <= 0.0 {
5962                    return 0.0;
5963                }
5964                let dz = velocity.dot(*axis);
5965                let dflat = velocity.sub(axis.scale(dz));
5966                let drho = flat.dot(dflat) / rho;
5967                let q = [rho, z];
5968                let mut best = 0.0f64;
5969                let mut h = (d + margin) / speed;
5970                for _ in 0..64 {
5971                    h *= 2.0;
5972                    if h > left {
5973                        h = left;
5974                    }
5975                    let low = rho - speed * h;
5976                    if low <= 0.0 {
5977                        break;
5978                    }
5979                    let bend = 2.0 * m + speed * speed / low;
5980                    let end = [rho + drho * h, z + dz * h];
5981                    let clear = meridian.iter().map(|piece| segment_clearance(piece, q, end)).fold(f64::INFINITY, f64::min);
5982                    // A segment that touches the outline may enter the tool: no bound.
5983                    let held = clear - 0.5 * bend * h * h;
5984                    if !held.is_finite() || clear <= 0.0 || held < -margin {
5985                        break;
5986                    }
5987                    best = h;
5988                    if h >= left {
5989                        break;
5990                    }
5991                }
5992                best
5993            }
5994        }
5995    }
5996}
5997
5998/// A lower bound on the distance between the segment `a`–`b` and a meridian
5999/// piece: a line piece's exact distance (0 where they cross), an arc's from
6000/// its whole circle.
6001fn segment_clearance(piece: &OutlinePiece, a: [f64; 2], b: [f64; 2]) -> f64 {
6002    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
6003    let dot = |p: [f64; 2], q: [f64; 2]| p[0] * q[0] + p[1] * q[1];
6004    let cross = |p: [f64; 2], q: [f64; 2]| p[0] * q[1] - p[1] * q[0];
6005    let to_segment = |x: [f64; 2], s: [f64; 2], e: [f64; 2]| -> f64 {
6006        let d = sub(e, s);
6007        let len2 = dot(d, d);
6008        let w = if len2 > 0.0 { (dot(sub(x, s), d) / len2).clamp(0.0, 1.0) } else { 0.0 };
6009        let foot = [s[0] + d[0] * w, s[1] + d[1] * w];
6010        let gap = sub(x, foot);
6011        gap[0].hypot(gap[1])
6012    };
6013    match *piece {
6014        OutlinePiece::Line { from, to } => {
6015            let (d1, d2) = (sub(b, a), sub(to, from));
6016            let denom = cross(d1, d2);
6017            if denom != 0.0 {
6018                let w = sub(from, a);
6019                let (s, t) = (cross(w, d2) / denom, cross(w, d1) / denom);
6020                if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
6021                    return 0.0;
6022                }
6023            }
6024            to_segment(a, from, to).min(to_segment(b, from, to)).min(to_segment(from, a, b)).min(to_segment(to, a, b))
6025        }
6026        OutlinePiece::Arc { centre, radius, .. } => {
6027            let near = to_segment(centre, a, b);
6028            let far = { let (x, y) = (sub(a, centre), sub(b, centre)); x[0].hypot(x[1]).max(y[0].hypot(y[1])) };
6029            (near - radius).max(radius - far).max(0.0)
6030        }
6031        // no bound read for an ellipse: zero is one
6032        OutlinePiece::Ellipse { .. } => 0.0,
6033    }
6034}
6035
6036/// A bound on how fast the tool-frame preimage `screw.invert(t, y)` of the
6037/// world point `y` moves per unit `t`; the tool's distance (1-Lipschitz)
6038/// changes no faster along it.
6039///
6040/// A plain screw about one fixed axis carries the preimage round that axis at
6041/// its distance from it, `ρ`, and along it at the advance's rate, two motions
6042/// square to each other: no faster than `hypot(|ω|·ρ, rate)`. A point near the axis barely moves, so a probe beside
6043/// a tool point on the axis (a coin turned about a line through its rim) walks
6044/// the motion in a few long steps, not millions of floor-sized ones. A riding
6045/// frame or two turns keep the coarser bound through `a`.
6046fn preimage_speed_bound(screw: &Screw, split: &Split, y: Vec3) -> f64 {
6047    let speed = if screw.frame.is_none() && screw.turns.is_none() {
6048        let r = y.sub(screw.a);
6049        let rho = r.sub(screw.e.scale(r.dot(screw.e))).length();
6050        (screw.omega.abs() * rho).hypot(screw.rate_bound())
6051    } else {
6052        let reach = y.sub(screw.a).length() + split.scale + screw.extent;
6053        screw.omega.abs() * reach + screw.rate_bound()
6054    };
6055    speed.max(1e-300)
6056}
6057
6058/// How far a revolved tool reaches about a plain screw's axis: its axial
6059/// coordinate `e·(x − a)` lies within `axial` and its distance from the axis
6060/// within `radial`, for every tool point `x` (bounds, not extremes: a meridian
6061/// line is bounded at its ends, an arc by its whole circle).
6062///
6063/// A plain screw keeps each point's distance from its axis and shifts its
6064/// axial coordinate only by the advance (a slide keeps every coordinate across
6065/// its direction), so a point `y` whose preimage stays outside these bounds
6066/// all through the motion is never inside the tool, and `covered` need not
6067/// walk the motion to say so. Without this a probe beside a face the tool runs
6068/// along all through the motion (the flat top of a coin turned about a line
6069/// through its rim, the floor of an end mill's pass) creeps through it in
6070/// steps of its own tiny distance from the tool.
6071struct ToolReach {
6072    /// The tool's revolution: its origin less the screw's point, its unit axis
6073    /// and its meridian (radius, height along the axis).
6074    base: Vec3,
6075    axis: Vec3,
6076    meridian: Vec<OutlinePiece>,
6077    axial: [f64; 2],
6078    radial: [f64; 2],
6079}
6080
6081/// The largest of |m₀|·p + m₁·q over a meridian (p ≥ 0): a line at its ends,
6082/// an arc by its circle (Cauchy–Schwarz on the offset from its centre).
6083fn meridian_most(meridian: &[OutlinePiece], p: f64, q: f64) -> f64 {
6084    meridian
6085        .iter()
6086        .map(|piece| match *piece {
6087            OutlinePiece::Line { from, to } => (from[0].abs() * p + from[1] * q).max(to[0].abs() * p + to[1] * q),
6088            OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() * p + centre[1] * q + radius * p.hypot(q),
6089            // within the circle of its larger semi-axis
6090            OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() * p + centre[1] * q + semi[0].max(semi[1]) * p.hypot(q),
6091        })
6092        .fold(f64::NEG_INFINITY, f64::max)
6093}
6094
6095impl ToolReach {
6096    fn of(screw: &Screw, split: &Split) -> Option<ToolReach> {
6097        if screw.frame.is_some() || screw.turns.is_some() {
6098            return None;
6099        }
6100        let Shape::Revolved { origin, axis, meridian } = &split.shape else { return None };
6101        let e = screw.e;
6102        // x − a = (origin − a) + m₁·axis + m₀·(unit vector ⊥ axis).
6103        let base = origin.sub(screw.a);
6104        let along = axis.dot(e);
6105        let across = axis.cross(e).length();
6106        let middle = base.dot(e);
6107        let top = middle + meridian_most(meridian, across, along);
6108        let bottom = middle - meridian_most(meridian, across, -along);
6109        // Off the axis: within |(origin − a)⊥| ± (|m₀| + |m₁|·|axis⊥e|).
6110        let off = base.sub(e.scale(middle)).length();
6111        let spread = meridian
6112            .iter()
6113            .map(|piece| match *piece {
6114                OutlinePiece::Line { from, to } => (from[0].abs() + from[1].abs() * across).max(to[0].abs() + to[1].abs() * across),
6115                OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() + centre[1].abs() * across + radius * (1.0 + across * across).sqrt(),
6116                OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() + centre[1].abs() * across + semi[0].max(semi[1]) * (1.0 + across * across).sqrt(),
6117            })
6118            .fold(f64::NEG_INFINITY, f64::max);
6119        let reach = ToolReach { base, axis: *axis, meridian: meridian.clone(), axial: [bottom, top], radial: [off - spread, off + spread] };
6120        (top.is_finite() && bottom.is_finite() && spread.is_finite()).then_some(reach)
6121    }
6122
6123    /// `covered` for a turn (no advance) about an axis along the tool's own,
6124    /// walked in the tool's radius instead of in time; `None` when the motion
6125    /// is not such a turn.
6126    ///
6127    /// The preimage keeps its height along the tool's axis, and its distance
6128    /// from that axis is `ρ_w² = ρ² + s² − 2·ρ·s·cos(θ − θ_W)`, `ρ` its own
6129    /// distance from the turn's axis, `s` the tool axis' and `θ − θ_W` the
6130    /// angle between them, which the turn sweeps through an interval. So the
6131    /// preimage takes every radius between the least and the most `ρ_w` over
6132    /// that interval, and no other: it is ever deeper than the margin inside
6133    /// the tool if and only if some radius in that range is, at that height.
6134    /// The meridian's distance is 1-Lipschitz in the radius, so the range is
6135    /// walked by it. Each radius is met once, where the walk in time crawls
6136    /// past a probe the tool grazes (by the probe's own tiny offset over the
6137    /// turn's speed at each step).
6138    fn turn_about_parallel_axis(&self, screw: &Screw, y: Vec3, margin: f64) -> Option<Result<bool, KernelRefusal>> {
6139        if screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 || self.axis.cross(screw.e).length() != 0.0 {
6140            return None;
6141        }
6142        let e = screw.e;
6143        let r = y.sub(screw.a);
6144        // From the tool's origin to the probe, and its height along the tool's
6145        // axis (the turn keeps it).
6146        let from_tool = r.sub(self.base);
6147        let height = from_tool.dot(self.axis);
6148        // In the plane square to the axis, from the turn's axis: the probe `P`
6149        // and the tool's axis `W`, and the probe from the tool's axis, `P − W`
6150        // (formed as one difference, not as two far points less each other).
6151        let flat = |x: Vec3| x.sub(e.scale(x.dot(e)));
6152        let (probe, tool, apart) = (flat(r), flat(self.base), flat(from_tool));
6153        let (rho, s) = (probe.length(), tool.length());
6154        // Rounding of the coordinates read here, a few ulps of the largest: past
6155        // a quarter of the margin, the walk in time decides instead.
6156        let slack = 64.0 * f64::EPSILON * (r.length() + self.base.length() + height.abs());
6157        if slack > 0.25 * margin {
6158            return None;
6159        }
6160        // The preimage at time t is R(−ω·t)·P: its distance from the tool's axis
6161        // is |R(φ)·(P − W) + (R(φ) − I)·W|, with R(φ) − I = −2 sin²(φ/2) + sin φ·(e ×).
6162        let radius = |phi: f64| -> f64 {
6163            let half = (0.5 * phi).sin();
6164            let turned = apart.rotate_about(e, phi).add(tool.scale(-2.0 * half * half)).add(e.cross(tool).scale(phi.sin()));
6165            turned.length()
6166        };
6167        let (phi0, phi1) = (-screw.omega * screw.t0, -screw.omega * screw.t1);
6168        // The angle from W to P; R(φ)·P lies along W at start + φ ≡ 0 and opposite it at ≡ π.
6169        let start = if rho == 0.0 || s == 0.0 { 0.0 } else { e.dot(tool.cross(probe)).atan2(tool.dot(probe)) };
6170        let (lo, hi) = ((start + phi0).min(start + phi1), (start + phi0).max(start + phi1));
6171        // Does [lo, hi] hold an angle ≡ `at` (mod 2π)?
6172        let holds = |at: f64| (lo - at).div_euclid(TAU) != (hi - at).div_euclid(TAU) || (lo - at).rem_euclid(TAU) == 0.0;
6173        let ends = [radius(phi0), radius(phi1)];
6174        // | |P| − |W| | as |(P − W)·(P + W)| / (|P| + |W|): no cancellation.
6175        let nearest = if rho + s > 0.0 { apart.dot(probe.add(tool)).abs() / (rho + s) } else { 0.0 };
6176        let mut least = if holds(0.0) { nearest } else { ends[0].min(ends[1]) };
6177        let mut most = if holds(PI) { rho + s } else { ends[0].max(ends[1]) };
6178        least = (least - slack).max(0.0);
6179        most += slack;
6180        let mut at = least;
6181        // No floor on the step (it is never less than the margin): a floor
6182        // could step over a wall thinner than itself.
6183        let mut steps = 0usize;
6184        loop {
6185            let d = outline_signed_distance(&self.meridian, [at, height]);
6186            if d < -margin {
6187                return Some(Ok(true));
6188            }
6189            if at >= most {
6190                return Some(Ok(false));
6191            }
6192            if steps > 2_000_000 {
6193                return Some(Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into())));
6194            }
6195            at = (at + d.abs() + margin).min(most);
6196            steps += 1;
6197        }
6198    }
6199
6200    /// A bound on `u·(x − a)` over the tool, `u` a unit direction.
6201    fn support(&self, u: Vec3) -> f64 {
6202        let along = u.dot(self.axis);
6203        let across = u.sub(self.axis.scale(along)).length();
6204        u.dot(self.base) + meridian_most(&self.meridian, across, along)
6205    }
6206
6207    /// Is `y`'s preimage outside the tool's reach, or within half the margin
6208    /// of its edge, at every time of the motion? Then the tool's boundary is
6209    /// within half the margin of every preimage inside (straight out of the
6210    /// bound), and none is deeper than the margin. `normal`: the probe's face
6211    /// normal, across which a slide is also tried.
6212    fn never_inside(&self, screw: &Screw, y: Vec3, normal: Vec3, margin: f64) -> bool {
6213        let r = y.sub(screw.a);
6214        let z = r.dot(screw.e);
6215        let rho = r.sub(screw.e.scale(z)).length();
6216        let mut advances = vec![screw.advance(screw.t0), screw.advance(screw.t1)];
6217        if screw.c2 != 0.0 {
6218            let vertex = -screw.c / (2.0 * screw.c2);
6219            if vertex > screw.t0 && vertex < screw.t1 {
6220                advances.push(screw.advance(vertex));
6221            }
6222        }
6223        let low = advances.iter().copied().fold(f64::INFINITY, f64::min);
6224        let high = advances.iter().copied().fold(f64::NEG_INFINITY, f64::max);
6225        // Half the margin, less what rounding may have cost the coordinates
6226        // and bounds compared (a few ulps of the largest of them).
6227        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());
6228        let half = 0.5 * margin - 1e-13 * size;
6229        if half <= 0.0 {
6230            return false;
6231        }
6232        if z - high >= self.axial[1] - half || z - low <= self.axial[0] + half {
6233            return true;
6234        }
6235        if rho >= self.radial[1] - half || (self.radial[0] > 0.0 && rho <= self.radial[0] + half) {
6236            return true;
6237        }
6238        // A slide carries the preimage along its direction only. `u` is meant
6239        // across it, but whatever of `e` rounding leaves in it moves `u·r`
6240        // with the advance: take the least `u·r` reaches over the motion.
6241        if screw.omega == 0.0 {
6242            if let Ok(u) = normal.sub(screw.e.scale(normal.dot(screw.e))).normalized() {
6243                let drift = u.dot(screw.e);
6244                let least = u.dot(r) - (drift * low).max(drift * high);
6245                if least >= self.support(u) - half {
6246                    return true;
6247                }
6248            }
6249        }
6250        false
6251    }
6252}
6253
6254/// Refuse a sweep that covers points just outside its own faces.
6255///
6256/// `sliding`: faces the tool slides within all through the motion. A probe
6257/// just off one stays that near the tool the whole way, and the walk's step
6258/// is that distance: it stands a thousand times further off them (whatever
6259/// of the tool rides higher than that over such a face is still found).
6260fn check_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
6261    let margin = 1e-9 * split.scale;
6262    let reach = ToolReach::of(screw, split);
6263    for face in body.shells.iter().flat_map(|s| &s.faces) {
6264        let step = if sliding.contains(&face.id) { 1e-3 * split.scale } else { 1e-6 * split.scale };
6265        let surface = &face.surface;
6266        // Probe inside the face: towards each corner of its loop from the
6267        // average of its corners (caps are convex in their parameters), and on
6268        // a grid for the four-sided walls.
6269        let mut corners: Vec<[f64; 2]> = Vec::new();
6270        for coedge in &face.loops[0].coedges {
6271            let domain = frag(coedge.pcurve.domain(), "domain")?;
6272            for k in 0..4 {
6273                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 4.0), "pcurve")?;
6274                corners.push([p.x, p.y]);
6275            }
6276        }
6277        let middle = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
6278        let middle = [middle[0] / corners.len() as f64, middle[1] / corners.len() as f64];
6279        let mut probes: Vec<[f64; 2]> = vec![middle];
6280        for c in &corners {
6281            for w in [0.25, 0.5, 0.75, 0.9, 0.99] {
6282                probes.push([middle[0] + (c[0] - middle[0]) * w, middle[1] + (c[1] - middle[1]) * w]);
6283            }
6284        }
6285        if surface.degree_v == 5 {
6286            let [u0, u1] = frag(surface.domain_u(), "domain")?;
6287            for i in 1..8 {
6288                for j in 1..64 {
6289                    probes.push([u0 + (u1 - u0) * i as f64 / 8.0, j as f64 / 64.0]);
6290                }
6291            }
6292        }
6293        let ([u0, u1], [v0, v1]) = (frag(surface.domain_u(), "domain")?, frag(surface.domain_v(), "domain")?);
6294        // Keep the probes inside the face's own loop (a face under a grazing
6295        // curve that dips is not convex in its parameters).
6296        let mut ring: Vec<[f64; 2]> = Vec::new();
6297        for coedge in &face.loops[0].coedges {
6298            let domain = frag(coedge.pcurve.domain(), "domain")?;
6299            for k in 0..32 {
6300                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 32.0), "pcurve")?;
6301                ring.push([p.x, p.y]);
6302            }
6303        }
6304        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])]));
6305        for i in 1..12 {
6306            for j in 1..12 {
6307                probes.push([lo[0] + (hi[0] - lo[0]) * i as f64 / 12.0, lo[1] + (hi[1] - lo[1]) * j as f64 / 12.0]);
6308            }
6309        }
6310        let inside = |q: [f64; 2]| -> bool {
6311            let mut crossings = 0;
6312            for k in 0..ring.len() {
6313                let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
6314                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]) {
6315                    crossings += 1;
6316                }
6317            }
6318            crossings % 2 == 1
6319        };
6320        for [u, v] in probes.into_iter().filter(|&q| inside(q)) {
6321            let p = frag(surface.evaluate(u, v), "probe")?;
6322            let (hu, hv) = (1e-6 * (u1 - u0), 1e-6 * (v1 - v0));
6323            // Derivatives, not raw differences: their cross product is
6324            // measured against an absolute zero.
6325            let (ua, ub, va, vb) = ((u - hu).max(u0), (u + hu).min(u1), (v - hv).max(v0), (v + hv).min(v1));
6326            let du = frag(surface.evaluate(ub, v), "probe")?.sub(frag(surface.evaluate(ua, v), "probe")?).scale(1.0 / (ub - ua));
6327            let dv = frag(surface.evaluate(u, vb), "probe")?.sub(frag(surface.evaluate(u, va), "probe")?).scale(1.0 / (vb - va));
6328            let Ok(n) = du.cross(dv).normalized() else { continue };
6329            let n = if face.same_sense { n } else { n.scale(-1.0) };
6330            if covered(screw, split, reach.as_ref(), p.add(n.scale(step)), n, margin)? {
6331                return Err(refuse("folds", format!("the sweep passes over a point twice (just outside its own face at {p:?}); not one pass")));
6332            }
6333        }
6334    }
6335    Ok(())
6336}
6337
6338
6339#[path = "solid_sweep_ring_fold.rs"]
6340mod ring_fold;