Skip to main content

brep_construction/construction/
solid_sweep_caps.rs

1//! The WHOLE sweep of a solid along a one-parameter motion, ends included:
2//! caps and wall.
3//!
4//! Along a screw (a turn is a screw of zero advance, a slide one of zero turn)
5//! the velocity field, read in the tool's own frame, does not change with time:
6//! at a boundary point x with outward normal n it is
7//! `g(x, n) = (ω e × (x − a) + c e) · n`. So the tool's boundary splits once
8//! and for all into FRONT (g > 0) and BACK (g < 0) parts, and the GRAZING LOOP
9//! K between them (g = 0 inside a face, or a sharp edge whose two faces have
10//! opposite signs) is fixed on the tool. Where every point of space is inside
11//! the moving tool for ONE interval of time, the sweep over [t0, t1] is bounded
12//! by exactly
13//!
14//! - the back of the tool at t0 (where points start to be covered),
15//! - the front of the tool at t1 (where they stop),
16//! - the WALL: K carried by the motion from t0 to t1.
17//!
18//! The body is assembled directly from those faces with shared edges, never as
19//! a boolean of the tool with a tube (the two meet tangentially along K).
20//!
21//! The one-interval condition is CHECKED, not assumed: points just outside
22//! every built face are walked through the whole motion, and a sweep that
23//! covers any of them (a fold, a buried cap, a turn running into itself) is
24//! refused by name.
25//!
26//! Tools: a convex polyhedron (K a polygon of edges and face chords); a solid
27//! of revolution whose faces are cylinders or cones (split along standing
28//! generators, or along two grazing curves moving round them, fitted), flat
29//! ends wholly front or back, a hemisphere from a pole to an equator or a whole
30//! ball (split along a great circle), or a ring (torus, split along its two
31//! grazing curves round it). Caps keep the tool's exact surfaces; walls are
32//! the K curves carried by quintic splines through the exact motion and its
33//! first two derivatives (error h⁶, 48 spans a turn), a row per quarter turn.
34//!
35//! Moving grazing loops: [`sweep_solid_along`] (a solid of revolution carried
36//! by a frame along a planar curve) and [`sweep_solid_tumbled`] (two turns
37//! about skew axes) split the tool at sample times, sample each piece of K
38//! exactly and loft the walls through time; a tumble that passes over a point
39//! twice is built from one-pass spans of its time, joined.
40//! [`sweep_prism_along`] sweeps a prism along a frame by the plane region the
41//! moving outline covers (an arrangement of its corners', grazing points' and
42//! end positions' paths), extruded. [`sweep_solid_parts`] returns a folding
43//! polyhedron's sweep as the sweeps of its halves through the motion's axis.
44//!
45//! [`sweep_solid_clipped`] adds the case the caller only needs inside a
46//! region: a polyhedron TURNED about the region's axis with both end positions
47//! outside the region's wedge fills the wedge with its (ρ, z) shadow turned,
48//! bounded by exact conic arcs (edges) and segments (face chords).
49use crate::solid_sweep::outline_signed_distance;
50use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
51pub use crate::{make_line, make_revolution, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, OrRefuse, OutlinePiece, SolidMotion, Vec3, Vec4};
52use std::collections::HashMap;
53use std::f64::consts::{FRAC_PI_2, PI, TAU};
54
55/// A tool the whole sweep takes.
56#[derive(Clone, Debug)]
57pub enum SolidTool {
58    /// A convex polyhedron: its corners, and its faces as loops of corner
59    /// indices (either winding; outward is found from the centroid).
60    Polyhedron { vertices: Vec<Vec3>, faces: Vec<Vec<usize>> },
61    /// A solid of revolution: the region `meridian` bounds in the
62    /// half-plane spanned by `radial` (first coordinate, the distance from the
63    /// axis, ≥ 0) and `axis_direction` (second coordinate), turned about the
64    /// axis through `axis_origin` (as [`crate::SweptTool::Revolved`]).
65    Revolved { axis_origin: Vec3, axis_direction: Vec3, radial: Vec3, meridian: Vec<OutlinePiece> },
66}
67
68/// Samples of a fitted pcurve: the image of its edge through the surface's
69/// exact inverse, interpolated (quintic). A rational chart's parameter has a
70/// second-derivative jump at its span joints, so the interpolant errs there
71/// as h³; at 576 that is below 1e-10 of a face's area.
72const PCURVE_SAMPLES: usize = 576;
73
74/// The prefix of every refusal of this operation.
75pub const SOLID_SWEEP_WHOLE_REFUSAL: &str = "sweepSolid";
76
77fn refuse(what: &'static str, message: String) -> KernelRefusal {
78    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
79}
80
81/// The stable slug of an unsupported-geometry refusal of this module.
82fn refused_as(error: &KernelRefusal) -> Option<&str> {
83    match &error.class {
84        crate::RefusalClass::UnsupportedGeometry { what } => Some(what.as_str()),
85        _ => None,
86    }
87}
88
89fn input(what: &'static str, message: String) -> KernelRefusal {
90    KernelRefusal::input(KernelStage::Collect, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
91}
92
93fn frag<T>(result: Result<T, String>, what: &'static str) -> Result<T, KernelRefusal> {
94    result.or_refuse(KernelStage::Fragment, what)
95}
96
97/// The motion `x ↦ a + R(ω t)(x − a) + (c t + c₂ t²) e`: a screw (c₂ = 0;
98/// a turn has c = 0, a slide ω = 0), or a turn whose rise grows as it turns.
99#[derive(Clone, Copy, Debug)]
100pub struct Screw {
101    pub a: Vec3,
102    pub e: Vec3,
103    pub omega: f64,
104    pub c: f64,
105    pub c2: f64,
106    pub t0: f64,
107    pub t1: f64,
108    /// A frame riding a curve instead (then `a` is the curve's start, `e` the
109    /// frame's fixed up direction, `omega` a bound on its turning rate and `c`
110    /// on its speed).
111    pub frame: Option<Frame>,
112    /// Two turns about fixed axes instead (then `a` is the first axis' point).
113    pub turns: Option<Turns>,
114    /// The time whose velocity field splits the tool (default: the middle).
115    pub frozen: Option<f64>,
116    /// How many spans a ring's grazing loop is sampled over, per half of the
117    /// ring (`LOFT_SAMPLES` unless a loft found its rows too coarse).
118    pub loop_samples: usize,
119    /// How far the frame's origin travels from `a` (for speed bounds).
120    pub extent: f64,
121}
122
123/// Two turns driven by one parameter: first `rates[0]·t` about the first
124/// axis, then `rates[1]·t` about the second; both axes fixed in the world.
125#[derive(Clone, Copy, Debug)]
126pub struct Turns {
127    points: [Vec3; 2],
128    directions: [Vec3; 2],
129    rates: [f64; 2],
130}
131
132impl Turns {
133    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
134        let y = self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t));
135        self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t))
136    }
137    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
138        let x = self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], -self.rates[1] * t));
139        self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], -self.rates[0] * t))
140    }
141    /// Velocity of the tool point x at t, read back in the tool's frame.
142    fn velocity(&self, t: f64, x: Vec3) -> Vec3 {
143        let first = x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t);
144        let y = self.points[0].add(first);
145        let moved = y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t);
146        let inner = self.directions[0].cross(first).scale(self.rates[0]);
147        let world = self.directions[1].cross(moved).scale(self.rates[1]).add(inner.rotate_about(self.directions[1], self.rates[1] * t));
148        world.rotate_about(self.directions[1], -self.rates[1] * t).rotate_about(self.directions[0], -self.rates[0] * t)
149    }
150}
151
152/// A frame riding a planar cubic Bézier curve: origin on the curve, first
153/// axis along its tangent, a fixed up direction square to its plane.
154#[derive(Clone, Copy, Debug)]
155pub struct Frame {
156    pub control: [Vec3; 4],
157    pub up: Vec3,
158    /// The tangent's direction at the start.
159    pub start_tangent: Vec3,
160}
161
162impl Frame {
163    fn point(&self, s: f64) -> Vec3 {
164        let [p0, p1, p2, p3] = self.control;
165        let r = 1.0 - s;
166        p0.scale(r * r * r).add(p1.scale(3.0 * r * r * s)).add(p2.scale(3.0 * r * s * s)).add(p3.scale(s * s * s))
167    }
168    fn first(&self, s: f64) -> Vec3 {
169        let [p0, p1, p2, p3] = self.control;
170        let r = 1.0 - s;
171        p1.sub(p0).scale(3.0 * r * r).add(p2.sub(p1).scale(6.0 * r * s)).add(p3.sub(p2).scale(3.0 * s * s))
172    }
173    fn second(&self, s: f64) -> Vec3 {
174        let [p0, p1, p2, p3] = self.control;
175        p2.sub(p1.scale(2.0)).add(p0).scale(6.0 * (1.0 - s)).add(p3.sub(p2.scale(2.0)).add(p1).scale(6.0 * s))
176    }
177    /// The frame's turn from its start, about `up`.
178    fn angle(&self, s: f64) -> f64 {
179        let t = self.first(s);
180        self.up.dot(self.start_tangent.cross(t)).atan2(self.start_tangent.dot(t))
181    }
182    fn angle_rate(&self, s: f64) -> f64 {
183        let (d1, d2) = (self.first(s), self.second(s));
184        self.up.dot(d1.cross(d2)) / d1.dot(d1)
185    }
186}
187
188/// A turn about an axis whose rise along it grows as it turns: turned by t
189/// (radians, right-handed about `axis_direction`) the tool has risen
190/// `rise[0] t + rise[1] t²`, for t from `from` to `to` (a variable-lead
191/// screw).
192#[derive(Clone, Copy, Debug)]
193pub struct RisingTurn {
194    pub axis_origin: Vec3,
195    pub axis_direction: Vec3,
196    pub rise: [f64; 2],
197    pub from: f64,
198    pub to: f64,
199}
200
201impl Screw {
202    pub fn from_motion(motion: &SolidMotion) -> Result<Self, KernelRefusal> {
203        let [step] = motion.steps.as_slice() else {
204            return Err(refuse("motion_steps", "only a single screw, turn or slide is swept whole here".into()));
205        };
206        let e = step
207            .axis_direction
208            .normalized()
209            .map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
210        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
211            return Err(input("range", "the motion's range must run forward".into()));
212        }
213        if step.turn == 0.0 && step.advance == 0.0 {
214            return Err(input("still", "the motion does not move".into()));
215        }
216        Ok(Self { a: step.axis_origin, e, omega: step.turn, c: step.advance, c2: 0.0, t0: motion.from, t1: motion.to, frame: None, turns: None, frozen: None,
217        loop_samples: LOFT_SAMPLES, extent: 0.0 })
218    }
219
220    fn from_rising(motion: &RisingTurn) -> Result<Self, KernelRefusal> {
221        let e = motion.axis_direction.normalized().map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
222        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
223            return Err(input("range", "the motion's range must run forward".into()));
224        }
225        // The rise's rate must keep one sign, or the tool's front and back swap.
226        let rate = |t: f64| motion.rise[0] + 2.0 * motion.rise[1] * t;
227        if rate(motion.from) * rate(motion.to) <= 0.0 {
228            return Err(refuse("rise_turns", "the rise stops or turns back within the motion".into()));
229        }
230        Ok(Self { a: motion.axis_origin, e, omega: 1.0, c: motion.rise[0], c2: motion.rise[1], t0: motion.from, t1: motion.to, frame: None, turns: None, frozen: None,
231        loop_samples: LOFT_SAMPLES, extent: 0.0 })
232    }
233
234    fn advance(&self, t: f64) -> f64 {
235        self.c * t + self.c2 * t * t
236    }
237
238    /// The fastest the motion advances along its axis.
239    fn rate_bound(&self) -> f64 {
240        (self.c + 2.0 * self.c2 * self.t0).abs().max((self.c + 2.0 * self.c2 * self.t1).abs())
241    }
242
243    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
244        if let Some(turns) = &self.turns {
245            return turns.apply(t, x);
246        }
247        if let Some(frame) = &self.frame {
248            return frame.point(t).add(x.sub(self.a).rotate_about(frame.up, frame.angle(t)));
249        }
250        self.a.add(x.sub(self.a).rotate_about(self.e, self.omega * t)).add(self.e.scale(self.advance(t)))
251    }
252
253    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
254        if let Some(turns) = &self.turns {
255            return turns.invert(t, y);
256        }
257        if let Some(frame) = &self.frame {
258            return self.a.add(y.sub(frame.point(t)).rotate_about(frame.up, -frame.angle(t)));
259        }
260        self.a.add(y.sub(self.e.scale(self.advance(t))).sub(self.a).rotate_about(self.e, -self.omega * t))
261    }
262
263    /// Velocity, in the tool's frame, of the tool point x (the same at every t
264    /// for a screw; for a growing rise, at the middle of the motion; the split
265    /// it gives is checked against both ends).
266    pub fn velocity(&self, x: Vec3) -> Vec3 {
267        self.velocity_at(self.frozen.unwrap_or(0.5 * (self.t0 + self.t1)), x)
268    }
269
270    fn velocity_at(&self, t: f64, x: Vec3) -> Vec3 {
271        if let Some(turns) = &self.turns {
272            return turns.velocity(t, x);
273        }
274        if let Some(frame) = &self.frame {
275            // In the riding frame: the speed along the start tangent and the
276            // turn about up through the frame's origin.
277            return frame.start_tangent.scale(frame.first(t).length()).add(frame.up.cross(x.sub(self.a)).scale(frame.angle_rate(t)));
278        }
279        self.e.cross(x.sub(self.a)).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t))
280    }
281
282    /// Value, first and second t-derivative of the path of the tool point x.
283    fn jet(&self, t: f64, x: Vec3) -> (Vec3, Vec3, Vec3) {
284        let r = x.sub(self.a).rotate_about(self.e, self.omega * t);
285        let axial = self.e.scale(r.dot(self.e));
286        let radial = r.sub(axial);
287        let value = self.a.add(r).add(self.e.scale(self.advance(t)));
288        let first = self.e.cross(radial).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t));
289        let second = radial.scale(-self.omega * self.omega).add(self.e.scale(2.0 * self.c2));
290        (value, first, second)
291    }
292
293    fn move_point(&self, t: f64, p: &Vec4) -> Result<Vec4, KernelRefusal> {
294        let x = frag(p.point(), "control_point")?;
295        Ok(Vec4::from_point(self.apply(t, x), p.w))
296    }
297
298    fn move_curve(&self, t: f64, curve: &NurbsCurve) -> Result<NurbsCurve, KernelRefusal> {
299        let points = curve.control_points.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?;
300        frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "moved_curve")
301    }
302
303    fn move_surface(&self, t: f64, surface: &NurbsSurface) -> Result<NurbsSurface, KernelRefusal> {
304        let mut rows = Vec::with_capacity(surface.control_points.len());
305        for row in &surface.control_points {
306            rows.push(row.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?);
307        }
308        frag(
309            NurbsSurface::new(surface.degree_u, surface.degree_v, surface.knots_u.clone(), surface.knots_v.clone(), rows),
310            "moved_surface",
311        )
312    }
313}
314
315/// The motion's times at the ends of its rows: each row of wall turns at most
316/// a quarter turn (long thin faces cost every later reading, and the cut).
317fn row_times(screw: &Screw) -> Vec<f64> {
318    let turned = (screw.omega * (screw.t1 - screw.t0)).abs();
319    let rows = ((turned / (0.5 * PI)).ceil() as usize).max(1);
320    // Breaks off the round fractions of the range, where a caller's workpiece
321    // faces tend to lie (a precaution: an edge lying in a face makes a
322    // degenerate cut).
323    let at = |k: usize| match k {
324        0 => screw.t0,
325        k if k == rows => screw.t1,
326        k => screw.t0 + (screw.t1 - screw.t0) * (k as f64 - 0.381966011250105) / rows as f64,
327    };
328    (0..=rows).map(at).collect()
329}
330
331/// Spans of the quintic carry over [ta, tb]: 48 per turn (error ≈ r·h⁶/46080
332/// ≈ 1e-10·r), at least 4.
333fn carry_segments(screw: &Screw, ta: f64, tb: f64) -> usize {
334    let turned = (screw.omega * (tb - ta)).abs();
335    ((turned / TAU * 48.0).ceil() as usize).max(4)
336}
337
338/// Knots of the C² quintic carry on [0, 1].
339fn carry_knots(segments: usize) -> Vec<f64> {
340    let mut knots = vec![0.0; 6];
341    for k in 1..segments {
342        knots.extend([k as f64 / segments as f64; 3]);
343    }
344    knots.extend([1.0; 6]);
345    knots
346}
347
348/// Control points of the C² quintic spline through the exact path of the tool
349/// point x, its first and second derivatives at `segments + 1` times. Affine
350/// in x, so carrying a rational curve's control points carries the curve.
351fn carry_points(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Vec<Vec3> {
352    let h = (tb - ta) / segments as f64;
353    let at = |k: usize| screw.jet(ta + h * k as f64, x);
354    let piece = |k: usize| {
355        let ((f0, d0, a0), (f1, d1, a1)) = (at(k), at(k + 1));
356        [
357            f0,
358            f0.add(d0.scale(h / 5.0)),
359            f0.add(d0.scale(2.0 * h / 5.0)).add(a0.scale(h * h / 20.0)),
360            f1.sub(d1.scale(2.0 * h / 5.0)).add(a1.scale(h * h / 20.0)),
361            f1.sub(d1.scale(h / 5.0)),
362            f1,
363        ]
364    };
365    let mut points = Vec::with_capacity(3 * segments + 3);
366    let first = piece(0);
367    points.extend_from_slice(&first[..3]);
368    for k in 0..segments - 1 {
369        let (here, next) = (piece(k), piece(k + 1));
370        points.push(here[3]);
371        points.push(here[4].scale(2.0).sub(here[3]));
372        points.push(next[2]);
373    }
374    let last = piece(segments - 1);
375    points.extend_from_slice(&last[3..]);
376    points
377}
378
379fn carry_curve(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Result<NurbsCurve, KernelRefusal> {
380    frag(
381        NurbsCurve::new(5, carry_knots(segments), carry_points(screw, x, ta, tb, segments).into_iter().map(|p| Vec4::from_point(p, 1.0)).collect()),
382        "carry_curve",
383    )
384}
385
386/// A boundary curve of the tool (in its own frame), from point `start` to
387/// point `end` along its parameter.
388struct ToolCurve {
389    curve: NurbsCurve,
390    start: usize,
391    end: usize,
392    degenerate: bool,
393    /// Exact points at `LOFT_SAMPLES + 1` even steps of a natural parameter
394    /// from start to end (meridian place, angle), where a grazing curve
395    /// moves on the tool and its wall is lofted through time.
396    samples: Option<Vec<Vec3>>,
397}
398
399/// Steps of a grazing curve's exact samples for a lofted wall.
400pub const LOFT_SAMPLES: usize = 128;
401
402/// How near a lofted wall keeps to its exact grazing loop, as a fraction of
403/// the sweep's size: every exact sample of the loop, in the middle of every
404/// time span, is within this of the wall.
405///
406/// It was 5e-10. A wall that tight is heavy (a quintic's miss falls as the
407/// sixth power of its span, so each tenfold costs half again as many spans
408/// each way), and whoever reads the solid pays for every span. The measures
409/// do not need it: an interpolant's miss changes sign from span to span and
410/// all but cancels in a volume or an area. Over this hundredfold the lofted
411/// cases' volumes and areas moved by 2e-10 or less.
412const LOFT_TARGET: f64 = 5e-8;
413
414/// A face of the tool after the split along K: its exact surface (normal
415/// outward), its side, and its loop (curve, traversed forward?, pcurve in the
416/// direction of traversal).
417struct Cap {
418    surface: NurbsSurface,
419    front: bool,
420    coedges: Vec<(usize, bool, NurbsCurve)>,
421    /// The surface's exact parameters of a point (in the tool's frame), where
422    /// known: a lofted edge's pcurve is then its exact image.
423    chart: Option<Chart>,
424}
425
426/// How a cap's surface is parameterized, to invert it exactly.
427#[derive(Clone, Copy, Debug)]
428enum Chart {
429    /// `plane_patch(origin, u, v, …)`: (x − origin)·u, (x − origin)·v.
430    Plane { origin: Vec3, u: Vec3, v: Vec3 },
431    /// `make_revolution(origin, w, generatrix, theta)` with the generatrix in the
432    /// meridian half-plane at angle `alpha` (from u1 towards u2).
433    Revolution { origin: Vec3, w: Vec3, u1: Vec3, u2: Vec3, alpha: f64, theta: f64, spans_u: usize, meridian: MeridianChart },
434}
435
436#[derive(Clone, Copy, Debug)]
437enum MeridianChart {
438    /// A segment from m0 to m1 in (ρ, z), parameter 0 -> 1.
439    Line { m0: [f64; 2], m1: [f64; 2] },
440    /// An arc about `centre` in (ρ, z) from angle `start` through `sweep`, as
441    /// `make_revolution` of a point makes it (`spans` arcs).
442    Arc { centre: [f64; 2], start: f64, sweep: f64, spans: usize },
443}
444
445impl Chart {
446    /// Is `x` on the chart's own axis, where its first parameter (the angle
447    /// about the axis) is not defined? A ball's pole.
448    fn at_pole(&self, x: Vec3) -> bool {
449        match *self {
450            Chart::Plane { .. } => false,
451            Chart::Revolution { origin, w, .. } => {
452                let r = x.sub(origin);
453                r.sub(w.scale(r.dot(w))).length() <= 1e-6 * r.length()
454            }
455        }
456    }
457
458    /// The chart's span joints in each parameter (`make_revolution`'s arcs
459    /// in equal spans of [0, 1]), where its parameter's second derivative
460    /// jumps along the surface.
461    fn joints(&self) -> (Vec<f64>, Vec<f64>) {
462        let inner = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
463        match *self {
464            Chart::Plane { .. } => (Vec::new(), Vec::new()),
465            Chart::Revolution { spans_u, meridian, .. } => (
466                inner(spans_u),
467                match meridian {
468                    MeridianChart::Arc { spans, .. } => inner(spans),
469                    MeridianChart::Line { .. } => Vec::new(),
470                },
471            ),
472        }
473    }
474
475    fn invert(&self, x: Vec3) -> [f64; 2] {
476        match *self {
477            Chart::Plane { origin, u, v } => {
478                let d = x.sub(origin);
479                [d.dot(u), d.dot(v)]
480            }
481            Chart::Revolution { origin, w, u1, u2, alpha, theta, spans_u, meridian } => {
482                let r = x.sub(origin);
483                let z = r.dot(w);
484                let rho = r.sub(w.scale(z)).length();
485                let mid = alpha + 0.5 * theta;
486                let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
487                let u = crate::circle_angle_to_parameter(spans_u, theta, psi - alpha);
488                let v = match meridian {
489                    MeridianChart::Line { m0, m1 } => {
490                        let (a, b) = (m1[0] - m0[0], m1[1] - m0[1]);
491                        ((rho - m0[0]) * a + (z - m0[1]) * b) / (a * a + b * b)
492                    }
493                    MeridianChart::Arc { centre, start, sweep, spans } => {
494                        let mid = start + 0.5 * sweep;
495                        let angle = mid + ((z - centre[1]).atan2(rho - centre[0]) - mid + PI).rem_euclid(TAU) - PI;
496                        crate::circle_angle_to_parameter(spans, sweep, angle - start)
497                    }
498                };
499                [u, v]
500            }
501        }
502    }
503}
504
505/// The spans `make_revolution` gives a sweep of `theta`.
506fn spans_of(surface_knots_u: &[f64]) -> usize {
507    (surface_knots_u.len() - 6) / 2 + 1
508}
509
510/// The tool's boundary split along K, in the tool's own frame.
511struct Split {
512    points: Vec<Vec3>,
513    curves: Vec<ToolCurve>,
514    caps: Vec<Cap>,
515    /// Flat ends that slide within their own plane all through the motion.
516    slides: Vec<SlideDisc>,
517    /// Cylinders that slide along their own generators all through it.
518    slide_sides: Vec<SlideSide>,
519    scale: f64,
520    shape: Shape,
521}
522
523/// A flat end about the tool's axis whose every point moves within the
524/// end's own plane (a turn about a parallel axis, a slide across the tool's
525/// axis): neither front nor back. What it sweeps is one face of the sweep in
526/// that plane, bounded by the rim's arcs beside back faces where the motion
527/// starts, its arcs beside front faces where it stops, and the paths of the
528/// points between them. `rim`: the rim's arcs counter-clockwise about the
529/// outward normal `u × v`, each with its direction of traversal.
530struct SlideDisc {
531    centre: Vec3,
532    u: Vec3,
533    v: Vec3,
534    rim: Vec<(usize, bool)>,
535}
536
537/// A cylinder about the tool's axis slid along that axis: every point moves
538/// along its own generator. What it sweeps is the cylinder from one rim where
539/// that rim's neighbour sits (back at the start, front at the end) to the
540/// other rim where its neighbour sits. `patches`: per stretch between two
541/// seam angles, (the angle it starts at, its sweep, the start rim's arc, the
542/// end rim's arc, the rim points at the start angle: start rim, end rim).
543struct SlideSide {
544    origin: Vec3,
545    w: Vec3,
546    patches: Vec<(f64, f64, usize, usize, [usize; 2])>,
547}
548
549/// What the membership oracle measures.
550enum Shape {
551    Planes(Vec<(Vec3, f64)>),
552    Revolved { origin: Vec3, axis: Vec3, meridian: Vec<OutlinePiece> },
553}
554
555impl Split {
556    /// Signed distance to the tool in its own frame (negative inside).
557    fn distance(&self, x: Vec3) -> f64 {
558        match &self.shape {
559            Shape::Planes(planes) => planes.iter().map(|(n, d)| n.dot(x) - d).fold(f64::NEG_INFINITY, f64::max),
560            Shape::Revolved { origin, axis, meridian } => {
561                let r = x.sub(*origin);
562                let z = r.dot(*axis);
563                let rho = r.sub(axis.scale(z)).length();
564                outline_signed_distance(meridian, [rho, z])
565            }
566        }
567    }
568
569    /// K: each curve with a front cap on one side and a back cap on the
570    /// other, with the direction in which the back cap runs along it (the back
571    /// on its left seen from outside).
572    fn grazing(&self) -> Result<Vec<(usize, bool)>, KernelRefusal> {
573        let mut uses: HashMap<usize, Vec<(bool, bool)>> = HashMap::new();
574        for cap in &self.caps {
575            for &(curve, forward, _) in &cap.coedges {
576                uses.entry(curve).or_default().push((forward, cap.front));
577            }
578        }
579        let mut grazing = Vec::new();
580        for (curve, list) in uses {
581            if self.curves[curve].degenerate {
582                continue;
583            }
584            // A sliding end's rim carries no wall: it moves within the end's plane.
585            if list.len() == 1
586                && (self.slides.iter().any(|slide| slide.rim.iter().any(|&(c, _)| c == curve))
587                    || self.slide_sides.iter().any(|side| side.patches.iter().any(|patch| patch.2 == curve || patch.3 == curve)))
588            {
589                continue;
590            }
591            match list.as_slice() {
592                [(fa, front_a), (fb, front_b)] => {
593                    if fa == fb {
594                        return Err(refuse("split_topology", "two caps run one boundary curve the same way".into()));
595                    }
596                    if front_a != front_b {
597                        grazing.push((curve, if *front_a { *fb } else { *fa }));
598                    }
599                }
600                _ => return Err(refuse("split_topology", format!("a boundary curve is used {} times", list.len()))),
601            }
602        }
603        grazing.sort_unstable();
604        Ok(grazing)
605    }
606}
607
608fn uv_line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
609    frag(make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)), "pcurve")
610}
611
612/// The plane through `origin` with in-plane axes u, v (u × v outward), as a
613/// patch covering `points`; and the map to its parameters.
614fn plane_patch(origin: Vec3, u: Vec3, v: Vec3, points: &[Vec3]) -> Result<NurbsSurface, KernelRefusal> {
615    let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
616    for p in points {
617        let q = [p.sub(origin).dot(u), p.sub(origin).dot(v)];
618        for k in 0..2 {
619            lo[k] = lo[k].min(q[k]);
620            hi[k] = hi[k].max(q[k]);
621        }
622    }
623    let at = |s: f64, t: f64| Vec4::from_point(origin.add(u.scale(s)).add(v.scale(t)), 1.0);
624    frag(
625        NurbsSurface::new(
626            1,
627            1,
628            vec![lo[0], lo[0], hi[0], hi[0]],
629            vec![lo[1], lo[1], hi[1], hi[1]],
630            vec![vec![at(lo[0], lo[1]), at(lo[0], hi[1])], vec![at(hi[0], lo[1]), at(hi[0], hi[1])]],
631        ),
632        "plane_surface",
633    )
634}
635
636/// A curve lying in the plane (origin, u, v), as a pcurve of that plane:
637/// its control points projected, weights kept (exact, the map is affine).
638fn plane_pcurve(origin: Vec3, u: Vec3, v: Vec3, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
639    let mut points = Vec::with_capacity(curve.control_points.len());
640    for p in &curve.control_points {
641        let x = frag(p.point(), "control_point")?.sub(origin);
642        points.push(Vec4::from_point(Vec3::new(x.dot(u), x.dot(v), 0.0), p.w));
643    }
644    let pcurve = frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "plane_pcurve")?;
645    if forward { Ok(pcurve) } else { frag(pcurve.reversed(), "plane_pcurve") }
646}
647
648fn split_polyhedron(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<Split, KernelRefusal> {
649    if vertices.len() < 4 || faces.len() < 4 {
650        return Err(input("polyhedron", "a polyhedron needs at least four corners and four faces".into()));
651    }
652    let centroid = vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &p| s.add(p)).scale(1.0 / vertices.len() as f64);
653    let scale = vertices.iter().map(|p| p.sub(centroid).length()).fold(0.0f64, f64::max).max(1e-300);
654    let tolerance = 1e-12 * scale.max(screw.a.sub(centroid).length());
655    let mut loops: Vec<Vec<usize>> = Vec::with_capacity(faces.len());
656    let mut planes = Vec::with_capacity(faces.len());
657    for face in faces {
658        if face.len() < 3 || face.iter().any(|&i| i >= vertices.len()) {
659            return Err(input("face", "a face needs three or more existing corners".into()));
660        }
661        let mut normal = Vec3::new(0.0, 0.0, 0.0);
662        for k in 0..face.len() {
663            let (p, q) = (vertices[face[k]], vertices[face[(k + 1) % face.len()]]);
664            normal = normal.add(p.sub(centroid).cross(q.sub(centroid)));
665        }
666        let mut normal = normal.normalized().map_err(|_| input("face", "a face has no area".into()))?;
667        let mut face = face.clone();
668        if normal.dot(vertices[face[0]].sub(centroid)) < 0.0 {
669            normal = normal.scale(-1.0);
670            face.reverse();
671        }
672        let offset = normal.dot(vertices[face[0]]);
673        for p in vertices {
674            if normal.dot(*p) - offset > 1e-9 * scale {
675                return Err(refuse("not_convex", "the polyhedron is not convex".into()));
676            }
677        }
678        for &i in &face {
679            if (normal.dot(vertices[i]) - offset).abs() > 1e-9 * scale {
680                return Err(input("face", "a face's corners are not in one plane".into()));
681            }
682        }
683        loops.push(face);
684        planes.push((normal, offset));
685    }
686    // Each face's grazing value (affine along the face).
687    let g = |face: usize, x: Vec3| -> f64 {
688        let value = screw.velocity(x).dot(planes[face].0);
689        if value.abs() <= tolerance * screw.velocity(x).length().max(1.0) { 0.0 } else { value }
690    };
691    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
692    for (index, face) in loops.iter().enumerate() {
693        for k in 0..face.len() {
694            owner.insert((face[k], face[(k + 1) % face.len()]), index);
695        }
696    }
697    for &(i, j) in owner.keys() {
698        if !owner.contains_key(&(j, i)) {
699            return Err(input("closed", "the polyhedron's faces do not close".into()));
700        }
701    }
702    // Split points on edges: where either neighbour's grazing value crosses zero.
703    let mut points: Vec<Vec3> = vertices.to_vec();
704    let mut edge_splits: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
705    let mut keys: Vec<(usize, usize)> = owner.keys().copied().filter(|&(i, j)| i < j).collect();
706    keys.sort_unstable();
707    for (i, j) in keys {
708        let mut params: Vec<f64> = Vec::new();
709        for f in [owner[&(i, j)], owner[&(j, i)]] {
710            let (gi, gj) = (g(f, vertices[i]), g(f, vertices[j]));
711            if gi * gj < 0.0 {
712                params.push(gi / (gi - gj));
713            }
714        }
715        params.sort_by(|a, b| a.total_cmp(b));
716        params.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
717        let mut list = Vec::new();
718        for s in params {
719            points.push(vertices[i].add(vertices[j].sub(vertices[i]).scale(s)));
720            list.push(points.len() - 1);
721        }
722        edge_splits.insert((i, j), list);
723    }
724    let splits_along = |i: usize, j: usize| -> Vec<usize> {
725        if i < j {
726            edge_splits[&(i, j)].clone()
727        } else {
728            edge_splits[&(j, i)].iter().rev().copied().collect()
729        }
730    };
731    // Sub-faces as point rings, counter-clockwise from outside.
732    let mut rings: Vec<(Vec<usize>, usize, bool)> = Vec::new();
733    for (index, face) in loops.iter().enumerate() {
734        let mut ring: Vec<usize> = Vec::new();
735        for k in 0..face.len() {
736            ring.push(face[k]);
737            ring.extend(splits_along(face[k], face[(k + 1) % face.len()]));
738        }
739        let values: Vec<f64> = ring.iter().map(|&p| g(index, points[p])).collect();
740        let positive = values.iter().any(|&v| v > 0.0);
741        let negative = values.iter().any(|&v| v < 0.0);
742        if !positive && !negative {
743            return Err(refuse("face_in_own_plane", format!("face {index} moves in its own plane (its sweep is flat)")));
744        }
745        if !(positive && negative) {
746            rings.push((ring, index, positive));
747            continue;
748        }
749        let zeros: Vec<usize> = (0..ring.len()).filter(|&k| values[k] == 0.0).collect();
750        if zeros.len() != 2 {
751            return Err(refuse("grazing_split", format!("face {index} meets its grazing line {} times", zeros.len())));
752        }
753        let (za, zb) = (zeros[0], zeros[1]);
754        if za + 1 == zb || (zb + 1) % ring.len() == za {
755            return Err(refuse("grazing_split", format!("face {index} is split along one of its own edges")));
756        }
757        let first: Vec<usize> = (za..=zb).map(|k| ring[k]).collect();
758        let second: Vec<usize> = (zb..ring.len()).chain(0..=za).map(|k| ring[k]).collect();
759        let first_front = values[za + 1] > 0.0;
760        rings.push((first, index, first_front));
761        rings.push((second, index, !first_front));
762    }
763    // A growing rise moves the grazing lines: every sub-face must keep its side
764    // at both ends of the motion.
765    if screw.c2 != 0.0 {
766        for (ring, face, front) in &rings {
767            for &p in ring {
768                for t in [screw.t0, screw.t1] {
769                    let value = screw.velocity_at(t, points[p]).dot(planes[*face].0);
770                    let slack = tolerance * screw.velocity_at(t, points[p]).length().max(1.0);
771                    if (*front && value < -slack) || (!*front && value > slack) {
772                        return Err(refuse("rising_sides", format!("face {face} changes side as the rise grows")));
773                    }
774                }
775            }
776        }
777    }
778    // Curves: one straight segment per point pair.
779    let mut curves: Vec<ToolCurve> = Vec::new();
780    let mut by_pair: HashMap<(usize, usize), usize> = HashMap::new();
781    let mut caps = Vec::with_capacity(rings.len());
782    for (ring, face, front) in rings {
783        let normal = planes[face].0;
784        let origin = points[ring[0]];
785        let u = frag(points[ring[1]].sub(origin).normalized(), "plane_axis")?;
786        let v = normal.cross(u);
787        let corners: Vec<Vec3> = ring.iter().map(|&p| points[p]).collect();
788        let surface = plane_patch(origin, u, v, &corners)?;
789        let mut coedges = Vec::with_capacity(ring.len());
790        for k in 0..ring.len() {
791            let (p, q) = (ring[k], ring[(k + 1) % ring.len()]);
792            let key = (p.min(q), p.max(q));
793            let index = match by_pair.get(&key) {
794                Some(&index) => index,
795                None => {
796                    curves.push(ToolCurve {
797                        curve: frag(make_line(points[key.0], points[key.1]), "line")?,
798                        start: key.0,
799                        end: key.1,
800                        degenerate: false,
801                        samples: None,
802                    });
803                    by_pair.insert(key, curves.len() - 1);
804                    curves.len() - 1
805                }
806            };
807            let forward = p == key.0;
808            coedges.push((index, forward, plane_pcurve(origin, u, v, &curves[index].curve, forward)?));
809        }
810        caps.push(Cap { surface, front, coedges, chart: Some(Chart::Plane { origin, u, v }) });
811    }
812    Ok(Split { points, curves, caps, slides: Vec::new(), slide_sides: Vec::new(), scale, shape: Shape::Planes(planes) })
813}
814
815/// The grazing value `A cos ψ + B sin ψ + C` of a face of revolution at one
816/// meridian point, from three samples.
817pub fn harmonic(g: impl Fn(f64) -> f64) -> (f64, f64, f64) {
818    let (g0, g90, g180) = (g(0.0), g(0.5 * PI), g(PI));
819    let c = 0.5 * (g0 + g180);
820    (0.5 * (g0 - g180), g90 - c, c)
821}
822
823pub fn piece_point(piece: &OutlinePiece, s: f64) -> [f64; 2] {
824    match *piece {
825        OutlinePiece::Line { from, to } => [from[0] + (to[0] - from[0]) * s, from[1] + (to[1] - from[1]) * s],
826        OutlinePiece::Arc { centre, radius, start, end } => {
827            let angle = start + (end - start) * s;
828            [centre[0] + radius * angle.cos(), centre[1] + radius * angle.sin()]
829        }
830        OutlinePiece::Ellipse { centre, semi, rotation, start, end } => crate::solid_sweep::ellipse_point(centre, semi, rotation, start + (end - start) * s),
831    }
832}
833
834/// The whole sweep takes meridians of lines and circular arcs; an elliptic
835/// piece is swept only by [`crate::sweep_solid_within`]'s region engine.
836fn refuse_elliptic(meridian: &[OutlinePiece]) -> Result<(), KernelRefusal> {
837    if meridian.iter().any(|piece| matches!(piece, OutlinePiece::Ellipse { .. })) {
838        return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into()));
839    }
840    Ok(())
841}
842
843fn split_revolved(
844    screw: &Screw,
845    origin: Vec3,
846    axis: Vec3,
847    radial: Vec3,
848    meridian: &[OutlinePiece],
849) -> Result<Split, KernelRefusal> {
850    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
851    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
852    let u2 = w.cross(u1);
853    refuse_elliptic(meridian)?;
854    if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian {
855        if ((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius {
856            return split_torus(screw, origin, w, u1, u2, *centre, *radius, meridian);
857        }
858    }
859    let at = |rho: f64, z: f64, psi: f64| origin.add(w.scale(z)).add(u1.scale(rho * psi.cos())).add(u2.scale(rho * psi.sin()));
860    let scale = meridian
861        .iter()
862        .flat_map(|p| [piece_point(p, 0.0), piece_point(p, 1.0)])
863        .map(|q| q[0].abs().max(q[1].abs()))
864        .fold(0.0f64, f64::max)
865        .max(1e-300);
866    let on_axis = |q: [f64; 2]| q[0].abs() <= 1e-12 * scale;
867    // Orientation of the meridian outline (+1 counter-clockwise in (ρ, z)).
868    let mut area = 0.0;
869    for piece in meridian {
870        for k in 0..16 {
871            let (p, q) = (piece_point(piece, k as f64 / 16.0), piece_point(piece, (k + 1) as f64 / 16.0));
872            area += p[0] * q[1] - q[0] * p[1];
873        }
874    }
875    // Work counter-clockwise in (ρ, z): a revolved patch's u × v is then outward.
876    let reversed_meridian: Vec<OutlinePiece>;
877    let meridian: &[OutlinePiece] = if area > 0.0 {
878        meridian
879    } else {
880        reversed_meridian = meridian
881            .iter()
882            .rev()
883            .map(|piece| match *piece {
884                OutlinePiece::Line { from, to } => OutlinePiece::Line { from: to, to: from },
885                OutlinePiece::Arc { centre, radius, start, end } => OutlinePiece::Arc { centre, radius, start: end, end: start },
886                OutlinePiece::Ellipse { centre, semi, rotation, start, end } => OutlinePiece::Ellipse { centre, semi, rotation, start: end, end: start },
887            })
888            .collect();
889        &reversed_meridian
890    };
891    let ccw = true;
892    // Outward normal in (ρ, z) of a piece at s.
893    let normal = |piece: &OutlinePiece, s: f64| -> [f64; 2] {
894        let (p, q) = (piece_point(piece, (s - 1e-6).max(0.0)), piece_point(piece, (s + 1e-6).min(1.0)));
895        let (dx, dz) = (q[0] - p[0], q[1] - p[1]);
896        let length = dx.hypot(dz);
897        if ccw { [dz / length, -dx / length] } else { [-dz / length, dx / length] }
898    };
899    let g = |piece: &OutlinePiece, s: f64, psi: f64| -> f64 {
900        let m = piece_point(piece, s);
901        let n = normal(piece, s);
902        let x = at(m[0], m[1], psi);
903        let normal = w.scale(n[1]).add(u1.scale(n[0] * psi.cos())).add(u2.scale(n[0] * psi.sin()));
904        screw.velocity(x).dot(normal)
905    };
906    // The faces: pieces off the axis.
907    let faces: Vec<usize> = (0..meridian.len())
908        .filter(|&i| !(matches!(meridian[i], OutlinePiece::Line { .. }) && on_axis(piece_point(&meridian[i], 0.0)) && on_axis(piece_point(&meridian[i], 1.0))))
909        .collect();
910    // Each face's split angles (where K meets it, constant along it), or its
911    // great circle.
912    enum Kind {
913        /// A cylinder or cone (or a flat end) split along generators at these
914        /// angles (empty: one side).
915        Ruled(Vec<f64>),
916        /// A cylinder or cone whose two grazing curves move round it along
917        /// the meridian (`branches`), from rim to rim.
918        Moving,
919        /// A hemisphere from a pole to an equator rim, split by the great
920        /// circle square to its centre's velocity.
921        Sphere { centre: Vec3, pole_at_start: bool },
922        /// A whole ball (a half circle from pole to pole), split by that
923        /// great circle into two hemispheres.
924        Ball { centre: Vec3, radius: f64 },
925        /// A rounded corner (a zone of a torus: an arc whose centre is off the
926        /// axis), crossed by K as a graph v(ψ) of the tube angle for ψ from
927        /// `psi_a` to `psi_b`, entering and leaving at the same rim (the end
928        /// rim when `at_end`).
929        TorusZone { psi_a: f64, psi_b: f64, at_end: bool },
930        /// A flat end that slides within its own plane (`SlideDisc`).
931        Slide,
932        /// A cylinder slid along its own axis (`SlideSide`).
933        SlideSide,
934        /// A rounded corner split along meridian arcs at these angles (the
935        /// grazing curve keeps its angle about the axis: a turn about a
936        /// parallel axis, a slide across the tool's axis).
937        RuledArc(Vec<f64>),
938    }
939    // The two grazing angles of a cylinder or cone at s, the lower and the
940    // upper, unwrapped against s = 0: the front lies between them.
941    let branches = |piece: &OutlinePiece, s: f64| -> Option<(f64, f64)> {
942        let reference = {
943            let (a, b, _) = harmonic(|psi| g(piece, 0.0, psi));
944            b.atan2(a)
945        };
946        let (a, b, c) = harmonic(|psi| g(piece, s, psi));
947        let r = a.hypot(b);
948        if !(c.abs() < r * (1.0 - 1e-9)) {
949            return None;
950        }
951        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
952        let spread = (-c / r).acos();
953        Some((base - spread, base + spread))
954    };
955    let mut kinds: Vec<Kind> = Vec::with_capacity(faces.len());
956    for &i in &faces {
957        let piece = &meridian[i];
958        match *piece {
959            OutlinePiece::Ellipse { .. } => return Err(refuse("revolved_ellipse", "a meridian with an elliptic piece is not swept whole here".into())),
960            OutlinePiece::Line { .. } => {
961                let roots = |s: f64| -> Vec<f64> {
962                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
963                    let r = a.hypot(b);
964                    if c.abs() >= r * (1.0 - 1e-12) {
965                        return Vec::new();
966                    }
967                    let base = b.atan2(a);
968                    let spread = (-c / r).acos();
969                    let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
970                    list.sort_by(|x, y| x.total_cmp(y));
971                    list
972                };
973                // Where the grazing value vanishes all round (a rim through
974                // the motion's axis turning in its own plane) it names no
975                // angle; read the roots where it does not.
976                let alive = |s: f64| {
977                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
978                    a.hypot(b).max(c.abs()) > 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound())
979                };
980                let readings: Vec<Vec<f64>> = [0.0, 0.5, 1.0].into_iter().filter(|&t| alive(t)).map(roots).collect();
981                if readings.is_empty() {
982                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
983                    let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
984                    if flat && (on_axis(m0) || on_axis(m1)) {
985                        kinds.push(Kind::Slide);
986                        continue;
987                    }
988                    let upright = (m0[0] - m1[0]).abs() <= 1e-12 * scale;
989                    if upright && screw.omega == 0.0 && screw.turns.is_none() && screw.frame.is_none() {
990                        kinds.push(Kind::SlideSide);
991                        continue;
992                    }
993                    return Err(refuse("revolved_grazing", format!("meridian piece {i} grazes all over")));
994                }
995                let r0 = readings[0].clone();
996                let still = readings.iter().all(|r| r.len() == r0.len() && r.iter().zip(&r0).all(|(x, y)| (x - y).abs() < 1e-10));
997                if still {
998                    // A face wholly on one side that is not a disc about the
999                    // axis (a cone to its point, an annulus, a whole side):
1000                    // two halves of the same side, seamed at 0 and π.
1001                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1002                    let disc = (m0[1] - m1[1]).abs() <= 1e-12 * scale && (on_axis(m0) || on_axis(m1));
1003                    kinds.push(Kind::Ruled(if r0.is_empty() && !disc { vec![0.0, PI] } else { r0 }));
1004                    continue;
1005                }
1006                let mut previous: Option<(f64, f64)> = None;
1007                for k in 0..=64 {
1008                    let Some(pair) = branches(piece, k as f64 / 64.0) else {
1009                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} do not run rim to rim")));
1010                    };
1011                    if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
1012                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} turn too fast")));
1013                    }
1014                    previous = Some(pair);
1015                }
1016                kinds.push(Kind::Moving);
1017            }
1018            OutlinePiece::Arc { centre, radius, start, end } => {
1019                let (p0, p1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1020                let span = (end - start).abs();
1021                let centre_on_axis = on_axis(centre);
1022                let pole_at_start = on_axis(p0);
1023                let equator = |p: [f64; 2]| (p[1] - centre[1]).abs() <= 1e-12 * scale && (p[0] - radius).abs() <= 1e-12 * scale;
1024                if centre_on_axis && (span - PI).abs() < 1e-12 && pole_at_start && on_axis(p1) {
1025                    kinds.push(Kind::Ball { centre: origin.add(w.scale(centre[1])), radius });
1026                    continue;
1027                }
1028                if centre[0] > radius * (1.0 + 1e-9) && end > start && span <= PI + 1e-12 {
1029                    let at_rim = |v: f64| [centre[0] + radius * v.cos(), centre[1] + radius * v.sin()];
1030                    let g_tube = |psi: f64, v: f64| -> f64 {
1031                        let m = at_rim(v);
1032                        let x = at(m[0], m[1], psi);
1033                        let normal = w.scale(v.sin()).add(u1.scale(v.cos() * psi.cos())).add(u2.scale(v.cos() * psi.sin()));
1034                        screw.velocity(x).dot(normal)
1035                    };
1036                    // K at the same angles about the axis all along the arc?
1037                    {
1038                        let roots_at = |v: f64| -> Option<Vec<f64>> {
1039                            let (a, b, c) = harmonic(|psi| g_tube(psi, v));
1040                            let r = a.hypot(b);
1041                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1042                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1043                                return None;
1044                            }
1045                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1046                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1047                            list.sort_by(|x, y| x.total_cmp(y));
1048                            Some(list)
1049                        };
1050                        let readings: Vec<Option<Vec<f64>>> = [0.25, 0.5, 0.75].into_iter().map(|t| roots_at(start + (end - start) * t)).collect();
1051                        if let [Some(r0), Some(r1), Some(r2)] = readings.as_slice() {
1052                            if r0.iter().zip(r1).chain(r0.iter().zip(r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1053                                kinds.push(Kind::RuledArc(r0.clone()));
1054                                continue;
1055                            }
1056                        }
1057                    }
1058                    if span >= PI {
1059                        return Err(refuse("revolved_arc", format!("meridian piece {i}: a half-round rim is swept only where its grazing curves keep their angle")));
1060                    }
1061                    let in_zone = |psi: f64| -> Result<Option<f64>, KernelRefusal> {
1062                        let (a, b, c) = harmonic(|v| g_tube(psi, v));
1063                        let r = a.hypot(b);
1064                        if !(c.abs() < r) {
1065                            return Ok(None);
1066                        }
1067                        let base = b.atan2(a);
1068                        let spread = (-c / r).acos();
1069                        let inside: Vec<f64> = [base - spread, base + spread]
1070                            .into_iter()
1071                            .map(|v| start + (v - start).rem_euclid(TAU))
1072                            .filter(|&v| v <= end)
1073                            .collect();
1074                        match inside.as_slice() {
1075                            [] => Ok(None),
1076                            [v] => Ok(Some(*v)),
1077                            _ => Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner twice at one angle"))),
1078                        }
1079                    };
1080                    let count = 720;
1081                    let has: Vec<bool> = (0..count).map(|k| in_zone(TAU * k as f64 / count as f64).map(|r| r.is_some())).collect::<Result<_, _>>()?;
1082                    let rises: Vec<usize> = (0..count).filter(|&k| has[k] && !has[(k + count - 1) % count]).collect();
1083                    let falls: Vec<usize> = (0..count).filter(|&k| !has[k] && has[(k + count - 1) % count]).collect();
1084                    let ([rise], [fall]) = (rises.as_slice(), falls.as_slice()) else {
1085                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve does not cross the rounded corner once")));
1086                    };
1087                    // The crossing's ends: roots of the grazing value along the rim it meets.
1088                    let estimate = |k: usize| TAU * (k as f64 - 0.5) / count as f64;
1089                    let (ea, eb) = (estimate(*rise), estimate(*fall));
1090                    let sample = |k: usize| TAU * (k % count) as f64 / count as f64;
1091                    let probe_v = in_zone(sample(*rise))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1092                    let at_end = (probe_v - end).abs() < (probe_v - start).abs();
1093                    let rim_v = if at_end { end } else { start };
1094                    let (a, b, c) = harmonic(|psi| g_tube(psi, rim_v));
1095                    let r = a.hypot(b);
1096                    let base = b.atan2(a);
1097                    let spread = (-c / r).acos();
1098                    let roots = [base - spread, base + spread];
1099                    let nearest = |e: f64| roots.iter().copied().min_by(|x, y| ((x - e + PI).rem_euclid(TAU) - PI).abs().total_cmp(&((y - e + PI).rem_euclid(TAU) - PI).abs())).expect("two");
1100                    let (psi_a, psi_b) = (nearest(ea).rem_euclid(TAU), nearest(eb).rem_euclid(TAU));
1101                    let psi_b = if psi_b <= psi_a { psi_b + TAU } else { psi_b };
1102                    let leave_v = in_zone(sample(*fall + count - 1))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1103                    if ((leave_v - end).abs() < (leave_v - start).abs()) != at_end {
1104                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner from rim to rim")));
1105                    }
1106                    kinds.push(Kind::TorusZone { psi_a, psi_b, at_end });
1107                    continue;
1108                }
1109                if !(centre_on_axis && (span - 0.5 * PI).abs() < 1e-12 && (pole_at_start && equator(p1) || on_axis(p1) && equator(p0))) {
1110                    // A cap of a sphere about the axis, from its pole to a rim
1111                    // short of (or past) the equator: swept where its grazing
1112                    // curves keep their angle about the axis (meridian arcs
1113                    // through the pole).
1114                    if centre_on_axis && end > start && span < PI && (pole_at_start != on_axis(p1)) {
1115                        let roots_at = |s: f64| -> Option<Vec<f64>> {
1116                            let (a, b, c) = harmonic(|psi| g(piece, s, psi));
1117                            let r = a.hypot(b);
1118                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1119                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1120                                return None;
1121                            }
1122                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1123                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1124                            list.sort_by(|x, y| x.total_cmp(y));
1125                            Some(list)
1126                        };
1127                        if let [Some(r0), Some(r1), Some(r2)] = [0.25, 0.5, 0.75].map(roots_at) {
1128                            if r0.iter().zip(&r1).chain(r0.iter().zip(&r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1129                                kinds.push(Kind::RuledArc(r0));
1130                                continue;
1131                            }
1132                        }
1133                    }
1134                    return Err(refuse("revolved_arc", format!("meridian piece {i}: only a quarter circle from a pole to an equator is swept here")));
1135                }
1136                kinds.push(Kind::Sphere { centre: origin.add(w.scale(centre[1])), pole_at_start });
1137            }
1138        }
1139    }
1140    // Rims: junctions off the axis, with the angles they are split at.
1141    let count = meridian.len();
1142    let junction = |k: usize| piece_point(&meridian[k], 1.0); // between piece k and k + 1
1143    let face_of = |piece: usize| faces.iter().position(|&f| f == piece);
1144    let mut rim_angles: HashMap<usize, Vec<f64>> = HashMap::new();
1145    for k in 0..count {
1146        if on_axis(junction(k)) {
1147            continue;
1148        }
1149        let mut angles: Vec<f64> = Vec::new();
1150        for (piece, s_end) in [(k, 1.0), ((k + 1) % count, 0.0)] {
1151            let Some(f) = face_of(piece) else { continue };
1152            match &kinds[f] {
1153                Kind::Ruled(roots) | Kind::RuledArc(roots) => angles.extend(roots.iter().copied()),
1154                Kind::Ball { .. } | Kind::Slide => {}
1155                Kind::SlideSide => angles.extend([0.0, PI]),
1156                Kind::TorusZone { psi_a, psi_b, .. } => angles.extend([psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)]),
1157                Kind::Moving => {
1158                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1159                    angles.extend([lower.rem_euclid(TAU), upper.rem_euclid(TAU)]);
1160                }
1161                Kind::Sphere { centre, .. } => {
1162                    let d = screw.velocity(*centre).cross(w);
1163                    let base = d.dot(u2).atan2(d.dot(u1)).rem_euclid(TAU);
1164                    angles.extend([base, (base + PI).rem_euclid(TAU)]);
1165                }
1166            }
1167        }
1168        angles.sort_by(|a, b| a.total_cmp(b));
1169        let mut merged: Vec<f64> = Vec::new();
1170        for a in angles {
1171            if merged.last().is_some_and(|&b| (a - b).abs() < 1e-9) || merged.first().is_some_and(|&b| (b + TAU - a).abs() < 1e-9) {
1172                continue;
1173            }
1174            merged.push(a);
1175        }
1176        rim_angles.insert(k, merged);
1177    }
1178    // Every face's own split angles must be its rims' (one arc per patch side).
1179    for (f, &piece) in faces.iter().enumerate() {
1180        for (k, s_end) in [((piece + count - 1) % count, 0.0), (piece, 1.0)] {
1181            let own: Vec<f64> = match &kinds[f] {
1182                Kind::Ruled(roots) | Kind::RuledArc(roots) => roots.clone(),
1183                Kind::Moving => {
1184                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1185                    let mut list = vec![lower.rem_euclid(TAU), upper.rem_euclid(TAU)];
1186                    list.sort_by(|a, b| a.total_cmp(b));
1187                    list
1188                }
1189                Kind::TorusZone { psi_a, psi_b, .. } => {
1190                    let mut list = vec![psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)];
1191                    list.sort_by(|a, b| a.total_cmp(b));
1192                    list
1193                }
1194                Kind::Sphere { .. } | Kind::Ball { .. } | Kind::Slide => continue,
1195                Kind::SlideSide => vec![0.0, PI],
1196            };
1197            if let Some(angles) = rim_angles.get(&k) {
1198                if own.is_empty() {
1199                    continue;
1200                }
1201                if angles.len() != own.len() || angles.iter().zip(&own).any(|(a, b)| (a - b).abs() > 1e-9) {
1202                    return Err(refuse("revolved_rims", format!("meridian piece {piece} splits at other angles than its rim")));
1203                }
1204            }
1205        }
1206    }
1207    let mut points: Vec<Vec3> = Vec::new();
1208    let mut curves: Vec<ToolCurve> = Vec::new();
1209    let mut caps: Vec<Cap> = Vec::new();
1210    let mut slides: Vec<SlideDisc> = Vec::new();
1211    let mut slide_sides: Vec<SlideSide> = Vec::new();
1212    // Rim points and arcs: arc j of rim k runs from angle j to angle j + 1.
1213    let mut rim_points: HashMap<(usize, usize), usize> = HashMap::new();
1214    let mut rim_arcs: HashMap<(usize, usize), usize> = HashMap::new();
1215    let mut rim_keys: Vec<usize> = rim_angles.keys().copied().collect();
1216    rim_keys.sort_unstable();
1217    for &k in &rim_keys {
1218        let q = junction(k);
1219        let angles = rim_angles[&k].clone();
1220        let angles = if angles.is_empty() { vec![0.0] } else { angles };
1221        for (j, &a) in angles.iter().enumerate() {
1222            points.push(at(q[0], q[1], a));
1223            rim_points.insert((k, j), points.len() - 1);
1224        }
1225        for j in 0..angles.len() {
1226            let a = angles[j];
1227            let b = if j + 1 < angles.len() { angles[j + 1] } else { angles[0] + TAU };
1228            let base = at(q[0], q[1], a);
1229            let surface = frag(make_revolution(origin, w, &frag(make_line(base, base.add(w)), "line")?, b - a), "rim")?;
1230            curves.push(ToolCurve {
1231                curve: frag(surface.iso_curve_v(0.0), "rim_arc")?,
1232                start: rim_points[&(k, j)],
1233                end: rim_points[&(k, (j + 1) % angles.len())],
1234                degenerate: false,
1235                samples: Some((0..=LOFT_SAMPLES).map(|i| at(q[0], q[1], a + (b - a) * i as f64 / LOFT_SAMPLES as f64)).collect()),
1236            });
1237            rim_arcs.insert((k, j), curves.len() - 1);
1238        }
1239        rim_angles.insert(k, angles);
1240    }
1241    let arc_index = |k: usize, angle: f64| -> Result<usize, KernelRefusal> {
1242        rim_angles[&k]
1243            .iter()
1244            .position(|&a| ((a - angle).rem_euclid(TAU)).min((angle - a).rem_euclid(TAU)) < 1e-9)
1245            .ok_or_else(|| refuse("revolved_rims", "a patch corner is not on its rim's split".into()))
1246    };
1247    let sign_at = |piece: &OutlinePiece, psi: f64| g(piece, 0.5, psi) > 0.0;
1248    for (f, &piece_index) in faces.iter().enumerate() {
1249        let piece = &meridian[piece_index];
1250        let below = (piece_index + count - 1) % count; // rim at the piece's start
1251        let above = piece_index; // rim at its end
1252        let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1253        match &kinds[f] {
1254            Kind::SlideSide => {
1255                if on_axis(m0) || on_axis(m1) {
1256                    return Err(refuse("revolved_grazing", format!("meridian piece {piece_index} grazes all over")));
1257                }
1258                let seams = [0.0, PI];
1259                let mut patches = Vec::with_capacity(2);
1260                for j in 0..2 {
1261                    let (alpha, theta) = (seams[j], PI);
1262                    let (ib, ia) = (arc_index(below, alpha)?, arc_index(above, alpha)?);
1263                    patches.push((alpha, theta, rim_arcs[&(below, ib)], rim_arcs[&(above, ia)], [rim_points[&(below, ib)], rim_points[&(above, ia)]]));
1264                }
1265                slide_sides.push(SlideSide { origin, w, patches });
1266            }
1267            Kind::RuledArc(roots) => {
1268                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1269                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1270                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1271                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1272                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1273                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1274                    let from = tube_point(psi, start);
1275                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1276                    frag(surface.iso_curve_v(0.0), "tube")
1277                };
1278                // A cap to its pole: the meridian arcs start (or end) there,
1279                // and each patch has a pole in place of a rim arc.
1280                let apex = if on_axis(m0) || on_axis(m1) {
1281                    let m = if on_axis(m0) { m0 } else { m1 };
1282                    points.push(at(0.0, m[1], 0.0));
1283                    Some(points.len() - 1)
1284                } else {
1285                    None
1286                };
1287                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1288                    match (on, apex) {
1289                        (true, Some(p)) => Ok(p),
1290                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1291                    }
1292                };
1293                let mut generators = Vec::with_capacity(roots.len());
1294                for &root in roots {
1295                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1296                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES).map(|i| tube_point(root, start + (end - start) * i as f64 / LOFT_SAMPLES as f64)).collect();
1297                    exact[0] = points[a];
1298                    exact[LOFT_SAMPLES] = points[b];
1299                    curves.push(ToolCurve { curve: generatrix(root)?, start: a, end: b, degenerate: false, samples: Some(exact) });
1300                    generators.push(curves.len() - 1);
1301                }
1302                for j in 0..roots.len() {
1303                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1304                    let surface = frag(make_revolution(origin, w, &generatrix(alpha)?, beta - alpha), "patch")?;
1305                    let (mid_psi, mid_v) = (0.5 * (alpha + beta), 0.5 * (start + end));
1306                    let mid_normal = w.scale(mid_v.sin()).add(u1.scale(mid_v.cos() * mid_psi.cos())).add(u2.scale(mid_v.cos() * mid_psi.sin()));
1307                    let front = screw.velocity(tube_point(mid_psi, mid_v)).dot(mid_normal) > 0.0;
1308                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1309                        let p = apex.expect("apex");
1310                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1311                        curves.len() - 1
1312                    };
1313                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1314                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1315                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1316                    let coedges = vec![
1317                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1318                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1319                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1320                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1321                    ];
1322                    let chart = Chart::Revolution {
1323                        origin,
1324                        w,
1325                        u1,
1326                        u2,
1327                        alpha,
1328                        theta: beta - alpha,
1329                        spans_u: spans_of(&surface.knots_u),
1330                        meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_of(&surface.knots_v) },
1331                    };
1332                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1333                }
1334            }
1335            Kind::Slide => {
1336                let rim = if on_axis(m0) { above } else { below };
1337                let n = normal(piece, 0.5);
1338                let outward = w.scale(n[1].signum());
1339                let arcs = rim_angles[&rim].len();
1340                // Counter-clockwise about the outward normal: increasing ψ about +w.
1341                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1342                slides.push(SlideDisc {
1343                    centre: origin.add(w.scale(m0[1])),
1344                    u: u1,
1345                    v: outward.cross(u1),
1346                    rim: order.into_iter().map(|j| (rim_arcs[&(rim, j)], n[1] > 0.0)).collect(),
1347                });
1348            }
1349            Kind::Ruled(roots) if roots.is_empty() => {
1350                // A flat end wholly on one side: a disc about the axis.
1351                let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
1352                if !flat || !(on_axis(m0) || on_axis(m1)) {
1353                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a whole side or ring is not swept here")));
1354                }
1355                let rim = if on_axis(m0) { above } else { below };
1356                let front = sign_at(piece, 0.0);
1357                if (0..64).any(|k| sign_at(piece, TAU * k as f64 / 64.0) != front) {
1358                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a flat end meets its grazing line")));
1359                }
1360                let n = normal(piece, 0.5);
1361                let outward = w.scale(n[1].signum());
1362                let centre = origin.add(w.scale(m0[1]));
1363                let (u, v) = (u1, outward.cross(u1));
1364                let arcs = rim_angles[&rim].len();
1365                let mut coedges = Vec::with_capacity(arcs);
1366                let mut corners = Vec::new();
1367                // Counter-clockwise about the outward normal: increasing ψ about +w.
1368                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1369                for j in order {
1370                    let c = rim_arcs[&(rim, j)];
1371                    let forward = n[1] > 0.0;
1372                    coedges.push((c, forward, plane_pcurve(centre, u, v, &curves[c].curve, forward)?));
1373                    corners.push(points[curves[c].start]);
1374                }
1375                let r = junction(rim)[0];
1376                corners.extend([centre.add(u.scale(r)).add(v.scale(r)), centre.sub(u.scale(r)).sub(v.scale(r))]);
1377                caps.push(Cap { surface: plane_patch(centre, u, v, &corners)?, front, coedges, chart: Some(Chart::Plane { origin: centre, u, v }) });
1378            }
1379            Kind::Ruled(roots) => {
1380                // A cone to a point: its generators start (or end) at the
1381                // apex, and each patch has a pole there in place of a rim arc.
1382                let apex = if on_axis(m0) || on_axis(m1) {
1383                    let m = if on_axis(m0) { m0 } else { m1 };
1384                    points.push(at(0.0, m[1], 0.0));
1385                    Some(points.len() - 1)
1386                } else {
1387                    None
1388                };
1389                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1390                    match (on, apex) {
1391                        (true, Some(p)) => Ok(p),
1392                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1393                    }
1394                };
1395                // Generators at each root, from the start rim to the end rim.
1396                let mut generators = Vec::with_capacity(roots.len());
1397                for &root in roots {
1398                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1399                    let line_samples = (0..=LOFT_SAMPLES).map(|i| points[a].add(points[b].sub(points[a]).scale(i as f64 / LOFT_SAMPLES as f64))).collect();
1400                    curves.push(ToolCurve { curve: frag(make_line(points[a], points[b]), "generator")?, start: a, end: b, degenerate: false, samples: Some(line_samples) });
1401                    generators.push(curves.len() - 1);
1402                }
1403                for j in 0..roots.len() {
1404                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1405                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1406                    let surface = frag(make_revolution(origin, w, &generatrix, beta - alpha), "patch")?;
1407                    let front = sign_at(piece, 0.5 * (alpha + beta));
1408                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1409                        let p = apex.expect("apex");
1410                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1411                        curves.len() - 1
1412                    };
1413                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1414                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1415                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1416                    let coedges = vec![
1417                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1418                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1419                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1420                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1421                    ];
1422                    let chart = Chart::Revolution { origin, w, u1, u2, alpha, theta: beta - alpha, spans_u: spans_of(&surface.knots_u), meridian: MeridianChart::Line { m0, m1 } };
1423                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1424                }
1425            }
1426            Kind::Moving => {
1427                if on_axis(m0) || on_axis(m1) {
1428                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a split cone to a point is not swept here")));
1429                }
1430                let n = 128;
1431                let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1432                let pairs: Vec<(f64, f64)> = params.iter().map(|&t| branches(piece, t).expect("checked")).collect();
1433                let pick = |pair: (f64, f64), which: usize| if which == 0 { pair.0 } else { pair.1 };
1434                // K: the lower and upper branch, each from the start rim to the end rim.
1435                let mut branch_curves = [0usize; 2];
1436                for which in 0..2 {
1437                    let (psi0, psi1) = (pick(pairs[0], which), pick(pairs[n], which));
1438                    let start = rim_points[&(below, arc_index(below, psi0)?)];
1439                    let end = rim_points[&(above, arc_index(above, psi1)?)];
1440                    let mut samples: Vec<Vec3> = params
1441                        .iter()
1442                        .zip(&pairs)
1443                        .map(|(&t, &pair)| {
1444                            let m = piece_point(piece, t);
1445                            at(m[0], m[1], pick(pair, which))
1446                        })
1447                        .collect();
1448                    samples[0] = points[start];
1449                    samples[n] = points[end];
1450                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES)
1451                        .map(|i| {
1452                            let t = i as f64 / LOFT_SAMPLES as f64;
1453                            let m = piece_point(piece, t);
1454                            at(m[0], m[1], pick(branches(piece, t).expect("checked"), which))
1455                        })
1456                        .collect();
1457                    exact[0] = points[start];
1458                    exact[LOFT_SAMPLES] = points[end];
1459                    curves.push(ToolCurve { curve: frag(fit_tool_curve(&samples, &params), "branch")?, start, end, degenerate: false, samples: Some(exact) });
1460                    branch_curves[which] = curves.len() - 1;
1461                }
1462                // Front between lower and upper; back from upper to lower + 2π.
1463                for (lo_which, hi_which, hi_turn) in [(0usize, 1usize, 0.0), (1, 0, TAU)] {
1464                    let lo = |i: usize| pick(pairs[i], lo_which);
1465                    let hi = |i: usize| pick(pairs[i], hi_which) + hi_turn;
1466                    let alpha = (0..=n).map(lo).fold(f64::INFINITY, f64::min) - 1e-3;
1467                    let theta = (0..=n).map(hi).fold(f64::NEG_INFINITY, f64::max) + 1e-3 - alpha;
1468                    if theta >= TAU {
1469                        return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a side patch wraps all the way round")));
1470                    }
1471                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1472                    let surface = frag(make_revolution(origin, w, &generatrix, theta), "patch")?;
1473                    let spans = (surface.knots_u.len() - 6) / 2 + 1;
1474                    let u_of = |psi: f64| crate::circle_angle_to_parameter(spans, theta, psi - alpha);
1475                    let angle_near = |x: Vec3, guess: f64| -> f64 {
1476                        let r = x.sub(origin);
1477                        let a = r.dot(u2).atan2(r.dot(u1));
1478                        guess + (a - guess + PI).rem_euclid(TAU) - PI
1479                    };
1480                    let front = sign_at(piece, 0.5 * (lo(n / 2) + hi(n / 2)));
1481                    // A rim arc's pcurve on this patch, through its own parameter.
1482                    let rim_pcurve = |arc: usize, v: f64| -> Result<NurbsCurve, KernelRefusal> {
1483                        let curve = &curves[arc].curve;
1484                        let [d0, d1] = frag(curve.domain(), "domain")?;
1485                        let ts: Vec<f64> = pcurve_stations(d0, d1);
1486                        let mut uv = Vec::with_capacity(ts.len());
1487                        for &t in &ts {
1488                            let x = frag(curve.evaluate(t), "rim")?;
1489                            uv.push(Vec3::new(u_of(angle_near(x, alpha + 0.5 * theta)), v, 0.0));
1490                        }
1491                        if pcurve_joints_on() {
1492                            let (ju, jv) = surface_joints(&surface);
1493                            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok([u_of(angle_near(frag(curve.evaluate(t), "rim")?, alpha + 0.5 * theta)), v]) };
1494                            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &ju, &jv, curve)? {
1495                                return Ok(fitted);
1496                            }
1497                        }
1498                        frag(fit_pcurve(&uv, &ts), "rim_pcurve")
1499                    };
1500                    // A grazing branch's pcurve: the image of the built edge,
1501                    // through its own parameter (angle about the axis; place
1502                    // along the meridian line).
1503                    let branch_pcurve = |which: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> {
1504                        let curve = &curves[branch_curves[which]].curve;
1505                        let [d0, d1] = frag(curve.domain(), "domain")?;
1506                        let (span_rho, span_z) = (m1[0] - m0[0], m1[1] - m0[1]);
1507                        let length2 = span_rho * span_rho + span_z * span_z;
1508                        let ts: Vec<f64> = pcurve_stations(d0, d1);
1509                        let mut uv = Vec::with_capacity(ts.len());
1510                        let read = |x: Vec3| -> [f64; 2] {
1511                            let r = x.sub(origin);
1512                            let z = r.dot(w);
1513                            let rho = r.sub(w.scale(z)).length();
1514                            let along = ((rho - m0[0]) * span_rho + (z - m0[1]) * span_z) / length2;
1515                            [u_of(angle_near(x, alpha + 0.5 * theta)), along]
1516                        };
1517                        for &t in &ts {
1518                            let [u, along] = read(frag(curve.evaluate(t), "branch")?);
1519                            uv.push(Vec3::new(u, along, 0.0));
1520                        }
1521                        if pcurve_joints_on() {
1522                            let (ju, jv) = surface_joints(&surface);
1523                            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok(read(frag(curve.evaluate(t), "branch")?)) };
1524                            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &ju, &jv, curve)? {
1525                                return Ok(fitted);
1526                            }
1527                        }
1528                        frag(fit_pcurve(&uv, &ts), "branch_pcurve")
1529                    };
1530                    let bottom = rim_arcs[&(below, arc_index(below, lo(0))?)];
1531                    let top = rim_arcs[&(above, arc_index(above, lo(n))?)];
1532                    let coedges = vec![
1533                        (bottom, true, rim_pcurve(bottom, 0.0)?),
1534                        (branch_curves[hi_which], true, branch_pcurve(hi_which, hi_turn)?),
1535                        (top, false, frag(rim_pcurve(top, 1.0)?.reversed(), "reversed")?),
1536                        (branch_curves[lo_which], false, frag(branch_pcurve(lo_which, 0.0)?.reversed(), "reversed")?),
1537                    ];
1538                    let chart_spans = spans_of(&surface.knots_u);
1539                    caps.push(Cap { surface, front, coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha, theta, spans_u: chart_spans, meridian: MeridianChart::Line { m0, m1 } }) });
1540                }
1541            }
1542            Kind::TorusZone { psi_a, psi_b, at_end } => {
1543                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1544                let (psi_a, psi_b, at_end) = (*psi_a, *psi_b, *at_end);
1545                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1546                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1547                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1548                let normal_at = |psi: f64, v: f64| w.scale(v.sin()).add(u1.scale(v.cos() * psi.cos())).add(u2.scale(v.cos() * psi.sin()));
1549                let root = |psi: f64| -> Option<f64> {
1550                    let (a, b, c) = harmonic(|v| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)));
1551                    let r = a.hypot(b);
1552                    if !(c.abs() < r) {
1553                        return None;
1554                    }
1555                    let base = b.atan2(a);
1556                    let spread = (-c / r).acos();
1557                    [base - spread, base + spread].into_iter().map(|v| start + (v - start).rem_euclid(TAU)).find(|&v| v <= end + 1e-12)
1558                };
1559                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1560                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1561                    let from = tube_point(psi, start);
1562                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1563                    frag(surface.iso_curve_v(0.0), "tube")
1564                };
1565                let (rim_k, other_k) = if at_end { (above, below) } else { (below, above) };
1566                let ka = rim_points[&(rim_k, arc_index(rim_k, psi_a)?)];
1567                let kb = rim_points[&(rim_k, arc_index(rim_k, psi_b)?)];
1568                // K: the graph over ψ ∈ [ψa, ψb].
1569                let n = 256;
1570                let params: Vec<f64> = (0..=n).map(|j| j as f64 / n as f64).collect();
1571                // Spaced as 1 − cos: where K meets its rim it runs along the
1572                // meridian, so its tube angle goes as √(ψ − ψa); in this
1573                // parameter it is regular.
1574                let psi_of = |t: f64| psi_a + (psi_b - psi_a) * 0.5 * (1.0 - (PI * t).cos());
1575                let mut xyz = Vec::with_capacity(n + 1);
1576                for j in 0..=n {
1577                    let psi = psi_of(params[j]);
1578                    let v = if j == 0 || j == n { if at_end { end } else { start } } else {
1579                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1580                    };
1581                    xyz.push(tube_point(psi, v));
1582                }
1583                xyz[0] = points[ka];
1584                xyz[n] = points[kb];
1585                let mut exact = Vec::with_capacity(LOFT_SAMPLES + 1);
1586                for i in 0..=LOFT_SAMPLES {
1587                    let psi = psi_of(i as f64 / LOFT_SAMPLES as f64);
1588                    let v = if i == 0 || i == LOFT_SAMPLES { if at_end { end } else { start } } else {
1589                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1590                    };
1591                    exact.push(tube_point(psi, v));
1592                }
1593                exact[0] = points[ka];
1594                exact[LOFT_SAMPLES] = points[kb];
1595                curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "torus_k")?, start: ka, end: kb, degenerate: false, samples: Some(exact) });
1596                let k_curve = curves.len() - 1;
1597                // Cut meridians at ψa and ψb, from the start rim to the end rim.
1598                let mut cut = [0usize; 2];
1599                for (slot, psi) in [(0, psi_a), (1, psi_b)] {
1600                    let (lo, hi) = (rim_points[&(below, arc_index(below, psi)?)], rim_points[&(above, arc_index(above, psi)?)]);
1601                    curves.push(ToolCurve { curve: generatrix(psi)?, start: lo, end: hi, degenerate: false, samples: None });
1602                    cut[slot] = curves.len() - 1;
1603                }
1604                let label = |psi: f64, v: f64| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)) > 0.0;
1605                // The patch over [α, β] and its exact inverse.
1606                let patch = |alpha: f64, beta: f64| -> Result<(NurbsSurface, usize, usize), KernelRefusal> {
1607                    let g = generatrix(alpha)?;
1608                    let surface = frag(make_revolution(origin, w, &g, beta - alpha), "torus_patch")?;
1609                    let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1610                    let spans_v = (g.knots.len() - 6) / 2 + 1;
1611                    Ok((surface, spans_u, spans_v))
1612                };
1613                let inverse_pcurve = |curve: &NurbsCurve, alpha: f64, beta: f64, spans_u: usize, spans_v: usize, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
1614                    let [d0, d1] = frag(curve.domain(), "domain")?;
1615                    let ts: Vec<f64> = pcurve_stations(d0, d1);
1616                    let mut uv = Vec::with_capacity(ts.len());
1617                    let read = |x: Vec3| -> [f64; 2] {
1618                        let r = x.sub(origin);
1619                        let mid = 0.5 * (alpha + beta);
1620                        let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
1621                        let q = x.sub(tube_centre(psi));
1622                        let radial = u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1623                        let vmid = 0.5 * (start + end);
1624                        let v = vmid + (q.dot(w).atan2(q.dot(radial)) - vmid + PI).rem_euclid(TAU) - PI;
1625                        [crate::circle_angle_to_parameter(spans_u, beta - alpha, psi - alpha), crate::circle_angle_to_parameter(spans_v, end - start, v - start)]
1626                    };
1627                    for &t in &ts {
1628                        let [u, v] = read(frag(curve.evaluate(t), "point")?);
1629                        uv.push(Vec3::new(u, v, 0.0));
1630                    }
1631                    if pcurve_joints_on() {
1632                        let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
1633                        let at = |t: f64| -> Result<[f64; 2], KernelRefusal> { Ok(read(frag(curve.evaluate(t), "point")?)) };
1634                        if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
1635                            return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
1636                        }
1637                    }
1638                    let fitted = frag(fit_pcurve(&uv, &ts), "torus_pcurve")?;
1639                    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
1640                };
1641                // The band away from K: a natural patch over [ψb, ψa + 2π].
1642                {
1643                    let (surface, _, band_spans_v) = patch(psi_b, psi_a + TAU)?;
1644                    let (bottom, top) = (rim_arcs[&(below, arc_index(below, psi_b)?)], rim_arcs[&(above, arc_index(above, psi_b)?)]);
1645                    let coedges = vec![
1646                        (bottom, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1647                        (cut[0], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1648                        (top, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1649                        (cut[1], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1650                    ];
1651                    let mid = psi_b + 0.5 * (psi_a + TAU - psi_b);
1652                    let chart_spans = spans_of(&surface.knots_u);
1653                    caps.push(Cap { surface, front: label(mid, 0.5 * (start + end)), coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_b, theta: psi_a + TAU - psi_b, spans_u: chart_spans, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: band_spans_v } }) });
1654                }
1655                // Over [ψa, ψb]: the lens between K and its rim, and the rest.
1656                let (surface, spans_u, spans_v) = patch(psi_a, psi_b)?;
1657                let rim_arc = rim_arcs[&(rim_k, arc_index(rim_k, psi_a)?)];
1658                let other_arc = rim_arcs[&(other_k, arc_index(other_k, psi_a)?)];
1659                let mid = 0.5 * (psi_a + psi_b);
1660                let v_k = root(mid).ok_or_else(|| refuse("torus_zone", "no grazing point mid-way".into()))?;
1661                let k_pc = |forward: bool| inverse_pcurve(&curves[k_curve].curve, psi_a, psi_b, spans_u, spans_v, forward);
1662                let lens_v = if at_end { 0.5 * (v_k + end) } else { 0.5 * (v_k + start) };
1663                let rest_v = if at_end { 0.5 * (v_k + start) } else { 0.5 * (v_k + end) };
1664                if at_end {
1665                    // Lens: K (ψa -> ψb) under the end rim, then the end rim back.
1666                    let lens = vec![(k_curve, true, k_pc(true)?), (rim_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?)];
1667                    caps.push(Cap { surface: surface.clone(), front: label(mid, lens_v), coedges: lens, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1668                    let rest = vec![
1669                        (other_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1670                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1671                        (k_curve, false, k_pc(false)?),
1672                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1673                    ];
1674                    caps.push(Cap { surface, front: label(mid, rest_v), coedges: rest, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1675                } else {
1676                    let lens = vec![(rim_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?), (k_curve, false, k_pc(false)?)];
1677                    caps.push(Cap { surface: surface.clone(), front: label(mid, lens_v), coedges: lens, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1678                    let rest = vec![
1679                        (k_curve, true, k_pc(true)?),
1680                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1681                        (other_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1682                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1683                    ];
1684                    caps.push(Cap { surface, front: label(mid, rest_v), coedges: rest, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_v } }) });
1685                }
1686            }
1687            Kind::Ball { centre, radius } => {
1688                let m = frag(screw.velocity(*centre).normalized(), "ball_still")?;
1689                let d = frag(w.cross(m).normalized().or_else(|_| u1.cross(m).normalized()), "ball_axis")?;
1690                let (e1, e2) = (centre.add(d.scale(*radius)), centre.sub(d.scale(*radius)));
1691                points.push(e1);
1692                points.push(e2);
1693                let (i1, i2) = (points.len() - 2, points.len() - 1);
1694                let half = frag(make_revolution(*centre, m, &frag(make_line(e1, e1.add(m)), "line")?, PI), "great")?;
1695                let k_a = frag(half.iso_curve_v(0.0), "great")?;
1696                // Exact samples at even angles from e1 round to e2 (for a
1697                // lofted wall), turned the way the curve runs.
1698                let k_a_samples: Vec<Vec3> = {
1699                    let [a0, a1] = frag(k_a.domain(), "domain")?;
1700                    let middle = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?;
1701                    let arm = e1.sub(*centre);
1702                    let sense = if arm.rotate_about(m, 0.5 * PI).add(*centre).sub(middle).length() < arm.rotate_about(m, -0.5 * PI).add(*centre).sub(middle).length() { 1.0 } else { -1.0 };
1703                    let mut list: Vec<Vec3> = (0..=LOFT_SAMPLES).map(|i| centre.add(arm.rotate_about(m, sense * PI * i as f64 / LOFT_SAMPLES as f64))).collect();
1704                    list[0] = e1;
1705                    list[LOFT_SAMPLES] = e2;
1706                    list
1707                };
1708                curves.push(ToolCurve { curve: k_a.clone(), start: i1, end: i2, degenerate: false, samples: Some(k_a_samples.clone()) });
1709                let k_a_index = curves.len() - 1;
1710                let [a0, a1] = frag(k_a.domain(), "domain")?;
1711                let h = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?.sub(*centre);
1712                let mut k_b_index: Option<usize> = None;
1713                for front in [true, false] {
1714                    let toward = if front { m } else { m.scale(-1.0) };
1715                    let da = if d.cross(h).dot(toward) > 0.0 { d } else { d.scale(-1.0) };
1716                    let mut generatrix = k_a.clone();
1717                    let mut surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1718                    let outward = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1719                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1720                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1721                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1722                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1723                    };
1724                    let mut forward = true;
1725                    if !outward(&surface)? {
1726                        generatrix = frag(generatrix.reversed(), "reversed")?;
1727                        surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1728                        forward = false;
1729                    }
1730                    let (start, end) = if forward { (i1, i2) } else { (i2, i1) };
1731                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1732                    let k_b = match k_b_index {
1733                        Some(index) => index,
1734                        None => {
1735                            // The other half of the great circle: the first half turned half way about `da`.
1736                            let mut samples: Vec<Vec3> = k_a_samples.iter().map(|&x| centre.add(x.sub(*centre).rotate_about(da, PI))).collect();
1737                            if !forward {
1738                                samples.reverse();
1739                            }
1740                            samples[0] = points[start];
1741                            samples[LOFT_SAMPLES] = points[end];
1742                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: Some(samples) });
1743                            k_b_index = Some(curves.len() - 1);
1744                            curves.len() - 1
1745                        }
1746                    };
1747                    let k_b_forward = curves[k_b].start == start;
1748                    let k_b_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1749                    let poles = [start, end].map(|p| {
1750                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1751                        curves.len() - 1
1752                    });
1753                    let coedges = vec![
1754                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1755                        (k_b, k_b_forward, k_b_pcurve),
1756                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1757                        (k_a_index, !forward, uv_line([0.0, g1], [0.0, g0])?),
1758                    ];
1759                    caps.push(Cap { surface, front, coedges, chart: None });
1760                }
1761            }
1762            Kind::Sphere { centre, pole_at_start } => {
1763                let rim = if *pole_at_start { above } else { below };
1764                let angles = rim_angles[&rim].clone();
1765                if angles.len() != 2 {
1766                    return Err(refuse("revolved_rims", "a hemisphere's rim is not split in two".into()));
1767                }
1768                let pole_side = w.scale(if *pole_at_start { m0[1] - m1[1] } else { m1[1] - m0[1] }.signum());
1769                let m = screw.velocity(*centre);
1770                let e1 = points[rim_points[&(rim, 0)]];
1771                let d = frag(e1.sub(*centre).normalized(), "lune_axis")?;
1772                let mut great: Option<usize> = None;
1773                for j in 0..2 {
1774                    let arc = rim_arcs[&(rim, j)];
1775                    let [a0, a1] = frag(curves[arc].curve.domain(), "domain")?;
1776                    let middle = frag(curves[arc].curve.evaluate(0.5 * (a0 + a1)), "middle")?;
1777                    let hv = middle.sub(*centre);
1778                    let da = if d.cross(hv).dot(pole_side) > 0.0 { d } else { d.scale(-1.0) };
1779                    // Turn the rim arc about da until its middle reaches K's plane.
1780                    let theta = (-m.dot(hv)).atan2(m.dot(da.cross(hv))).rem_euclid(TAU);
1781                    let theta = if theta > PI { theta - PI } else { theta };
1782                    if !(theta > 1e-9 && theta < PI - 1e-9) {
1783                        return Err(refuse("revolved_lune", "the great circle meets the rim's plane edge-on".into()));
1784                    }
1785                    let mut generatrix = curves[arc].curve.clone();
1786                    let mut surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1787                    // Outward: (x − centre) at the lune's middle.
1788                    let probe = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1789                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1790                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1791                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1792                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1793                    };
1794                    let mut forward = true;
1795                    if !probe(&surface)? {
1796                        generatrix = frag(generatrix.reversed(), "reversed")?;
1797                        surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1798                        forward = false;
1799                    }
1800                    let (start, end) = if forward { (curves[arc].start, curves[arc].end) } else { (curves[arc].end, curves[arc].start) };
1801                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1802                    // The great-circle half: the turned generatrix (u = 1), from
1803                    // `start` to `end`; made once, by the first lune.
1804                    let k_curve = match great {
1805                        Some(index) => index,
1806                        None => {
1807                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: None });
1808                            great = Some(curves.len() - 1);
1809                            curves.len() - 1
1810                        }
1811                    };
1812                    let k_forward = curves[k_curve].start == start;
1813                    let poles = [start, end].map(|p| {
1814                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1815                        curves.len() - 1
1816                    });
1817                    let k_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1818                    let coedges = vec![
1819                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1820                        (k_curve, k_forward, k_pcurve),
1821                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1822                        (arc, !forward, uv_line([0.0, g1], [0.0, g0])?),
1823                    ];
1824                    let mid_psi = if j == 0 { 0.5 * (angles[0] + angles[1]) } else { 0.5 * (angles[1] + angles[0] + TAU) };
1825                    let front = m.dot(at(1.0, 0.0, mid_psi).sub(origin)) > 0.0;
1826                    caps.push(Cap { surface, front, coedges, chart: None });
1827                }
1828            }
1829        }
1830    }
1831    Ok(Split {
1832        points,
1833        curves,
1834        caps,
1835        slides,
1836        slide_sides,
1837        scale,
1838        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
1839    })
1840}
1841
1842/// `BREP_SWEEP_RING_WINDING` (default off): a ring whose grazing curves wind
1843/// round its tube as they go once round the ring is split along their
1844/// continuous unwrapping, in six pieces, instead of refused.
1845fn ring_winding_on() -> bool {
1846    crate::switch!("BREP_SWEEP_RING_WINDING", false)
1847}
1848
1849/// A ring split by grazing curves that wind round its tube: the curves' angle
1850/// v on the tube, unwrapped continuously along ψ, gains a whole number of
1851/// turns going once round the ring. None where it gains none (the two-halves
1852/// split serves). Six pieces along ψ keep each band's stretch of v short of a
1853/// whole turn while the curves turn, and leave the tumble's eight trial seams
1854/// (π/4 apart) four distinct placements.
1855#[allow(clippy::too_many_arguments)]
1856fn split_torus_wound(
1857    screw: &Screw,
1858    origin: Vec3,
1859    w: Vec3,
1860    u1: Vec3,
1861    u2: Vec3,
1862    centre: [f64; 2],
1863    radius: f64,
1864    meridian: &[OutlinePiece],
1865) -> Result<Option<Split>, KernelRefusal> {
1866    const PIECES: usize = 6;
1867    let (rho_c, z_c) = (centre[0], centre[1]);
1868    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1869    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
1870    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
1871    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
1872    let n = screw.loop_samples;
1873    let total = PIECES * n;
1874    // (ψ, lower, upper) round the whole ring, each base angle the one nearest
1875    // the last.
1876    let mut round: Vec<(f64, f64, f64)> = Vec::with_capacity(total + 1);
1877    let mut near = {
1878        let (a, b, _) = harmonic(|v| g(0.0, v));
1879        b.atan2(a)
1880    };
1881    for i in 0..=total {
1882        let psi = TAU * i as f64 / total as f64;
1883        let (a, b, c) = harmonic(|v| g(psi, v));
1884        let r = a.hypot(b);
1885        if !(c.abs() < r * (1.0 - 1e-9)) {
1886            return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
1887        }
1888        let base = near + (b.atan2(a) - near + PI).rem_euclid(TAU) - PI;
1889        if i > 0 && (base - near).abs() > 0.5 {
1890            return Err(refuse("ring_grazing", "the ring's grazing curves turn too fast".into()));
1891        }
1892        near = base;
1893        let spread = (-c / r).acos();
1894        round.push((psi, base - spread, base + spread));
1895    }
1896    if ((round[total].1 - round[0].1) / TAU).round() == 0.0 {
1897        return Ok(None);
1898    }
1899    let samples: Vec<Vec<(f64, f64, f64)>> = (0..PIECES).map(|k| round[k * n..=(k + 1) * n].to_vec()).collect();
1900    let seam_psi = |k: usize| TAU * k as f64 / PIECES as f64;
1901    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1902    let mut points: Vec<Vec3> = Vec::new();
1903    let mut curves: Vec<ToolCurve> = Vec::new();
1904    // Points: at each seam, on each branch (the last piece ends on seam 0,
1905    // a whole number of turns round the tube on).
1906    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, branch)
1907    for (seam, piece) in samples.iter().enumerate() {
1908        let (psi, lower, upper) = piece[0];
1909        for (branch, v) in [(0, lower), (1, upper)] {
1910            points.push(point(psi, v));
1911            corner.insert((seam, branch), points.len() - 1);
1912        }
1913    }
1914    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (piece, branch)
1915    for (piece, list) in samples.iter().enumerate() {
1916        for branch in 0..2 {
1917            let mut xyz: Vec<Vec3> = list.iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
1918            let (start, end) = (corner[&(piece, branch)], corner[&((piece + 1) % PIECES, branch)]);
1919            xyz[0] = points[start];
1920            xyz[n] = points[end];
1921            curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
1922            branch_curve.insert((piece, branch), curves.len() - 1);
1923        }
1924    }
1925    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
1926        let start = point(psi, v0);
1927        let axis = radial(psi).cross(w);
1928        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
1929        frag(surface.iso_curve_v(0.0), "tube_arc")
1930    };
1931    // Seam arcs of each band: band 0 (front) from lower to upper, band 1
1932    // (back) from upper to lower + 2π.
1933    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
1934    for seam in 0..PIECES {
1935        let (psi, lower, upper) = samples[seam][0];
1936        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
1937        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
1938        seam_arc.insert((seam, 0), curves.len() - 1);
1939        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
1940        seam_arc.insert((seam, 1), curves.len() - 1);
1941    }
1942    let mut caps = Vec::new();
1943    for piece in 0..PIECES {
1944        let (psi_a, psi_b) = (seam_psi(piece), seam_psi(piece + 1));
1945        for band in 0..2 {
1946            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
1947            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
1948            // As in the two-halves split: a margin each side for end trims.
1949            let low = samples[piece].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
1950            let high = samples[piece].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
1951            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
1952            let (v_low, v_high) = (low - margin, high + margin);
1953            let theta_v = v_high - v_low;
1954            if theta_v >= TAU {
1955                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
1956            }
1957            let generatrix = tube_arc(psi_a, v_low, v_high)?;
1958            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
1959            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1960            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
1961            let uv_of = |psi: f64, v: f64| {
1962                Vec3::new(
1963                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
1964                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
1965                    0.0,
1966                )
1967            };
1968            let angles_of = |x: Vec3| -> (f64, f64) {
1969                let r = x.sub(origin);
1970                let psi = r.dot(u2).atan2(r.dot(u1));
1971                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
1972                let q = x.sub(tube_centre(psi));
1973                let v = q.dot(w).atan2(q.dot(radial(psi)));
1974                let mid = 0.5 * (v_low + v_high);
1975                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
1976            };
1977            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
1978                let [d0, d1] = frag(curve.domain(), "domain")?;
1979                let ts: Vec<f64> = pcurve_stations(d0, d1);
1980                let mut uv = Vec::with_capacity(ts.len());
1981                for &t in &ts {
1982                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1983                    uv.push(uv_of(psi, v));
1984                }
1985                // Broken at the band's span joints (`BREP_SWEEP_PCURVE_JOINTS`).
1986                if pcurve_joints_on() {
1987                    let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
1988                    let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
1989                        let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1990                        let p = uv_of(psi, v);
1991                        Ok([p.x, p.y])
1992                    };
1993                    if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
1994                        return Ok(fitted);
1995                    }
1996                }
1997                frag(fit_pcurve(&uv, &ts), "ring_pcurve")
1998            };
1999            let lower_edge = branch_curve[&(piece, lo_branch)];
2000            let upper_edge = branch_curve[&(piece, hi_branch)];
2001            let right = seam_arc[&((piece + 1) % PIECES, band)];
2002            let left = seam_arc[&(piece, band)];
2003            let coedges = vec![
2004                (lower_edge, true, inverse_pcurve(&curves[lower_edge].curve)?),
2005                (right, true, inverse_pcurve(&curves[right].curve)?),
2006                (upper_edge, false, frag(inverse_pcurve(&curves[upper_edge].curve)?.reversed(), "reversed")?),
2007                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
2008            ];
2009            let mid = &samples[piece][n / 2];
2010            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
2011            caps.push(Cap { surface, front, coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre: [rho_c, z_c], start: v_low, sweep: theta_v, spans: spans_v } }) });
2012        }
2013    }
2014    Ok(Some(Split {
2015        points,
2016        curves,
2017        caps,
2018        slides: Vec::new(),
2019        slide_sides: Vec::new(),
2020        scale: rho_c + radius,
2021        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
2022    }))
2023}
2024
2025/// A ring (torus: the circle of `radius` about `centre` in (ρ, z), off the
2026/// axis), split by its two grazing curves. For each angle ψ about the ring's
2027/// axis the grazing value along the tube's circle is A cos v + B sin v + C, so
2028/// each curve is a graph v(ψ) round the ring; the front band lies between
2029/// them. Each band is built in two halves (ψ in [0, π] and [π, 2π]) so no face
2030/// closes on itself.
2031#[allow(clippy::too_many_arguments)]
2032fn split_torus(
2033    screw: &Screw,
2034    origin: Vec3,
2035    w: Vec3,
2036    u1: Vec3,
2037    u2: Vec3,
2038    centre: [f64; 2],
2039    radius: f64,
2040    meridian: &[OutlinePiece],
2041) -> Result<Split, KernelRefusal> {
2042    if ring_winding_on() {
2043        if let Some(split) = split_torus_wound(screw, origin, w, u1, u2, centre, radius, meridian)? {
2044            return Ok(split);
2045        }
2046    }
2047    let (rho_c, z_c) = (centre[0], centre[1]);
2048    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
2049    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
2050    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
2051    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
2052    let reference = {
2053        let (a, b, _) = harmonic(|v| g(0.0, v));
2054        b.atan2(a)
2055    };
2056    // The lower and upper grazing angles v at ψ, unwrapped; the front between.
2057    let branches = |psi: f64| -> Option<(f64, f64)> {
2058        let (a, b, c) = harmonic(|v| g(psi, v));
2059        let r = a.hypot(b);
2060        if !(c.abs() < r * (1.0 - 1e-9)) {
2061            return None;
2062        }
2063        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
2064        let spread = (-c / r).acos();
2065        Some((base - spread, base + spread))
2066    };
2067    let n = screw.loop_samples;
2068    let halves = [(0.0, PI), (PI, TAU)];
2069    let mut samples: Vec<Vec<(f64, f64, f64)>> = Vec::new(); // per half: (ψ, lower, upper)
2070    for &(a, b) in &halves {
2071        let mut list = Vec::with_capacity(n + 1);
2072        let mut previous: Option<(f64, f64)> = None;
2073        for i in 0..=n {
2074            let psi = a + (b - a) * i as f64 / n as f64;
2075            let Some(pair) = branches(psi) else {
2076                return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
2077            };
2078            if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
2079                return Err(refuse("ring_grazing", "the ring's grazing curves turn too fast".into()));
2080            }
2081            previous = Some(pair);
2082            list.push((psi, pair.0, pair.1));
2083        }
2084        samples.push(list);
2085    }
2086    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
2087    let mut points: Vec<Vec3> = Vec::new();
2088    let mut curves: Vec<ToolCurve> = Vec::new();
2089    // Points: at ψ = 0 and π, on each branch.
2090    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam 0 | 1, branch)
2091    for seam in 0..2 {
2092        let (psi, (lower, upper)) = if seam == 0 { (0.0, (samples[0][0].1, samples[0][0].2)) } else { (PI, (samples[1][0].1, samples[1][0].2)) };
2093        for (branch, v) in [(0, lower), (1, upper)] {
2094            points.push(point(psi, v));
2095            corner.insert((seam, branch), points.len() - 1);
2096        }
2097    }
2098    let seam_of_end = |half: usize, at_end: bool| -> usize { if at_end { 1 - half } else { half } };
2099    // K: each branch over each half.
2100    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (half, branch)
2101    for half in 0..2 {
2102        for branch in 0..2 {
2103            let mut xyz: Vec<Vec3> = samples[half].iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
2104            let (start, end) = (corner[&(seam_of_end(half, false), branch)], corner[&(seam_of_end(half, true), branch)]);
2105            xyz[0] = points[start];
2106            xyz[n] = points[end];
2107            curves.push(ToolCurve { curve: frag(fit_tool_curve(&xyz, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
2108            branch_curve.insert((half, branch), curves.len() - 1);
2109        }
2110    }
2111    // Seam arcs of each band at ψ = 0 and π: band 0 (front) from lower to
2112    // upper, band 1 (back) from upper to lower + 2π.
2113    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
2114        let start = point(psi, v0);
2115        let axis = radial(psi).cross(w);
2116        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
2117        frag(surface.iso_curve_v(0.0), "tube_arc")
2118    };
2119    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
2120    for seam in 0..2 {
2121        let psi = if seam == 0 { 0.0 } else { PI };
2122        let (lower, upper) = (samples[seam][0].1, samples[seam][0].2);
2123        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
2124        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
2125        seam_arc.insert((seam, 0), curves.len() - 1);
2126        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
2127        seam_arc.insert((seam, 1), curves.len() - 1);
2128    }
2129    let mut caps = Vec::new();
2130    for half in 0..2 {
2131        let (psi_a, psi_b) = halves[half];
2132        for band in 0..2 {
2133            // The band's lower and upper edges (v), as branches.
2134            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
2135            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
2136            // A margin each side: an end cap may be carried a little across its
2137            // grazing curve (see `end_trim`), as far as the tube leaves room.
2138            let low = samples[half].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
2139            let high = samples[half].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
2140            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
2141            let (v_low, v_high) = (low - margin, high + margin);
2142            let theta_v = v_high - v_low;
2143            if theta_v >= TAU {
2144                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
2145            }
2146            let generatrix = tube_arc(psi_a, v_low, v_high)?;
2147            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
2148            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
2149            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
2150            let uv_of = |psi: f64, v: f64| {
2151                Vec3::new(
2152                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
2153                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
2154                    0.0,
2155                )
2156            };
2157            // (ψ, v) of a point, unwrapped near the patch.
2158            let angles_of = |x: Vec3| -> (f64, f64) {
2159                let r = x.sub(origin);
2160                let psi = r.dot(u2).atan2(r.dot(u1));
2161                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
2162                let q = x.sub(tube_centre(psi));
2163                let v = q.dot(w).atan2(q.dot(radial(psi)));
2164                let mid = 0.5 * (v_low + v_high);
2165                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
2166            };
2167            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
2168                let [d0, d1] = frag(curve.domain(), "domain")?;
2169                let ts: Vec<f64> = pcurve_stations(d0, d1);
2170                let mut uv = Vec::with_capacity(ts.len());
2171                for &t in &ts {
2172                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
2173                    uv.push(uv_of(psi, v));
2174                }
2175                // Broken at the band's span joints (`BREP_SWEEP_PCURVE_JOINTS`).
2176                if pcurve_joints_on() {
2177                    let joints = |spans: usize| (1..spans).map(|k| k as f64 / spans as f64).collect::<Vec<f64>>();
2178                    let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
2179                        let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
2180                        let p = uv_of(psi, v);
2181                        Ok([p.x, p.y])
2182                    };
2183                    if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints(spans_u), &joints(spans_v), curve)? {
2184                        return Ok(fitted);
2185                    }
2186                }
2187                frag(fit_pcurve(&uv, &ts), "ring_pcurve")
2188            };
2189            let branch_pcurve = |b: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> { inverse_pcurve(&curves[branch_curve[&(half, b)]].curve) };
2190            let lower_edge = branch_curve[&(half, lo_branch)];
2191            let upper_edge = branch_curve[&(half, hi_branch)];
2192            let right = seam_arc[&(seam_of_end(half, true), band)];
2193            let left = seam_arc[&(seam_of_end(half, false), band)];
2194            let coedges = vec![
2195                (lower_edge, true, branch_pcurve(lo_branch, 0.0)?),
2196                (right, true, inverse_pcurve(&curves[right].curve)?),
2197                (upper_edge, false, frag(branch_pcurve(hi_branch, hi_turn)?.reversed(), "reversed")?),
2198                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
2199            ];
2200            let mid = &samples[half][n / 2];
2201            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
2202            caps.push(Cap { surface, front, coedges, chart: Some(Chart::Revolution { origin, w, u1, u2, alpha: psi_a, theta: psi_b - psi_a, spans_u, meridian: MeridianChart::Arc { centre: [rho_c, z_c], start: v_low, sweep: theta_v, spans: spans_v } }) });
2203        }
2204    }
2205    Ok(Split {
2206        points,
2207        curves,
2208        caps,
2209        slides: Vec::new(),
2210        slide_sides: Vec::new(),
2211        scale: rho_c + radius,
2212        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
2213    })
2214}
2215
2216/// Builder of a closed shell with shared vertices and edges.
2217struct Shell {
2218    vertices: Vec<VertexRecord>,
2219    edges: Vec<EdgeRecord>,
2220    faces: Vec<FaceRecord>,
2221    next: u64,
2222    /// Loops beyond each face's first (holes).
2223    holes: usize,
2224}
2225
2226impl Shell {
2227    fn new() -> Self {
2228        Self { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 1, holes: 0 }
2229    }
2230
2231    fn id(&mut self) -> u64 {
2232        self.next += 1;
2233        self.next
2234    }
2235
2236    fn vertex(&mut self, point: Vec3) -> u64 {
2237        let id = self.id();
2238        self.vertices.push(VertexRecord { id, point });
2239        id
2240    }
2241
2242    fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64, degenerate: bool) -> Result<u64, KernelRefusal> {
2243        let domain = frag(curve.domain(), "edge_domain")?;
2244        let id = self.id();
2245        self.edges.push(EdgeRecord { id, curve, t0: domain[0], t1: domain[1], start_vertex_id: start, end_vertex_id: end, degenerate, name: None });
2246        Ok(id)
2247    }
2248
2249    /// A face from its surface and its loop: (edge, traversed forward?, pcurve
2250    /// in the traversal direction).
2251    fn face(&mut self, surface: NurbsSurface, coedges: Vec<(u64, bool, NurbsCurve)>) -> u64 {
2252        let mut records = Vec::with_capacity(coedges.len());
2253        for (edge, forward, pcurve) in coedges {
2254            let id = self.id();
2255            records.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2256        }
2257        let loop_id = self.id();
2258        let id = self.id();
2259        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: vec![LoopRecord { id: loop_id, coedges: records }], name: None });
2260        id
2261    }
2262
2263    /// A face from its surface and its loops, the outer one first.
2264    fn face_loops(&mut self, surface: NurbsSurface, loops: Vec<Vec<(u64, bool, NurbsCurve)>>) -> u64 {
2265        let mut records = Vec::with_capacity(loops.len());
2266        for coedges in loops {
2267            let mut list = Vec::with_capacity(coedges.len());
2268            for (edge, forward, pcurve) in coedges {
2269                let id = self.id();
2270                list.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2271            }
2272            let id = self.id();
2273            records.push(LoopRecord { id, coedges: list });
2274        }
2275        self.holes += records.len().saturating_sub(1);
2276        let id = self.id();
2277        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: records, name: None });
2278        id
2279    }
2280
2281    fn solid(mut self) -> BrepSolid {
2282        let shell = self.id();
2283        let id = self.id();
2284        // One shell: V − E + F = 2 − 2g (every face one loop; a pole's
2285        // degenerate edge is not counted, as the validator counts).
2286        let edges = self.edges.iter().filter(|e| !e.degenerate).count() as i64;
2287        // A face with holes counts once for each loop beyond its first less.
2288        let euler = self.vertices.len() as i64 - edges + self.faces.len() as i64 - self.holes as i64;
2289        let genus = (2 - euler) / 2;
2290        BrepSolid {
2291            mass_properties_cache: Default::default(),
2292            id,
2293            vertices: self.vertices,
2294            edges: self.edges,
2295            shells: vec![ShellRecord { id: shell, faces: self.faces }],
2296            genus,
2297            kind: Default::default(),
2298            cells: Default::default(),
2299        }
2300    }
2301}
2302
2303/// The whole sweep of `tool` along `motion` (a single screw, turn or slide),
2304/// its two end positions included.
2305pub fn sweep_solid(tool: &SolidTool, motion: &SolidMotion) -> Result<BrepSolid, KernelRefusal> {
2306    sweep_with(&Screw::from_motion(motion)?, tool)
2307}
2308
2309fn sweep_with(screw: &Screw, tool: &SolidTool) -> Result<BrepSolid, KernelRefusal> {
2310    let screw = *screw;
2311    if let SolidTool::Revolved { meridian, .. } = tool {
2312        refuse_elliptic(meridian)?;
2313    }
2314    if let SolidTool::Revolved { axis_origin, axis_direction, meridian, radial } = tool {
2315        if let Some(body) = ball_across_axis(&screw, *axis_origin, *axis_direction, *radial, meridian)? {
2316            return Ok(body);
2317        }
2318        // (A tool whose radial direction lies along its axis is left to the
2319        // refusal below.)
2320        let radial_holds = match (tool, axis_direction.normalized()) {
2321            (SolidTool::Revolved { radial, .. }, Ok(w)) => radial.sub(w.scale(radial.dot(w))).normalized().is_ok(),
2322            _ => false,
2323        };
2324        if radial_holds && ball_screw::ball_screw_on() {
2325            if let Some(body) = ball_screw::ball_screwed_past_fold(&screw, *axis_origin, *axis_direction, meridian)? {
2326                return Ok(body);
2327            }
2328        }
2329    }
2330    if let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool {
2331        if ring_fold::ring_fold_on() {
2332            if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() {
2333                if ((end - start).abs() - TAU).abs() < 1e-12 {
2334                    let w = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
2335                    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
2336                    if let Some(body) = ring_fold::ring_slid_past_fold(&screw, *axis_origin, w, u1, w.cross(u1), *centre, *radius)? {
2337                        return Ok(body);
2338                    }
2339                }
2340            }
2341        }
2342        if let Some(body) = flat_ring(&screw, *axis_origin, *axis_direction, *radial, meridian)? {
2343            return Ok(body);
2344        }
2345        if let Some(body) = rod_across_axis(&screw, *axis_origin, *axis_direction, meridian)? {
2346            return Ok(body);
2347        }
2348    }
2349    if let SolidTool::Polyhedron { vertices, faces } = tool {
2350        let slid = screw.omega == 0.0 && screw.c2 == 0.0 && screw.frame.is_none() && screw.turns.is_none();
2351        if slid && slid_hull_on() {
2352            return slid_polyhedron_hull(&screw, vertices, faces);
2353        }
2354    }
2355    if let SolidTool::Polyhedron { vertices, faces } = tool {
2356        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);
2357        if whole {
2358            return whole_turn_shadow(&screw, vertices, faces);
2359        }
2360    }
2361    let split = match tool {
2362        SolidTool::Polyhedron { vertices, faces } => split_polyhedron(&screw, vertices, faces)?,
2363        SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } => {
2364            split_revolved(&screw, *axis_origin, *axis_direction, *radial, meridian)?
2365        }
2366    };
2367    let grazing = split.grazing()?;
2368    // A tool slid along its own axis has no grazing curve: its sliding sides
2369    // join its back at the start to its front at the end.
2370    if grazing.is_empty() && split.slide_sides.is_empty() {
2371        return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
2372    }
2373    let times = row_times(&screw);
2374    let last = times.len() - 1;
2375    let mut shell = Shell::new();
2376    // Vertices and edges at the row times (0 and `last` are the end positions),
2377    // made on demand.
2378    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
2379    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
2380    let mut at_time = |shell: &mut Shell, j: usize, p: usize| -> u64 {
2381        *vertex_at.entry((j, p)).or_insert_with(|| shell.vertex(screw.apply(times[j], split.points[p])))
2382    };
2383    let mut time_edge = |shell: &mut Shell, j: usize, c: usize, vertex: &mut dyn FnMut(&mut Shell, usize, usize) -> u64| -> Result<u64, KernelRefusal> {
2384        if let Some(&edge) = edge_at.get(&(j, c)) {
2385            return Ok(edge);
2386        }
2387        let curve = &split.curves[c];
2388        let (a, b) = (vertex(shell, j, curve.start), vertex(shell, j, curve.end));
2389        let edge = shell.edge(screw.move_curve(times[j], &curve.curve)?, a, b, curve.degenerate)?;
2390        edge_at.insert((j, c), edge);
2391        Ok(edge)
2392    };
2393    // Caps: the back at t0, the front at t1.
2394    for cap in &split.caps {
2395        let j = if cap.front { last } else { 0 };
2396        let surface = screw.move_surface(times[j], &cap.surface)?;
2397        let mut coedges = Vec::with_capacity(cap.coedges.len());
2398        for (c, forward, pcurve) in &cap.coedges {
2399            let edge = time_edge(&mut shell, j, *c, &mut at_time)?;
2400            coedges.push((edge, *forward, pcurve.clone()));
2401        }
2402        shell.face(surface, coedges);
2403    }
2404    // Walls, a row at a time. The back cap at t0 runs K's curve with the back
2405    // on its left, so the wall beside it runs the other way: u along the curve
2406    // that way, v from the row's start to its end, the loop (u0,0) (u1,0)
2407    // (u1,1) (u0,1).
2408    // The paths of K's corners, a row at a time: (row, point) -> edge.
2409    let mut orbit_at: HashMap<(usize, usize), u64> = HashMap::new();
2410    for row in 0..last {
2411        let (ta, tb) = (times[row], times[row + 1]);
2412        let segments = carry_segments(&screw, ta, tb);
2413        let knots_v = carry_knots(segments);
2414        let mut orbits: HashMap<usize, u64> = HashMap::new();
2415        for &(c, _) in &grazing {
2416            for r in [split.curves[c].start, split.curves[c].end] {
2417                if orbits.contains_key(&r) {
2418                    continue;
2419                }
2420                let (v0, v1) = (at_time(&mut shell, row, r), at_time(&mut shell, row + 1, r));
2421                let edge = shell.edge(carry_curve(&screw, split.points[r], ta, tb, segments)?, v0, v1, false)?;
2422                orbits.insert(r, edge);
2423                orbit_at.insert((row, r), edge);
2424            }
2425        }
2426        for &(c, back_forward) in &grazing {
2427            let tool_curve = &split.curves[c];
2428            let along = if back_forward { frag(tool_curve.curve.reversed(), "reversed")? } else { tool_curve.curve.clone() };
2429            let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
2430            let mut rows = Vec::with_capacity(along.control_points.len());
2431            for p in &along.control_points {
2432                let x = frag(p.point(), "control_point")?;
2433                rows.push(carry_points(&screw, x, ta, tb, segments).into_iter().map(|q| Vec4::from_point(q, p.w)).collect::<Vec<_>>());
2434            }
2435            let surface = frag(NurbsSurface::new(along.degree, 5, along.knots.clone(), knots_v.clone(), rows), "wall")?;
2436            let [u0, u1] = frag(along.domain(), "domain")?;
2437            let bottom = time_edge(&mut shell, row, c, &mut at_time)?;
2438            let top = time_edge(&mut shell, row + 1, c, &mut at_time)?;
2439            let coedges = vec![
2440                (bottom, !back_forward, uv_line([u0, 0.0], [u1, 0.0])?),
2441                (orbits[&to], true, uv_line([u1, 0.0], [u1, 1.0])?),
2442                (top, back_forward, uv_line([u1, 1.0], [u0, 1.0])?),
2443                (orbits[&from], false, uv_line([u0, 1.0], [u0, 0.0])?),
2444            ];
2445            shell.face(surface, coedges);
2446        }
2447    }
2448    // Sliding ends: each rim arc where its neighbour's cap sits (back at t0,
2449    // front at t1), joined by the paths of the points where that changes.
2450    // Faces the tool slides within: the one-pass probe stands further off them.
2451    let mut sliding: std::collections::HashSet<u64> = std::collections::HashSet::new();
2452    let side_of: HashMap<usize, bool> = split.caps.iter().flat_map(|cap| cap.coedges.iter().map(move |&(c, _, _)| (c, cap.front))).collect();
2453    for slide in &split.slides {
2454        let centre = screw.apply(times[0], slide.centre);
2455        let u = screw.apply(times[0], slide.centre.add(slide.u)).sub(centre);
2456        let v = screw.apply(times[0], slide.centre.add(slide.v)).sub(centre);
2457        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2458            match side_of.get(&c) {
2459                Some(true) => Ok(last),
2460                Some(false) => Ok(0),
2461                None => Err(refuse("revolved_grazing", "a sliding end has no face beside its rim".into())),
2462            }
2463        };
2464        let mut coedges = Vec::new();
2465        let mut corners: Vec<Vec3> = Vec::new();
2466        let push = |coedges: &mut Vec<(u64, bool, NurbsCurve)>, corners: &mut Vec<Vec3>, edge: u64, forward: bool, curve: &NurbsCurve| -> Result<(), KernelRefusal> {
2467            let [d0, d1] = frag(curve.domain(), "domain")?;
2468            for k in 0..=8 {
2469                corners.push(frag(curve.evaluate(d0 + (d1 - d0) * k as f64 / 8.0), "slide")?);
2470            }
2471            coedges.push((edge, forward, plane_pcurve(centre, u, v, curve, forward)?));
2472            Ok(())
2473        };
2474        for (index, &(c, forward)) in slide.rim.iter().enumerate() {
2475            let j = row_of(c)?;
2476            let edge = time_edge(&mut shell, j, c, &mut at_time)?;
2477            push(&mut coedges, &mut corners, edge, forward, &screw.move_curve(times[j], &split.curves[c].curve)?)?;
2478            // On to the next arc's time along the path of the point between them.
2479            let (next, _) = slide.rim[(index + 1) % slide.rim.len()];
2480            let next_j = row_of(next)?;
2481            if next_j == j {
2482                continue;
2483            }
2484            let point = if forward { split.curves[c].end } else { split.curves[c].start };
2485            let rows: Vec<usize> = if next_j > j { (j..next_j).collect() } else { (next_j..j).rev().collect() };
2486            for row in rows {
2487                let Some(&orbit) = orbit_at.get(&(row, point)) else {
2488                    return Err(refuse("revolved_grazing", "a sliding end's rim changes side where no grazing curve meets it".into()));
2489                };
2490                let (ta, tb) = (times[row], times[row + 1]);
2491                let curve = carry_curve(&screw, split.points[point], ta, tb, carry_segments(&screw, ta, tb))?;
2492                push(&mut coedges, &mut corners, orbit, next_j > j, &curve)?;
2493            }
2494        }
2495        sliding.insert(shell.face(plane_patch(centre, u, v, &corners)?, coedges));
2496    }
2497    // Sliding cylinders: from the start rim where its neighbour sits to the
2498    // end rim where its neighbour sits, in halves seamed along generators.
2499    for side in &split.slide_sides {
2500        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2501            match side_of.get(&c) {
2502                Some(true) => Ok(last),
2503                Some(false) => Ok(0),
2504                None => Err(refuse("revolved_grazing", "a sliding side has no face beside its rim".into())),
2505            }
2506        };
2507        let origin = screw.apply(times[0], side.origin);
2508        let w = screw.apply(times[0], side.origin.add(side.w)).sub(origin);
2509        let rows: Vec<[usize; 2]> = side.patches.iter().map(|patch| Ok([row_of(patch.2)?, row_of(patch.3)?])).collect::<Result<_, KernelRefusal>>()?;
2510        if rows.iter().any(|r| *r != rows[0]) {
2511            return Err(refuse("revolved_grazing", "a sliding side's rim changes side along it".into()));
2512        }
2513        let [jb, ja] = rows[0];
2514        // Seams: the generator at each patch's start angle, rim point to rim point.
2515        let mut seams = Vec::with_capacity(side.patches.len());
2516        for patch in &side.patches {
2517            let (a, b) = (at_time(&mut shell, jb, patch.4[0]), at_time(&mut shell, ja, patch.4[1]));
2518            let line = frag(make_line(screw.apply(times[jb], split.points[patch.4[0]]), screw.apply(times[ja], split.points[patch.4[1]])), "seam")?;
2519            seams.push((shell.edge(line.clone(), a, b, false)?, line));
2520        }
2521        for (k, patch) in side.patches.iter().enumerate() {
2522            let surface = frag(make_revolution(origin, w, &seams[k].1, patch.1), "slide_side")?;
2523            let lower = time_edge(&mut shell, jb, patch.2, &mut at_time)?;
2524            let upper = time_edge(&mut shell, ja, patch.3, &mut at_time)?;
2525            let next = (k + 1) % side.patches.len();
2526            let face = shell.face(
2527                surface,
2528                vec![
2529                    (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
2530                    (seams[next].0, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
2531                    (upper, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
2532                    (seams[k].0, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
2533                ],
2534            );
2535            sliding.insert(face);
2536        }
2537    }
2538    let body = shell.solid();
2539    let issues = body.validate();
2540    if !issues.is_empty() {
2541        return Err(refuse("assembly", format!("the assembled sweep is not valid: {:?}", issues.first())));
2542    }
2543    // A ball under one screw is proved one pass from its centre's helix
2544    // (`BREP_SWEEP_BALL_ONE_PASS`, default on): nothing for the walk to find.
2545    if !crate::solid_sweep_one_pass::ball_screw_one_pass(&screw, tool) {
2546        check_single_pass(&screw, &split, &body, &sliding)?;
2547    }
2548    Ok(body)
2549}
2550
2551/// A rod (a cylinder with flat ends) TURNED about a line that crosses its
2552/// axis squarely between its ends, if `meridian` is one and the motion such.
2553///
2554/// Arm by arm: the rod is its arm one way from the turn's axis and its arm
2555/// the other way, and sweeps what they sweep. At a height z (half-width
2556/// w = √(r² − z²)) an arm of length L is the rectangle 0 ≤ x ≤ L, |y| ≤ w,
2557/// which a circle about the turn's axis of radius ρ ≤ L meets in one arc
2558/// holding the arm's own direction, and beyond, out to √(L² + w²), in two
2559/// arcs ±[a, b] with a ≤ acos(L / √(L² + r²)). Turned by more than 2a, the
2560/// two arcs sweep the same angles as the arc [−b, b] they leave a gap in:
2561/// the arm with the gap filled, its points beyond its end within
2562/// √(L² + r²) of the crossing point (a cap of that ball). The filled arm
2563/// meets every circle in one arc holding its direction, so it sweeps itself
2564/// where it starts and where it stops and, between, its section by the half
2565/// plane at its direction turned. So the sweep is the union of the filled rod
2566/// (one solid of revolution about the rod's axis) at both ends of the turn
2567/// and the two arms' sections turned.
2568fn rod_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2569    if screw.frame.is_some() || screw.turns.is_some() || screw.omega == 0.0 || screw.c != 0.0 || screw.c2 != 0.0 {
2570        return Ok(None);
2571    }
2572    let Ok(w) = axis.normalized() else { return Ok(None) };
2573    // A rectangle against the axis: radius r from z0 to z1.
2574    let mut corners: Vec<[f64; 2]> = Vec::new();
2575    for piece in meridian {
2576        let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
2577        corners.push(*from);
2578        corners.push(*to);
2579    }
2580    if meridian.len() != 4 {
2581        return Ok(None);
2582    }
2583    let r = corners.iter().map(|c| c[0]).fold(0.0f64, f64::max);
2584    let (z0, z1) = corners.iter().map(|c| c[1]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), z| (lo.min(z), hi.max(z)));
2585    let scale = r.max(z0.abs()).max(z1.abs());
2586    let on = |a: f64, b: f64| (a - b).abs() <= 1e-12 * scale;
2587    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))) {
2588        return Ok(None);
2589    }
2590    // The turn's axis squarely across the rod's, between its ends.
2591    if w.dot(screw.e).abs() > 1e-12 {
2592        return Ok(None);
2593    }
2594    let offset = screw.a.sub(origin);
2595    let along = offset.dot(w);
2596    let foot = origin.add(w.scale(along));
2597    let apart = screw.a.sub(foot);
2598    if apart.sub(screw.e.scale(apart.dot(screw.e))).length() > 1e-12 * (scale + offset.length()) {
2599        return Ok(None);
2600    }
2601    if !(along > z0 + 1e-9 * scale && along < z1 - 1e-9 * scale) {
2602        return Ok(None);
2603    }
2604    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
2605    let arms = [z1 - along, along - z0];
2606    let gap = arms.iter().map(|l| (l / l.hypot(r)).acos()).fold(0.0f64, f64::max);
2607    if !(theta > 2.0 * gap * (1.0 + 1e-9) && theta < TAU * (1.0 - 1e-9)) {
2608        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()));
2609    }
2610    let arc = |centre: Vec3, from: Vec3, normal: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
2611        let surface = frag(make_revolution(centre, normal, &frag(make_line(from, from.add(normal)), "line")?, angle), "rod_across")?;
2612        frag(surface.iso_curve_v(0.0), "rod_across")
2613    };
2614    let line = |a: Vec3, b: Vec3| frag(make_line(a, b), "rod_across");
2615    // At one time: the crossing point, the rod's direction and the turn's.
2616    let filled_at = |t: f64| -> Result<BrepSolid, KernelRefusal> {
2617        let o = screw.apply(t, foot);
2618        let x = screw.apply(t, foot.add(w)).sub(o);
2619        let up = screw.e;
2620        let at = |rho: f64, s: f64| o.add(up.scale(rho)).add(x.scale(s));
2621        let n = up.cross(x);
2622        let (far_plus, far_minus) = (arms[0].hypot(r), arms[1].hypot(r));
2623        let profile = [
2624            arc(o, at(0.0, -far_minus), n, r.atan2(arms[1]))?,
2625            line(at(r, -arms[1]), at(r, arms[0]))?,
2626            arc(o, at(r, arms[0]), n, r.atan2(arms[0]))?,
2627            line(at(0.0, far_plus), at(0.0, -far_minus))?,
2628        ];
2629        frag(crate::revolve_profile_brep(&profile, o, x, TAU), "rod_across")
2630    };
2631    let o = screw.apply(screw.t0, foot);
2632    let x = screw.apply(screw.t0, foot.add(w)).sub(o);
2633    let turn_axis = screw.e.scale(screw.omega.signum());
2634    let section = |direction: Vec3, length: f64| -> Result<BrepSolid, KernelRefusal> {
2635        let at = |rho: f64, z: f64| o.add(direction.scale(rho)).add(screw.e.scale(z));
2636        let half = (r / length.hypot(r)).asin();
2637        let profile = [
2638            line(at(0.0, -r), at(length, -r))?,
2639            arc(o, at(length, -r), direction.cross(screw.e), 2.0 * half)?,
2640            line(at(length, r), at(0.0, r))?,
2641            line(at(0.0, r), at(0.0, -r))?,
2642        ];
2643        frag(crate::revolve_profile_brep(&profile, o, turn_axis, theta), "rod_across")
2644    };
2645    let parts = [filled_at(screw.t0)?, filled_at(screw.t1)?, section(x, arms[0])?, section(x.scale(-1.0), arms[1])?];
2646    crate::boolean_operation_nary(&parts, crate::BooleanOperation::Union).map(Some)
2647}
2648
2649/// `BREP_SWEEP_RING_LENS_SEWN` (on by default; `=0` restores the booleans): a
2650/// ring slid flat short of its
2651/// hole's width is the filled ring's sweep less the lens its hole leaves open
2652/// at both ends. That lens is built here and sewn into the sweep's top and
2653/// bottom faces in place of the two booleans (the lens intersect and the
2654/// subtract): its caps are the two holes' top and bottom discs in common,
2655/// whose outlines become inner loops of the sweep's flat faces, and its walls
2656/// are the two holes' own tube surfaces, meeting in the slide's bisector
2657/// plane along `y(ψ) = √(ρ(ψ)² − D²/4)`, `ρ = R − r cos ψ`, `z = r sin ψ`
2658/// (the tube's section by that plane, interpolated through exact points and
2659/// read back against them). A lens that pinches at the tube's middle (`D ≥
2660/// 2 (R − r)`) or anything that does not validate is left to the booleans.
2661pub(crate) fn ring_lens_sewn_on() -> bool {
2662    crate::switch!("BREP_SWEEP_RING_LENS_SEWN", true)
2663}
2664
2665/// `BREP_SWEEP_RING_LENS_SEWN_CHECK` (default off): both built, the booleans'
2666/// body kept; the sewn one's volume and area compared with it
2667/// ([`ring_lens_check_take`]).
2668fn ring_lens_sewn_check_on() -> bool {
2669    crate::switch!("BREP_SWEEP_RING_LENS_SEWN_CHECK", false)
2670}
2671
2672thread_local! {
2673    static RING_LENS_CHECK: std::cell::Cell<(u64, u64, f64)> = const { std::cell::Cell::new((0, 0, 0.0)) };
2674}
2675
2676/// (bodies compared, sewn bodies missing or differing past `1e-7` relative
2677/// in volume or area, the worst relative difference) on this thread since the
2678/// last call. The bar is the booleans' own error, the bench's tier: the sewn
2679/// body reads the closed form to `1e-10` where the booleans' body reads it
2680/// `2.9e-9` off (tube 2 round 6, slid 6) and `3.8e-8` off (tube 1 round 5,
2681/// slid 3).
2682pub fn ring_lens_check_take() -> (u64, u64, f64) {
2683    RING_LENS_CHECK.with(|cell| cell.replace((0, 0, 0.0)))
2684}
2685
2686fn ring_lens_check_record(cut: &BrepSolid, sewn: Option<&BrepSolid>) {
2687    let worst = match (crate::solid_mass_properties(cut), sewn.map(crate::solid_mass_properties)) {
2688        (Ok(a), Some(Ok(b))) => ((a.volume - b.volume) / a.volume).abs().max(((a.surface_area - b.surface_area) / a.surface_area).abs()),
2689        _ => f64::INFINITY,
2690    };
2691    RING_LENS_CHECK.with(|cell| {
2692        let (n, bad, w) = cell.get();
2693        cell.set((n + 1, bad + u64::from(!(worst <= 1e-7)), w.max(worst)));
2694    });
2695}
2696
2697/// The filled ring's sweep `whole` (a slide of the ring's centre from `c0` to
2698/// `c1`, square to its axis `w`, its tube `tube` round the circle of radius
2699/// `big`) less the lens both holes share, built directly. `None` where it
2700/// does not apply or does not validate.
2701fn sewn_lens(whole: &BrepSolid, c0: Vec3, c1: Vec3, w: Vec3, big: f64, tube: f64) -> Option<BrepSolid> {
2702    let slide = c1.sub(c0);
2703    let d = slide.length();
2704    let scale = (big + tube + d).max(1e-300);
2705    if !(slide.dot(w).abs() <= 1e-12 * scale && d > 1e-9 * scale && d < 2.0 * (big - tube) * (1.0 - 1e-9)) {
2706        return None;
2707    }
2708    let ed = slide.scale(1.0 / d);
2709    let ey = w.cross(ed);
2710    let mid = c0.add(ed.scale(0.5 * d));
2711    let half = 0.5 * d;
2712    let alpha = (half / big).acos();
2713    let y_top = (big * big - half * half).sqrt();
2714    let corner = |side: f64, z: f64| mid.add(ey.scale(side * y_top)).add(w.scale(z));
2715    let (t_plus, t_minus, b_plus, b_minus) = (corner(1.0, tube), corner(-1.0, tube), corner(1.0, -tube), corner(-1.0, -tube));
2716    // The flat faces the caps sit in.
2717    let shell = whole.shells.first()?;
2718    let flat_at = |z: f64| -> Option<usize> {
2719        shell.faces.iter().position(|f| {
2720            f.loops.len() == 1
2721                && f.surface.degree_u == 1
2722                && f.surface.degree_v == 1
2723                && f.surface.control_points.iter().flatten().all(|c| c.point().map(|p| (p.sub(c0).dot(w) - z).abs() <= 1e-12 * scale).unwrap_or(false))
2724        })
2725    };
2726    let (top, bottom) = (flat_at(tube)?, flat_at(-tube)?);
2727    // Edges. Arcs: A on the circle about c0 (the lens's side away from c0's
2728    // far rim: angles −α..α from ed), B about c1 (π−α..π+α).
2729    let arc = |centre: Vec3, from: f64, to: f64| crate::make_arc(centre, ed, ey, big, from, to).ok();
2730    let a_top = arc(c0.add(w.scale(tube)), -alpha, alpha)?; // t_minus -> t_plus
2731    let b_top = arc(c1.add(w.scale(tube)), PI - alpha, PI + alpha)?; // t_plus -> t_minus
2732    let a_bot = arc(c0.add(w.scale(-tube)), -alpha, alpha)?; // b_minus -> b_plus
2733    let b_bot = arc(c1.add(w.scale(-tube)), PI - alpha, PI + alpha)?; // b_plus -> b_minus
2734    // The walls' carriers: each hole's inner tube half turned a whole turn
2735    // about its axis, its generatrix drawn opposite the lens (the turn's seam
2736    // away from the wall).
2737    let wall_surface = |centre: Vec3, away: Vec3| -> Option<NurbsSurface> {
2738        let n = w.cross(away);
2739        let at = |rho: f64, z: f64| centre.add(away.scale(rho)).add(w.scale(z));
2740        let from = at(big, -tube);
2741        let half_round = crate::make_revolution(at(big, 0.0), n, &crate::make_line(from, from.add(n)).ok()?, PI).ok()?.iso_curve_v(0.0).ok()?;
2742        crate::make_revolution(centre, w, &half_round, TAU).ok()
2743    };
2744    let (wall_a, wall_b) = (wall_surface(c0, ed.scale(-1.0))?, wall_surface(c1, ed)?);
2745    // Seams, bottom to top, through exact points of the bisector section, with
2746    // their pcurves on both walls interpolated through the same points' feet
2747    // at the same parameters; all three read back at the mid-samples.
2748    // (Each seam in two halves, split at the tube's waist ψ = 0: the walls'
2749    // half-round generatrix is two quarter arcs, its parameter speed jumps
2750    // there, and a pcurve through it would kink.)
2751    let seam = |side: f64, from: f64, to: f64| -> Option<(NurbsCurve, NurbsCurve, NurbsCurve)> {
2752        let at = |psi: f64| {
2753            let rho = big - tube * psi.cos();
2754            mid.add(ey.scale(side * (rho * rho - half * half).max(0.0).sqrt())).add(w.scale(tube * psi.sin()))
2755        };
2756        let feet = |surface: &NurbsSurface, points: &[Vec3]| -> Option<Vec<Vec3>> {
2757            let mut out: Vec<Vec3> = Vec::with_capacity(points.len());
2758            for point in points {
2759                // From the last foot; where that lands off the point (the tube
2760                // turning fast near its top and bottom), the global reading.
2761                let seeded = out.last().and_then(|last| crate::project_point_to_surface_seeded(surface, *point, last.x, last.y).ok());
2762                let q = match seeded {
2763                    Some(q) if q.distance <= 1e-7 * scale => q,
2764                    _ => crate::project_point_to_surface(surface, *point).ok()?,
2765                };
2766                // The projector stops near 1e-9; the point is on the carrier
2767                // exactly, so Gauss-Newton on |S(u, v) − p|² takes the foot to
2768                // rounding.
2769                let (mut u, mut v) = (q.u, q.v);
2770                for _ in 0..4 {
2771                    let d = surface.derivatives(u, v, 1).ok()?;
2772                    let (f, su, sv) = (d[0][0].sub(*point), d[1][0], d[0][1]);
2773                    let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv));
2774                    let (g0, g1) = (su.dot(f), sv.dot(f));
2775                    let det = a * c - b * b;
2776                    if !(det > 0.0) {
2777                        return None;
2778                    }
2779                    u -= (c * g0 - b * g1) / det;
2780                    v -= (a * g1 - b * g0) / det;
2781                }
2782                if !(surface.evaluate(u, v).ok()?.sub(*point).length() <= 1e-11 * scale) {
2783                    return None;
2784                }
2785                out.push(Vec3::new(u, v, 0.0));
2786            }
2787            Some(out)
2788        };
2789        let mut n = 16usize;
2790        loop {
2791            let psis: Vec<f64> = (0..=n).map(|k| from + (to - from) * k as f64 / n as f64).collect();
2792            let points: Vec<Vec3> = psis.iter().map(|&psi| at(psi)).collect();
2793            let params: Vec<f64> = psis.iter().map(|psi| (psi - from) / (to - from)).collect();
2794            let curve = crate::interpolate_curve(&points, 3, &params).ok()?;
2795            let on_a = crate::interpolate_curve(&feet(&wall_a, &points)?, 3, &params).ok()?;
2796            let on_b = crate::interpolate_curve(&feet(&wall_b, &points)?, 3, &params).ok()?;
2797            let mut worst = 0.0f64;
2798            for k in 0..n {
2799                let psi = 0.5 * (psis[k] + psis[k + 1]);
2800                let t = (psi - from) / (to - from);
2801                let p = curve.evaluate(t).ok()?;
2802                worst = worst.max(p.sub(at(psi)).length());
2803                for (surface, pcurve) in [(&wall_a, &on_a), (&wall_b, &on_b)] {
2804                    let uv = pcurve.evaluate(t).ok()?;
2805                    worst = worst.max(surface.evaluate(uv.x, uv.y).ok()?.sub(p).length());
2806                }
2807            }
2808            if worst <= 1e-10 * scale {
2809                return Some((curve, on_a, on_b));
2810            }
2811            if n >= 4096 {
2812                return None;
2813            }
2814            n *= 2;
2815        }
2816    };
2817    let (lower_plus, upper_plus) = (seam(1.0, -0.5 * PI, 0.0)?, seam(1.0, 0.0, 0.5 * PI)?);
2818    let (lower_minus, upper_minus) = (seam(-1.0, -0.5 * PI, 0.0)?, seam(-1.0, 0.0, 0.5 * PI)?);
2819    let waist = |side: f64| mid.add(ey.scale(side * ((big - tube).powi(2) - half * half).sqrt()));
2820    let (m_plus, m_minus) = (waist(1.0), waist(-1.0));
2821    // Ids past every existing one.
2822    let mut next = whole.vertices.iter().map(|v| v.id).chain(whole.edges.iter().map(|e| e.id)).chain(shell.faces.iter().flat_map(|f| std::iter::once(f.id).chain(f.loops.iter().flat_map(|l| std::iter::once(l.id).chain(l.coedges.iter().map(|c| c.id)))))).max().unwrap_or(0) + 1;
2823    let mut id = || {
2824        next += 1;
2825        next
2826    };
2827    let mut body = whole.clone();
2828    let vertex = |body: &mut BrepSolid, id: u64, point: Vec3| body.vertices.push(VertexRecord { id, point });
2829    let (vt_plus, vt_minus, vb_plus, vb_minus, vm_plus, vm_minus) = (id(), id(), id(), id(), id(), id());
2830    vertex(&mut body, vm_plus, m_plus);
2831    vertex(&mut body, vm_minus, m_minus);
2832    vertex(&mut body, vt_plus, t_plus);
2833    vertex(&mut body, vt_minus, t_minus);
2834    vertex(&mut body, vb_plus, b_plus);
2835    vertex(&mut body, vb_minus, b_minus);
2836    let mut edge = |body: &mut BrepSolid, curve: NurbsCurve, start: u64, end: u64| -> Option<u64> {
2837        let [t0, t1] = curve.domain().ok()?;
2838        let e = id();
2839        body.edges.push(EdgeRecord { id: e, curve, t0, t1, start_vertex_id: start, end_vertex_id: end, degenerate: false, name: None });
2840        Some(e)
2841    };
2842    // The arcs' ends must be the corners they are named for.
2843    for (curve, a, b) in [(&a_top, t_minus, t_plus), (&b_top, t_plus, t_minus), (&a_bot, b_minus, b_plus), (&b_bot, b_plus, b_minus), (&lower_plus.0, b_plus, m_plus), (&upper_plus.0, m_plus, t_plus), (&lower_minus.0, b_minus, m_minus), (&upper_minus.0, m_minus, t_minus)] {
2844        let [t0, t1] = curve.domain().ok()?;
2845        if curve.evaluate(t0).ok()?.sub(a).length() > 1e-9 * scale || curve.evaluate(t1).ok()?.sub(b).length() > 1e-9 * scale {
2846            return None;
2847        }
2848    }
2849    // The seams' pcurves, built with them: (edge, wall, pcurve along the edge).
2850    let mut given: Vec<(u64, usize, NurbsCurve)> = Vec::new();
2851    let e_a_top = edge(&mut body, a_top, vt_minus, vt_plus)?;
2852    let e_b_top = edge(&mut body, b_top, vt_plus, vt_minus)?;
2853    let e_a_bot = edge(&mut body, a_bot, vb_minus, vb_plus)?;
2854    let e_b_bot = edge(&mut body, b_bot, vb_plus, vb_minus)?;
2855    let mut seam_edge = |body: &mut BrepSolid, piece: (NurbsCurve, NurbsCurve, NurbsCurve), start: u64, end: u64, given: &mut Vec<(u64, usize, NurbsCurve)>| -> Option<u64> {
2856        let (curve, on_a, on_b) = piece;
2857        let e = edge(body, curve, start, end)?;
2858        given.extend([(e, 1, on_a), (e, 2, on_b)]);
2859        Some(e)
2860    };
2861    let e_lp = seam_edge(&mut body, lower_plus, vb_plus, vm_plus, &mut given)?;
2862    let e_up = seam_edge(&mut body, upper_plus, vm_plus, vt_plus, &mut given)?;
2863    let e_lm = seam_edge(&mut body, lower_minus, vb_minus, vm_minus, &mut given)?;
2864    let e_um = seam_edge(&mut body, upper_minus, vm_minus, vt_minus, &mut given)?;
2865    let curve_of = |body: &BrepSolid, e: u64| body.edges.iter().find(|x| x.id == e).map(|x| x.curve.clone());
2866    // A coedge of edge `e` on `surface`, forward or reversed, with its pcurve
2867    // fitted along the coedge.
2868    let coedge = |body: &BrepSolid, id: u64, surface: &NurbsSurface, e: u64, forward: bool, given: &[(u64, usize, NurbsCurve)], wall: usize| -> Option<CoedgeRecord> {
2869        if let Some((_, _, pcurve)) = given.iter().find(|(edge, on, _)| *edge == e && *on == wall) {
2870            let pcurve = if forward { pcurve.clone() } else { pcurve.reversed().ok()? };
2871            return Some(CoedgeRecord { id, edge_id: e, forward, pcurve });
2872        }
2873        let fit = crate::fit_pcurve_on_surface(surface, &curve_of(body, e)?).ok()?;
2874        if !(fit.report.residual <= 1e-7 * scale) {
2875            return None;
2876        }
2877        let pcurve = if forward { fit.curve } else { fit.curve.reversed().ok()? };
2878        Some(CoedgeRecord { id, edge_id: e, forward, pcurve })
2879    };
2880    // The loop's signed area in its face's parameters.
2881    let uv_area = |coedges: &[CoedgeRecord]| -> f64 {
2882        let mut area = 0.0;
2883        for c in coedges {
2884            let Ok([p0, p1]) = c.pcurve.domain() else { return f64::NAN };
2885            let samples = 64;
2886            let mut last = match c.pcurve.evaluate(p0) { Ok(p) => p, Err(_) => return f64::NAN };
2887            for k in 1..=samples {
2888                let Ok(p) = c.pcurve.evaluate(p0 + (p1 - p0) * k as f64 / samples as f64) else { return f64::NAN };
2889                area += last.x * p.y - p.x * last.y;
2890                last = p;
2891            }
2892        }
2893        0.5 * area
2894    };
2895    // Caps: the top's hole runs clockwise seen from outside (from +w), the
2896    // bottom's clockwise seen from −w.
2897    for (face_index, loop_edges) in [(top, [(e_a_top, false), (e_b_top, false)]), (bottom, [(e_a_bot, true), (e_b_bot, true)])] {
2898        let surface = body.shells[0].faces[face_index].surface.clone();
2899        let mut coedges = Vec::new();
2900        for (e, forward) in loop_edges {
2901            let c = id();
2902            coedges.push(coedge(&body, c, &surface, e, forward, &given, 0)?);
2903        }
2904        // An inner loop runs opposite its face's outer loop in the parameters.
2905        let outer = uv_area(&body.shells[0].faces[face_index].loops[0].coedges);
2906        let inner = uv_area(&coedges);
2907        if !(outer.is_finite() && inner.is_finite() && outer * inner < 0.0) {
2908            return None;
2909        }
2910        let loop_id = id();
2911        body.shells[0].faces[face_index].loops.push(LoopRecord { id: loop_id, coedges });
2912    }
2913    // Walls: A uses the arcs the caps reversed and B likewise, the seams once each way.
2914    for (wall, surface, centre, loop_edges) in [
2915        (1usize, wall_a, c0, vec![(e_a_top, true), (e_up, false), (e_lp, false), (e_a_bot, false), (e_lm, true), (e_um, true)]),
2916        (2usize, wall_b, c1, vec![(e_b_top, true), (e_um, false), (e_lm, false), (e_b_bot, false), (e_lp, true), (e_up, true)]),
2917    ] {
2918        let mut coedges = Vec::new();
2919        for (e, forward) in loop_edges {
2920            let c = id();
2921            coedges.push(coedge(&body, c, &surface, e, forward, &given, wall)?);
2922        }
2923        let area = uv_area(&coedges);
2924        if !(area.is_finite() && area != 0.0) {
2925            return None;
2926        }
2927        // Counter-clockwise in the parameters: the loop's outward is the
2928        // surface's normal side; it must face into the lens (towards the
2929        // hole's own axis).
2930        let same_sense = area > 0.0;
2931        let face_id = id();
2932        let loop_id = id();
2933        let face = FaceRecord { id: face_id, surface, same_sense, loops: vec![LoopRecord { id: loop_id, coedges }], name: None };
2934        // Sense check at the wall's middle: towards the hole's axis.
2935        let middle = mid.add(ed.scale(if centre.sub(c0).length() == 0.0 { big - tube - half } else { -(big - tube - half) }));
2936        let q = crate::project_point_to_surface(&face.surface, middle).ok()?;
2937        let n = face.surface.normal(q.u, q.v).ok()?;
2938        let n = if face.same_sense { n } else { n.scale(-1.0) };
2939        let toward_axis = centre.sub(middle);
2940        let toward_axis = toward_axis.sub(w.scale(toward_axis.dot(w)));
2941        if !(n.dot(toward_axis) > 0.0) {
2942            return None;
2943        }
2944        body.shells[0].faces.push(face);
2945    }
2946    // The lens runs through from the top face to the bottom: one handle more.
2947    body.genus = whole.genus + 1;
2948    body.mass_properties_cache = Default::default();
2949    if body.validate().iter().any(|issue| issue.severity == "error") {
2950        return None;
2951    }
2952    Some(body)
2953}
2954
2955/// A ring (or another tool with a hole about its axis walled straight
2956/// through) lying flat to its motion (a turn about an axis parallel to the
2957/// tool's, a slide square to it), if `meridian` is one and the motion such.
2958///
2959/// Every point then moves in its own plane square to the ring's axis, where
2960/// the ring's section is an annulus. The tube passes over where the hole was,
2961/// so the sweep does not pass each point once; but an annulus sweeps what its
2962/// filled disc sweeps as soon as it travels far enough that no point stays in
2963/// the hole from start to end (the hole at the start and at the end share
2964/// nothing: travel beyond the hole's greatest width, the tube's centre
2965/// circle). So the ring sweeps what the FILLED ring sweeps: a tool with a
2966/// half-round rim and flat faces, which is swept whole. A whole turn sweeps
2967/// the solid of revolution of that tool's shadow about the turn's axis.
2968fn flat_ring(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2969    if screw.frame.is_some() || screw.turns.is_some() || screw.c2 != 0.0 {
2970        return Ok(None);
2971    }
2972    let Ok(w) = axis.normalized() else { return Ok(None) };
2973    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 };
2974    if !flat {
2975        return Ok(None);
2976    }
2977    // The holed tool: a torus (`torus`: its tube), or straight-sided pieces
2978    // whose hole is one upright wall from the tool's top to its bottom.
2979    // `big`: half the hole's greatest width. `filled_meridian`: the tool
2980    // with its hole closed, flat across at its top and bottom.
2981    let (big, level, torus, filled_meridian): (f64, f64, Option<f64>, Vec<OutlinePiece>) = match meridian {
2982        [OutlinePiece::Arc { centre, radius, start, end }] => {
2983            let (big, tube, level) = (centre[0], *radius, centre[1]);
2984            if ((end - start).abs() - TAU).abs() >= 1e-12 || big <= tube {
2985                return Ok(None);
2986            }
2987            (
2988                big,
2989                level,
2990                Some(tube),
2991                vec![
2992                    OutlinePiece::Line { from: [0.0, level - tube], to: [big, level - tube] },
2993                    OutlinePiece::Arc { centre: [big, level], radius: tube, start: -0.5 * PI, end: 0.5 * PI },
2994                    OutlinePiece::Line { from: [big, level + tube], to: [0.0, level + tube] },
2995                    OutlinePiece::Line { from: [0.0, level + tube], to: [0.0, level - tube] },
2996                ],
2997            )
2998        }
2999        pieces => {
3000            let mut ends: Vec<([f64; 2], [f64; 2])> = Vec::with_capacity(pieces.len());
3001            for piece in pieces {
3002                let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
3003                ends.push((*from, *to));
3004            }
3005            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);
3006            let inner = ends.iter().flat_map(|(a, b)| [a[0], b[0]]).fold(f64::INFINITY, f64::min);
3007            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)));
3008            if ends.len() < 3 || inner <= 1e-9 * scale {
3009                return Ok(None);
3010            }
3011            let walls: Vec<usize> = (0..ends.len())
3012                .filter(|&k| {
3013                    let (a, b) = ends[k];
3014                    (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
3015                })
3016                .collect();
3017            let [wall] = walls.as_slice() else { return Ok(None) };
3018            let (from, to) = ends[*wall];
3019            // From the wall's end round the outside back to its start, then
3020            // across to the axis and along it.
3021            let mut filled = vec![OutlinePiece::Line { from: [0.0, to[1]], to }];
3022            for k in 1..pieces.len() {
3023                filled.push(pieces[(wall + k) % pieces.len()].clone());
3024            }
3025            filled.push(OutlinePiece::Line { from, to: [0.0, from[1]] });
3026            filled.push(OutlinePiece::Line { from: [0.0, from[1]], to: [0.0, to[1]] });
3027            (inner, 0.5 * (low + high), None, filled)
3028        }
3029    };
3030    let centre0 = origin.add(w.scale(level));
3031    let filled = SolidTool::Revolved { axis_origin: origin, axis_direction: w, radial, meridian: filled_meridian };
3032    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());
3033    if screw.omega == 0.0 {
3034        if screw.c.abs() * (screw.t1 - screw.t0) <= 2.0 * big * (1.0 + 1e-9) {
3035            let Some(tube) = torus else { return Err(short()) };
3036            // Short of its hole: what stays open, all the way through, is the
3037            // lens the hole shares where the ring starts and where it stops.
3038            // The hole at one place: inside the ring's inner half, between
3039            // its top and bottom planes.
3040            let hole = |t: f64| -> Result<BrepSolid, KernelRefusal> {
3041                let o = screw.apply(t, centre0);
3042                let u = frag(radial.sub(w.scale(radial.dot(w))).normalized(), "ring_flat")?;
3043                let at = |rho: f64, z: f64| o.add(u.scale(rho)).add(w.scale(z));
3044                let n = w.cross(u);
3045                let from = at(big, -tube);
3046                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")?;
3047                let profile = [
3048                    frag(make_line(at(0.0, -tube), at(big, -tube)), "ring_flat")?,
3049                    inner,
3050                    frag(make_line(at(big, tube), at(0.0, tube)), "ring_flat")?,
3051                    frag(make_line(at(0.0, tube), at(0.0, -tube)), "ring_flat")?,
3052                ];
3053                frag(crate::revolve_profile_brep(&profile, o, w, TAU), "ring_flat")
3054            };
3055            let (sewn_on, sewn_check) = (ring_lens_sewn_on(), ring_lens_sewn_check_on());
3056            if sewn_on || sewn_check {
3057                let whole = sweep_with(screw, &filled)?;
3058                let c0 = screw.apply(screw.t0, centre0);
3059                let c1 = screw.apply(screw.t1, centre0);
3060                let sewn = sewn_lens(&whole, c0, c1, w, big, tube);
3061                if sewn_check {
3062                    let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
3063                    let cut = crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract)?;
3064                    ring_lens_check_record(&cut, sewn.as_ref());
3065                    return Ok(Some(cut));
3066                }
3067                if let Some(body) = sewn {
3068                    return Ok(Some(body));
3069                }
3070            }
3071            let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
3072            let whole = sweep_with(screw, &filled)?;
3073            return crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract).map(Some);
3074        }
3075        return sweep_with(screw, &filled).map(Some);
3076    }
3077    // A turn: the ring's centre runs a circle of radius `reach` about the axis.
3078    let start_centre = screw.apply(screw.t0, centre0);
3079    let from_axis = start_centre.sub(screw.a);
3080    let across = from_axis.sub(screw.e.scale(from_axis.dot(screw.e)));
3081    let reach = across.length();
3082    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
3083    if theta >= TAU * (1.0 - 1e-12) {
3084        let Some(tube) = torus else {
3085            return Err(refuse("ring_flat", "a whole turn of a holed tool in its own plane is swept for a ring only".into()));
3086        };
3087        if reach <= (big + tube) * (1.0 + 1e-9) {
3088            return Err(refuse("ring_flat", "a ring turned a whole turn in its own plane reaches the turn's axis".into()));
3089        }
3090        let out = frag(across.normalized(), "ring_flat")?;
3091        let foot = start_centre.sub(across);
3092        let at = |rho: f64, z: f64| foot.add(out.scale(rho)).add(screw.e.scale(z));
3093        let half_round = |centre: Vec3, from: Vec3| -> Result<NurbsCurve, KernelRefusal> {
3094            let n = out.cross(screw.e);
3095            let surface = frag(make_revolution(centre, n, &frag(make_line(from, from.add(n)), "line")?, PI), "ring_flat")?;
3096            frag(surface.iso_curve_v(0.0), "ring_flat")
3097        };
3098        let profile = [
3099            frag(make_line(at(reach - big, -tube), at(reach + big, -tube)), "ring_flat")?,
3100            half_round(at(reach + big, 0.0), at(reach + big, -tube))?,
3101            frag(make_line(at(reach + big, tube), at(reach - big, tube)), "ring_flat")?,
3102            half_round(at(reach - big, 0.0), at(reach - big, tube))?,
3103        ];
3104        return frag(crate::revolve_profile_brep(&profile, foot, screw.e, TAU), "ring_flat").map(Some);
3105    }
3106    let covered = if theta >= PI { big < reach } else { reach * (0.5 * theta).sin() > big * (1.0 + 1e-9) };
3107    if !covered {
3108        return Err(short());
3109    }
3110    sweep_with(screw, &filled).map(Some)
3111}
3112
3113/// The sweep of `tool` along `motion`, where it lies in `clip` (the caller
3114/// cuts a workpiece inside that region). A TURN about the clip's own axis
3115/// whose two end positions stay outside the clip's wedge covers the wedge
3116/// wholly with the tool's shadow in (ρ, z): that shadow, turned over the wedge,
3117/// is the sweep there (a convex polyhedron's shadow is bounded by conic arcs
3118/// from its edges and straight lines from its faces, so every surface is
3119/// exact); a turn about that axis whose ends reach the wedge is refused. A
3120/// screw or turn about the region's axis whose tool reaches far past the
3121/// region's radius sweeps only the tool's part that can reach it (see
3122/// `trim_to_clip`). Any other motion gets the whole sweep ([`sweep_solid`]).
3123pub fn sweep_solid_clipped(tool: &SolidTool, motion: &SolidMotion, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
3124    let screw = Screw::from_motion(motion)?;
3125    if let (SolidTool::Polyhedron { vertices, faces }, Some(wedge)) = (tool, clip.angle) {
3126        let axis = clip.axis_direction.normalized().map_err(|_| input("clip_axis", "the clip's axis has no direction".into()))?;
3127        let same_axis = screw.c == 0.0 && screw.c2 == 0.0
3128            && screw.e.cross(axis).length() < 1e-12
3129            && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
3130        if same_axis {
3131            return turn_shadow(&screw, vertices, faces, clip, axis, wedge);
3132        }
3133    }
3134    if let SolidTool::Polyhedron { vertices, faces } = tool {
3135        if let Some((vertices, faces)) = trim_to_clip(&screw, vertices, faces, clip)? {
3136            return sweep_solid(&SolidTool::Polyhedron { vertices, faces }, motion);
3137        }
3138    }
3139    sweep_solid(tool, motion)
3140}
3141
3142/// The sweep of `tool` along a turn whose rise grows as it turns, where it lies
3143/// in `clip` (as [`sweep_solid_clipped`]). Its front and back are those at
3144/// the middle of the motion; a tool whose faces change side along it is refused.
3145pub fn sweep_solid_rising(tool: &SolidTool, motion: &RisingTurn, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
3146    let screw = Screw::from_rising(motion)?;
3147    let SolidTool::Polyhedron { vertices, faces } = tool else {
3148        return Err(refuse("rising_tool", "a growing rise sweeps a polyhedron only".into()));
3149    };
3150    let (vertices, faces) = trim_to_clip(&screw, vertices, faces, clip)?.unwrap_or_else(|| (vertices.clone(), faces.clone()));
3151    sweep_with(&screw, &SolidTool::Polyhedron { vertices, faces })
3152}
3153
3154/// The sweep of `tool` along `motion` as parts whose union it is (a caller cuts
3155/// a workpiece by all of them). One part where the whole sweep passes once. A
3156/// convex polyhedron whose sweep folds over itself (a face facing away from a
3157/// screw's or turn's axis grazes along a line inside it, and the faces beyond
3158/// that line are swept over again) is split by the plane through the axis and
3159/// that line: each half grazes that face only along its cut edge, and is swept
3160/// whole. The halves' walls share cylinders about the axis.
3161pub fn sweep_solid_parts(tool: &SolidTool, motion: &SolidMotion) -> Result<Vec<BrepSolid>, KernelRefusal> {
3162    let folded = match sweep_solid(tool, motion) {
3163        Ok(body) => return Ok(vec![body]),
3164        Err(error) if refused_as(&error) == Some("folds") => error,
3165        Err(error) => return Err(error),
3166    };
3167    let SolidTool::Polyhedron { vertices, faces } = tool else { return Err(folded) };
3168    let screw = Screw::from_motion(motion)?;
3169    if screw.omega == 0.0 {
3170        return Err(folded);
3171    }
3172    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);
3173    let mut planes: Vec<(Vec3, f64)> = Vec::new();
3174    for face in faces {
3175        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
3176        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
3177        if n.dot(p.sub(centroid)) < 0.0 {
3178            n = n.scale(-1.0);
3179        }
3180        planes.push((n, n.dot(p)));
3181    }
3182    // A face square to the axis' plane through it (its normal square to the
3183    // axis) graze along the line through its foot from the axis; it folds if
3184    // it faces away from the axis and that line crosses it.
3185    for (n, d) in planes.clone() {
3186        if n.dot(screw.e).abs() > 1e-12 {
3187            continue;
3188        }
3189        let foot = screw.a.add(n.scale(d - n.dot(screw.a)));
3190        let radial = foot.sub(screw.a).sub(screw.e.scale(foot.sub(screw.a).dot(screw.e)));
3191        if radial.dot(n) <= 0.0 {
3192            continue; // faces the axis: its grazing line is the sweep's inner wall
3193        }
3194        let cut = match screw.e.cross(radial).normalized() {
3195            Ok(m) => m,
3196            Err(_) => continue,
3197        };
3198        let offset = cut.dot(screw.a);
3199        let mut parts = Vec::with_capacity(2);
3200        for sense in [1.0, -1.0] {
3201            let mut half = planes.clone();
3202            half.push((cut.scale(sense), offset * sense));
3203            let (corners, loops) = polyhedron_of_planes(&half)?;
3204            if corners.len() < 4 || loops.len() < 4 {
3205                parts.clear();
3206                break;
3207            }
3208            match sweep_solid(&SolidTool::Polyhedron { vertices: corners, faces: loops }, motion) {
3209                Ok(body) => parts.push(body),
3210                Err(_) => {
3211                    parts.clear();
3212                    break;
3213                }
3214            }
3215        }
3216        if parts.len() == 2 {
3217            return Ok(parts);
3218        }
3219    }
3220    Err(folded)
3221}
3222
3223/// A screw or turn about the clip's axis maps the clip's cylinder (radius
3224/// ≤ R) onto itself, so inside it the sweep of the tool is the sweep of any
3225/// part of the tool holding the tool's part inside the cylinder. A tool
3226/// reaching far past it (a bar pointing at the axis) is replaced by its part
3227/// inside the prism over the shadow's piece of a slightly larger disc, with
3228/// that disc's arc replaced by the two tangents at its ends: those faces graze
3229/// only along their own end edges, where the far ends of a long tool would
3230/// fold the sweep over itself. None when the tool needs no trim.
3231fn trim_to_clip(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip) -> Result<Option<(Vec<Vec3>, Vec<Vec<usize>>)>, KernelRefusal> {
3232    let Ok(axis) = clip.axis_direction.normalized() else { return Ok(None) };
3233    let same_axis = screw.omega != 0.0
3234        && screw.e.cross(axis).length() < 1e-12
3235        && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
3236    if !same_axis || !clip.radius[1].is_finite() {
3237        return Ok(None);
3238    }
3239    let ez = axis;
3240    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))?;
3241    let ey = ez.cross(ex);
3242    let flat = |p: Vec3| {
3243        let r = p.sub(clip.axis_origin);
3244        [r.dot(ex), r.dot(ey)]
3245    };
3246    let radius = clip.radius[1] * 1.02;
3247    let shadow: Vec<[f64; 2]> = vertices.iter().map(|&p| flat(p)).collect();
3248    if shadow.iter().all(|q| q[0].hypot(q[1]) <= radius) {
3249        return Ok(None);
3250    }
3251    // The shadow's convex hull, counter-clockwise.
3252    let mut points = shadow.clone();
3253    points.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
3254    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]);
3255    let mut hull: Vec<[f64; 2]> = Vec::new();
3256    for pass in 0..2 {
3257        let start = hull.len();
3258        let ordered: Vec<[f64; 2]> = if pass == 0 { points.clone() } else { points.iter().rev().copied().collect() };
3259        for p in ordered {
3260            while hull.len() >= start + 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
3261                hull.pop();
3262            }
3263            hull.push(p);
3264        }
3265        hull.pop();
3266    }
3267    // Where the hull's boundary leaves and re-enters the disc.
3268    let m = hull.len();
3269    let inside = |q: [f64; 2]| q[0].hypot(q[1]) <= radius;
3270    // Leave a tool that does not reach the disc, or wraps the axis.
3271    let mut nearest = f64::INFINITY;
3272    let mut wraps = true;
3273    for k in 0..m {
3274        let (a, b) = (hull[k], hull[(k + 1) % m]);
3275        let d = [b[0] - a[0], b[1] - a[1]];
3276        let t = (-(a[0] * d[0] + a[1] * d[1]) / (d[0] * d[0] + d[1] * d[1])).clamp(0.0, 1.0);
3277        nearest = nearest.min((a[0] + d[0] * t).hypot(a[1] + d[1] * t));
3278        if cross(a, b, [0.0, 0.0]) < 0.0 {
3279            wraps = false;
3280        }
3281    }
3282    if wraps || nearest >= radius || (0..m).all(|k| inside(hull[k])) {
3283        return Ok(None);
3284    }
3285    let mut leave: Vec<f64> = Vec::new();
3286    let mut enter: Vec<f64> = Vec::new();
3287    for k in 0..m {
3288        let (a, b) = (hull[k], hull[(k + 1) % m]);
3289        let d = [b[0] - a[0], b[1] - a[1]];
3290        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);
3291        let disc = qb * qb - 4.0 * qa * qc;
3292        if disc <= 0.0 {
3293            continue;
3294        }
3295        for t in [(-qb - disc.sqrt()) / (2.0 * qa), (-qb + disc.sqrt()) / (2.0 * qa)] {
3296            if t > 0.0 && t < 1.0 {
3297                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
3298                let outward = 2.0 * (q[0] * d[0] + q[1] * d[1]) > 0.0;
3299                (if outward { &mut leave } else { &mut enter }).push(q[1].atan2(q[0]));
3300            }
3301        }
3302    }
3303    let ([a], [b]) = (leave.as_slice(), enter.as_slice()) else {
3304        return Err(refuse("clip_trim", "the tool's shadow leaves the clip's disc more than once".into()));
3305    };
3306    let width = (b - a).rem_euclid(TAU);
3307    if width >= 0.9 * PI {
3308        return Err(refuse("clip_trim", "the tool's shadow spans too much of the clip's circle to be trimmed".into()));
3309    }
3310    // Planes of the tool, and the two tangents (outward normals in the plane).
3311    let mut planes: Vec<(Vec3, f64)> = Vec::new();
3312    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);
3313    for face in faces {
3314        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
3315        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
3316        if n.dot(p.sub(centroid)) < 0.0 {
3317            n = n.scale(-1.0);
3318        }
3319        planes.push((n, n.dot(p)));
3320    }
3321    for angle in [*a, *b] {
3322        let n = ex.scale(angle.cos()).add(ey.scale(angle.sin()));
3323        planes.push((n, n.dot(clip.axis_origin) + radius));
3324    }
3325    Ok(Some(polyhedron_of_planes(&planes)?))
3326}
3327
3328/// `BREP_SWEEP_SLID_POLYHEDRON_HULL` (default on; `=0` restores the refusal): a convex polyhedron slid
3329/// straight sweeps exactly the convex hull of its two end positions (every
3330/// point between is on a segment from one to the other), so the sweep is that
3331/// hull. The grazing split refused a face the slide moves in its own plane (a
3332/// block slid along one of its faces: the face's sweep is flat).
3333fn slid_hull_on() -> bool {
3334    crate::switch!("BREP_SWEEP_SLID_POLYHEDRON_HULL", true)
3335}
3336
3337/// The convex hull of the polyhedron at the screw's two ends, the screw being a
3338/// straight slide. The polyhedron must be the convex one its faces bound (the
3339/// hull of a concave tool is not its sweep), so its faces are read first: each
3340/// flat, the set closed, and every corner on the inner side of every face.
3341fn slid_polyhedron_hull(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
3342    if vertices.len() < 4 || faces.len() < 4 || vertices.len() > 256 {
3343        return Err(input("polyhedron", "the tool needs at least four corners and four faces (and at most 256 corners)".into()));
3344    }
3345    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);
3346    let extent = vertices.iter().map(|p| p.sub(centroid).length()).fold(0.0f64, f64::max);
3347    if !(extent > 0.0) {
3348        return Err(input("polyhedron", "the tool's corners coincide".into()));
3349    }
3350    let slack = 1e-9 * extent;
3351    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
3352    // Either winding is a face's (as the grazing split reads it): each is
3353    // turned to run counter-clockwise from outside before the faces are read.
3354    let mut oriented: Vec<Vec<usize>> = Vec::with_capacity(faces.len());
3355    let mut normals: Vec<Vec3> = Vec::with_capacity(faces.len());
3356    for (index, face) in faces.iter().enumerate() {
3357        if face.len() < 3 || face.iter().any(|&k| k >= vertices.len()) {
3358            return Err(input("face", format!("face {index} names fewer than three corners or one past the tool's")));
3359        }
3360        // Newell's normal, then outward by the centroid.
3361        let mut normal = Vec3::new(0.0, 0.0, 0.0);
3362        for k in 0..face.len() {
3363            let (a, b) = (vertices[face[k]].sub(centroid), vertices[face[(k + 1) % face.len()]].sub(centroid));
3364            normal = normal.add(Vec3::new((a.y - b.y) * (a.z + b.z), (a.z - b.z) * (a.x + b.x), (a.x - b.x) * (a.y + b.y)));
3365        }
3366        // Against the tool's own size, not an absolute floor.
3367        let length = normal.length();
3368        if !(length > 1e-18 * extent * extent) {
3369            return Err(input("face", format!("face {index} has no area")));
3370        }
3371        let mut normal = normal.scale(1.0 / length);
3372        let mut face = face.clone();
3373        let d = normal.dot(vertices[face[0]].sub(centroid));
3374        let d = if d < 0.0 {
3375            normal = normal.scale(-1.0);
3376            face.reverse();
3377            -d
3378        } else {
3379            d
3380        };
3381        for &k in &face {
3382            if (normal.dot(vertices[k].sub(centroid)) - d).abs() > slack {
3383                return Err(input("face", format!("face {index}'s corners are not in one plane")));
3384            }
3385        }
3386        if vertices.iter().any(|p| normal.dot(p.sub(centroid)) - d > slack) {
3387            return Err(input("convex", "the tool is not convex: a corner lies outside one of its faces".into()));
3388        }
3389        for k in 0..face.len() {
3390            let (a, b) = (face[k], face[(k + 1) % face.len()]);
3391            if owner.insert((a, b), index).is_some() {
3392                return Err(input("closed", "an edge is used more than once the same way".into()));
3393            }
3394        }
3395        oriented.push(face);
3396        normals.push(normal);
3397    }
3398    for &(a, b) in owner.keys() {
3399        if !owner.contains_key(&(b, a)) {
3400            return Err(input("closed", "the polyhedron's faces do not close".into()));
3401        }
3402    }
3403    // The faces must bound one closed part (the polyhedron builder's own
3404    // reading: faces given twice, once each way, close into separate parts).
3405    crate::make_polyhedron_brep(vertices, &oriented)?;
3406    // The sweep is the tool's Minkowski sum with the slide [0, s]: faces it
3407    // leaves behind at the start (n · s < 0), faces it leads with at the end
3408    // (n · s > 0), faces it slides in their own plane stretched to the hull of
3409    // their two copies, and one parallelogram per edge where the faces either
3410    // side face opposite ways. Built from the tool's own faces, no plane is
3411    // searched for and no tolerance grows with the slide.
3412    let n = vertices.len();
3413    let start: Vec<Vec3> = vertices.iter().map(|&p| screw.apply(screw.t0, p)).collect();
3414    let end: Vec<Vec3> = vertices.iter().map(|&p| screw.apply(screw.t1, p)).collect();
3415    let slide = end[0].sub(start[0]);
3416    let travel = slide.length();
3417    if !(travel > 0.0 && travel.is_finite()) {
3418        return Err(input("still", "the slide does not move".into()));
3419    }
3420    let along = slide.scale(1.0 / travel);
3421    // The polyhedron builder reads its faces against its whole extent, so a
3422    // slide far longer than the tool's thinnest width is beyond what it
3423    // builds (that width: the least spread of the corners along a face's
3424    // normal).
3425    let width = normals.iter().map(|nf| {
3426        let reach: Vec<f64> = vertices.iter().map(|p| nf.dot(*p)).collect();
3427        reach.iter().copied().fold(f64::NEG_INFINITY, f64::max) - reach.iter().copied().fold(f64::INFINITY, f64::min)
3428    }).fold(f64::INFINITY, f64::min);
3429    if slide.length() > 1e6 * width {
3430        return Err(refuse("slid_hull", format!("the slide ({:.3e}) is more than 1e6 times the tool's thinnest width ({width:.3e})", slide.length())));
3431    }
3432    let side: Vec<i8> = normals.iter().map(|nf| {
3433        let c = nf.dot(along);
3434        if c.abs() <= 1e-12 { 0 } else if c > 0.0 { 1 } else { -1 }
3435    }).collect();
3436    let corners: Vec<Vec3> = start.iter().chain(end.iter()).copied().collect();
3437    // A corner the slide carries onto another (a block slid by its own width)
3438    // is one corner: every index is read as its first coincident one.
3439    let canonical: Vec<usize> = (0..corners.len())
3440        .map(|k| (0..k).find(|&j| corners[j].sub(corners[k]).length() <= slack).unwrap_or(k))
3441        .collect();
3442    let mut pool: Vec<usize> = canonical.clone();
3443    pool.sort_unstable();
3444    pool.dedup();
3445    let canon = |set: Vec<usize>| -> Vec<usize> {
3446        let mut out: Vec<usize> = set.into_iter().map(|k| canonical[k]).collect();
3447        out.sort_unstable();
3448        out.dedup();
3449        out
3450    };
3451    // A ring of corner indices, ordered as the convex hull of its points
3452    // counter-clockwise about `normal` (corners inside it or on its sides
3453    // dropped).
3454    let ring = |set: &[usize], normal: Vec3| -> Option<Vec<usize>> {
3455        let middle = set.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &k| s.add(corners[k])).scale(1.0 / set.len() as f64);
3456        // The longest offset in the plane, divided by its own length (no
3457        // absolute floor: a small face is as good as a large one).
3458        let u = set
3459            .iter()
3460            .map(|&k| corners[k].sub(middle))
3461            .map(|r| r.sub(normal.scale(r.dot(normal))))
3462            .max_by(|a, b| a.length().total_cmp(&b.length()))?;
3463        let u = (u.length() > 0.0).then(|| u.scale(1.0 / u.length()))?;
3464        let v = normal.cross(u);
3465        let flat = |k: usize| {
3466            let r = corners[k].sub(middle);
3467            (r.dot(u), r.dot(v))
3468        };
3469        let mut order = set.to_vec();
3470        order.sort_by(|&a, &b| {
3471            let (pa, pb) = (flat(a), flat(b));
3472            pa.0.total_cmp(&pb.0).then(pa.1.total_cmp(&pb.1))
3473        });
3474        // A point is on the line through two others when it stands off it by
3475        // no more than the tool's tolerance (a distance, whatever the slide's
3476        // length): twice the triangle's area over the base.
3477        let left = |o: usize, a: usize, b: usize| {
3478            let (po, pa, pb) = (flat(o), flat(a), flat(b));
3479            let cross = (pa.0 - po.0) * (pb.1 - po.1) - (pa.1 - po.1) * (pb.0 - po.0);
3480            cross > slack * (pb.0 - po.0).hypot(pb.1 - po.1)
3481        };
3482        let mut hull: Vec<usize> = Vec::new();
3483        for pass in [false, true] {
3484            let begin = hull.len();
3485            let sequence: Vec<usize> = if pass { order.iter().rev().copied().collect() } else { order.clone() };
3486            for k in sequence {
3487                while hull.len() >= begin + 2 && !left(hull[hull.len() - 2], hull[hull.len() - 1], k) {
3488                    hull.pop();
3489                }
3490                hull.push(k);
3491            }
3492            hull.pop();
3493        }
3494        if hull.len() < 3 {
3495            return None;
3496        }
3497        // Every corner of the sweep on a side of this ring stays on it, in
3498        // order: whichever face it came from, the neighbour across that side
3499        // reads the same corners there, so the two rings carry the same edges.
3500        let mut out: Vec<usize> = Vec::with_capacity(set.len());
3501        for k in 0..hull.len() {
3502            let (p, q) = (hull[k], hull[(k + 1) % hull.len()]);
3503            out.push(p);
3504            let (a, d) = (corners[p], corners[q].sub(corners[p]));
3505            let length = d.length();
3506            let mut between: Vec<(f64, usize)> = pool
3507                .iter()
3508                .filter(|&&m| m != p && m != q)
3509                .filter_map(|&m| {
3510                    let r = corners[m].sub(a);
3511                    let t = r.dot(d) / (length * length);
3512                    let off = r.sub(d.scale(t)).length();
3513                    (t > 0.0 && t < 1.0 && off <= slack).then_some((t, m))
3514                })
3515                .collect();
3516            between.sort_by(|x, y| x.0.total_cmp(&y.0));
3517            out.extend(between.into_iter().map(|(_, m)| m));
3518        }
3519        Some(out)
3520    };
3521    // Coplanar faces of a convex polyhedron are one face of it: grouped by
3522    // plane, each group read as one (the union of its corners).
3523    let offsets: Vec<f64> = oriented.iter().zip(&normals).map(|(face, nf)| nf.dot(vertices[face[0]].sub(centroid))).collect();
3524    let mut group = vec![usize::MAX; oriented.len()];
3525    let mut groups: Vec<Vec<usize>> = Vec::new();
3526    for f in 0..oriented.len() {
3527        if group[f] != usize::MAX {
3528            continue;
3529        }
3530        group[f] = groups.len();
3531        let mut members = vec![f];
3532        for g in f + 1..oriented.len() {
3533            // One face only if the slide reads them alike too: two faces a
3534            // hair apart in angle can face it opposite ways, and then their
3535            // shared edge is a silhouette of its own.
3536            if group[g] == usize::MAX && side[g] == side[f] && normals[g].sub(normals[f]).length() <= 1e-9 && (offsets[g] - offsets[f]).abs() <= slack {
3537                group[g] = groups.len();
3538                members.push(g);
3539            }
3540        }
3541        groups.push(members);
3542    }
3543    let mut hull_faces: Vec<Vec<usize>> = Vec::new();
3544    for (index, members) in groups.iter().enumerate() {
3545        let f = members[0];
3546        let mut corners_of: Vec<usize> = members.iter().flat_map(|&m| oriented[m].iter().copied()).collect();
3547        corners_of.sort_unstable();
3548        corners_of.dedup();
3549        let set: Vec<usize> = canon(match side[f] {
3550            -1 => corners_of,
3551            1 => corners_of.iter().map(|&k| k + n).collect(),
3552            _ => corners_of.iter().flat_map(|&k| [k, k + n]).collect(),
3553        });
3554        hull_faces.push(ring(&set, normals[f]).ok_or_else(|| refuse("slid_hull", format!("face group {index}'s sweep has no area")))?);
3555    }
3556    // In a fixed order, so the same tool builds the same body.
3557    let mut edges: Vec<(usize, usize)> = owner.keys().copied().filter(|&(a, b)| a < b).collect();
3558    edges.sort_unstable();
3559    for (a, b) in edges {
3560        let (f, g) = (owner[&(a, b)], owner[&(b, a)]);
3561        // Once per edge between two faces of the hull's own (not two
3562        // coplanar pieces of one), where the face on its left leads and the
3563        // one on its right trails (or the other way): the edge's own sweep is
3564        // a face.
3565        if group[f] != group[g] && side[f] * side[g] < 0 {
3566            let edge = start[b].sub(start[a]);
3567            // Against the edge's own length (an edge of a silhouette is never
3568            // along the slide: its faces would both slide in their planes).
3569            let cross = edge.cross(along);
3570            let length = cross.length();
3571            if !(length > 1e-12 * edge.length()) {
3572                return Err(refuse("slid_hull", "a silhouette edge runs along the slide".into()));
3573            }
3574            let mut normal = cross.scale(1.0 / length);
3575            if normal.dot(start[a].sub(centroid)) < 0.0 {
3576                normal = normal.scale(-1.0);
3577            }
3578            hull_faces.push(ring(&canon(vec![a, b, a + n, b + n]), normal).ok_or_else(|| refuse("slid_hull", "an edge's sweep has no area".into()))?);
3579        }
3580    }
3581    crate::make_polyhedron_brep(&corners, &hull_faces)
3582}
3583
3584/// The convex polyhedron {n · p ≤ d for every plane}: its corners (where three
3585/// planes meet inside all) and a face per plane that bounds it.
3586pub fn polyhedron_of_planes(planes: &[(Vec3, f64)]) -> Result<(Vec<Vec3>, Vec<Vec<usize>>), KernelRefusal> {
3587    let k = planes.len();
3588    let mut corners: Vec<Vec3> = Vec::new();
3589    let scale = planes.iter().map(|p| p.1.abs()).fold(1.0f64, f64::max);
3590    for i in 0..k {
3591        for j in i + 1..k {
3592            for l in j + 1..k {
3593                let (a, b, c) = (planes[i].0, planes[j].0, planes[l].0);
3594                let det = a.dot(b.cross(c));
3595                if det.abs() < 1e-12 {
3596                    continue;
3597                }
3598                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);
3599                if planes.iter().all(|(n, d)| n.dot(p) - d <= 1e-9 * scale) && !corners.iter().any(|q| q.sub(p).length() <= 1e-9 * scale) {
3600                    corners.push(p);
3601                }
3602            }
3603        }
3604    }
3605    let mut faces = Vec::new();
3606    for (n, d) in planes {
3607        let on: Vec<usize> = (0..corners.len()).filter(|&c| (n.dot(corners[c]) - d).abs() <= 1e-9 * scale).collect();
3608        if on.len() < 3 {
3609            continue;
3610        }
3611        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);
3612        let u = frag(corners[on[0]].sub(middle).normalized(), "face_axis")?;
3613        let v = n.cross(u);
3614        let mut ordered = on.clone();
3615        ordered.sort_by(|&p, &q| {
3616            let (rp, rq) = (corners[p].sub(middle), corners[q].sub(middle));
3617            rp.dot(v).atan2(rp.dot(u)).total_cmp(&rq.dot(v).atan2(rq.dot(u)))
3618        });
3619        faces.push(ordered);
3620    }
3621    Ok((corners, faces))
3622}
3623
3624fn turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip, axis: Vec3, wedge: [f64; 2]) -> Result<BrepSolid, KernelRefusal> {
3625    let ez = axis;
3626    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()))?;
3627    let ey = ez.cross(ex);
3628    // Turning by ω t about e = ±ez moves angles about ez by ±ω t.
3629    let rate = screw.omega * screw.e.dot(ez).signum();
3630    let local = |p: Vec3| {
3631        let r = p.sub(clip.axis_origin);
3632        [r.dot(ex), r.dot(ey), r.dot(ez)]
3633    };
3634    let corners: Vec<[f64; 3]> = vertices.iter().map(|&p| local(p)).collect();
3635    // The tool's angular extent about the axis (its corners'; the tool must
3636    // keep off the axis, so its shadow on the plane misses the origin).
3637    let mid = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
3638    let mid_angle = mid[1].atan2(mid[0]);
3639    let angles: Vec<f64> = corners.iter().map(|c| mid_angle + (c[1].atan2(c[0]) - mid_angle + PI).rem_euclid(TAU) - PI).collect();
3640    let (low, high) = (angles.iter().copied().fold(f64::INFINITY, f64::min), angles.iter().copied().fold(f64::NEG_INFINITY, f64::max));
3641    if high - low >= PI {
3642        return Err(refuse("turn_shadow", "the tool reaches round the turn's axis".into()));
3643    }
3644    let (start, end) = (rate * screw.t0, rate * screw.t1);
3645    let (first, last) = if rate > 0.0 { (start, end) } else { (end, start) };
3646    let reference = 0.5 * (wedge[0] + wedge[1]);
3647    let near = |a: f64| reference + (a - reference + PI).rem_euclid(TAU) - PI;
3648    // Before the wedge at one end, after it at the other (angles taken near the wedge).
3649    let clear = near(high + first) < wedge[0] - 1e-9 && near(low + last) > wedge[1] + 1e-9 && (last - first) < TAU;
3650    if !clear {
3651        return Err(refuse("turn_shadow", "the turned tool's ends reach the clip's wedge; its sweep there is not its turned shadow".into()));
3652    }
3653    let profile = polyhedron_shadow(&corners, faces, false)?;
3654    // The profile in the half-plane at the wedge's start angle.
3655    let (c0, s0) = (wedge[0].cos(), wedge[0].sin());
3656    let world = |rho: f64, z: f64| clip.axis_origin.add(ez.scale(z)).add(ex.scale(rho * c0)).add(ey.scale(rho * s0));
3657    let mut curves = Vec::with_capacity(profile.len());
3658    for piece in &profile {
3659        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
3660        let curve = if points.len() == 2 {
3661            frag(make_line(frag(points[0].point(), "point")?, frag(points[1].point(), "point")?), "line")?
3662        } else {
3663            frag(NurbsCurve::new(2, vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points), "conic")?
3664        };
3665        curves.push(curve);
3666    }
3667    frag(crate::revolve_profile_brep(&curves, clip.axis_origin, ez, wedge[1] - wedge[0]), "turn_shadow")
3668}
3669
3670/// A convex polyhedron turned a whole turn (no advance): the solid of
3671/// revolution of its shadow {(ρ, z)} about the turn's axis, which may pass
3672/// through it. Its corners' paths bound it only where an edge is farthest
3673/// from the axis; an edge skew to the axis turns a hyperboloid.
3674fn whole_turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
3675    let ez = screw.e;
3676    let ex = frag(ez.perpendicular(), "turn_shadow")?;
3677    let ex = frag(ex.sub(ez.scale(ex.dot(ez))).normalized(), "turn_shadow")?;
3678    let ey = ez.cross(ex);
3679    let corners: Vec<[f64; 3]> = vertices
3680        .iter()
3681        .map(|&p| {
3682            let r = screw.apply(screw.t0, p).sub(screw.a);
3683            [r.dot(ex), r.dot(ey), r.dot(ez)]
3684        })
3685        .collect();
3686    let profile = polyhedron_shadow(&corners, faces, true)?;
3687    // A point of the outline on the axis to round-off is on it.
3688    let reach = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(0.0f64, f64::max);
3689    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 }));
3690    let mut curves = Vec::with_capacity(profile.len());
3691    // The outline's stretch along the axis, as one edge (it comes a piece per
3692    // corner height).
3693    let on_axis = |piece: &ShadowPiece| piece.iter().all(|&(rho, _, _)| rho.abs() <= 1e-10 * reach);
3694    let mut along: Option<(f64, f64)> = None;
3695    for piece in &profile {
3696        if on_axis(piece) {
3697            let (za, zb) = (piece[0].1, piece[piece.len() - 1].1);
3698            along = Some(match along {
3699                Some((from, _)) => (from, zb),
3700                None => (za, zb),
3701            });
3702            continue;
3703        }
3704        if let Some((from, to)) = along.take() {
3705            curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3706        }
3707        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
3708        let (first, last) = (frag(points[0].point(), "point")?, frag(points[points.len() - 1].point(), "point")?);
3709        if first.sub(last).length() <= 1e-12 * (1.0 + first.length()) {
3710            continue;
3711        }
3712        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")? };
3713        curves.push(curve);
3714    }
3715    if let Some((from, to)) = along.take() {
3716        curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
3717    }
3718    frag(crate::revolve_profile_brep(&curves, screw.a, ez, TAU), "turn_shadow")
3719}
3720
3721/// One piece of the shadow's outline: a segment (two points) or a rational
3722/// quadratic arc (three, the middle with its weight), as (ρ, z, weight).
3723type ShadowPiece = Vec<(f64, f64, f64)>;
3724
3725/// The shadow {(ρ, z)} of a convex polyhedron (corners in the axis frame):
3726/// at each z its section is a convex polygon, the ρ it reaches an interval
3727/// from the section's nearest point to its farthest corner. The farthest is
3728/// always on an edge (ρ² = quadratic in z: a conic arc); the nearest is on a
3729/// face (ρ linear in z: a segment) or an edge.
3730///
3731/// `through`: the axis may pass through the tool (its nearest ρ is then 0 and
3732/// the outline runs along the axis there); refused otherwise.
3733fn polyhedron_shadow(corners: &[[f64; 3]], faces: &[Vec<usize>], through: bool) -> Result<Vec<ShadowPiece>, KernelRefusal> {
3734    let zs: Vec<f64> = corners.iter().map(|c| c[2]).collect();
3735    let (z_low, z_high) = (zs.iter().copied().fold(f64::INFINITY, f64::min), zs.iter().copied().fold(f64::NEG_INFINITY, f64::max));
3736    let scale = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(1.0f64, f64::max);
3737    // The hull's edges (from the faces' loops) and the faces beside each.
3738    let mut edge_faces: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
3739    for (f, face) in faces.iter().enumerate() {
3740        for k in 0..face.len() {
3741            let (i, j) = (face[k], face[(k + 1) % face.len()]);
3742            edge_faces.entry((i.min(j), i.max(j))).or_default().push(f);
3743        }
3744    }
3745    let mut edges: Vec<(usize, usize)> = edge_faces.keys().copied().collect();
3746    edges.sort_unstable();
3747    // Each face's plane in the axis frame: n · p = d.
3748    let planes: Vec<([f64; 3], f64)> = faces
3749        .iter()
3750        .map(|face| {
3751            let (a, b, c) = (corners[face[0]], corners[face[1]], corners[face[2]]);
3752            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]]);
3753            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]];
3754            (n, n[0] * a[0] + n[1] * a[1] + n[2] * a[2])
3755        })
3756        .collect();
3757    #[derive(Clone, Copy, PartialEq, Debug)]
3758    enum Source {
3759        /// The crossing of edge k.
3760        Edge(usize),
3761        /// The nearest point of face f's section line.
3762        Face(usize),
3763        /// The axis itself, where it passes through the tool.
3764        Axis,
3765    }
3766    let edge_at = |k: usize, z: f64| -> [f64; 2] {
3767        let (a, b) = (corners[edges[k].0], corners[edges[k].1]);
3768        let t = (z - a[2]) / (b[2] - a[2]);
3769        [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
3770    };
3771    let crossing = |z: f64| -> Vec<usize> {
3772        (0..edges.len()).filter(|&k| (corners[edges[k].0][2] - z) * (corners[edges[k].1][2] - z) < 0.0).collect()
3773    };
3774    let farthest = |z: f64| -> (Source, f64) {
3775        let mut best = (Source::Edge(0), f64::NEG_INFINITY);
3776        for k in crossing(z) {
3777            let p = edge_at(k, z);
3778            let r = p[0].hypot(p[1]);
3779            if r > best.1 {
3780                best = (Source::Edge(k), r);
3781            }
3782        }
3783        best
3784    };
3785    // The section polygon: edge crossings ordered by angle about their mean.
3786    let nearest = |z: f64| -> Result<(Source, f64), KernelRefusal> {
3787        let list = crossing(z);
3788        let points: Vec<[f64; 2]> = list.iter().map(|&k| edge_at(k, z)).collect();
3789        let m = points.len();
3790        if m < 3 {
3791            return Err(refuse("turn_shadow", "a section of the tool is not a polygon".into()));
3792        }
3793        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]);
3794        let mut order: Vec<usize> = (0..m).collect();
3795        order.sort_by(|&a, &b| {
3796            let (pa, pb) = (points[a], points[b]);
3797            (pa[1] - centre[1]).atan2(pa[0] - centre[0]).total_cmp(&(pb[1] - centre[1]).atan2(pb[0] - centre[0]))
3798        });
3799        let mut inside = true;
3800        let mut best = (Source::Edge(0), f64::INFINITY);
3801        for k in 0..m {
3802            let (ia, ib) = (order[k], order[(k + 1) % m]);
3803            let (a, b) = (points[ia], points[ib]);
3804            let d = [b[0] - a[0], b[1] - a[1]];
3805            if d[0] * (0.0 - a[1]) - d[1] * (0.0 - a[0]) < 0.0 {
3806                inside = false;
3807            }
3808            let length2 = d[0] * d[0] + d[1] * d[1];
3809            let t = -(a[0] * d[0] + a[1] * d[1]) / length2;
3810            let (source, r) = if t > 0.0 && t < 1.0 {
3811                let (ea, eb) = (edges[list[ia]], edges[list[ib]]);
3812                let shared = edge_faces[&ea].iter().find(|f| edge_faces[&eb].contains(f)).copied();
3813                let Some(face) = shared else {
3814                    return Err(refuse("turn_shadow", "a section side does not lie on one face".into()));
3815                };
3816                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
3817                (Source::Face(face), q[0].hypot(q[1]))
3818            } else {
3819                let q = if t <= 0.0 { a } else { b };
3820                (Source::Edge(list[if t <= 0.0 { ia } else { ib }]), q[0].hypot(q[1]))
3821            };
3822            if r < best.1 {
3823                best = (source, r);
3824            }
3825        }
3826        if inside {
3827            if !through {
3828                return Err(refuse("turn_shadow", "the turn's axis passes through the tool".into()));
3829            }
3830            return Ok((Source::Axis, 0.0));
3831        }
3832        Ok(best)
3833    };
3834    // ρ of a source at z, from its own geometry (smooth across the piece).
3835    let value = |source: Source, z: f64| -> f64 {
3836        match source {
3837            Source::Edge(k) => {
3838                let p = edge_at(k, z);
3839                p[0].hypot(p[1])
3840            }
3841            Source::Face(f) => {
3842                let (n, d) = planes[f];
3843                (d - n[2] * z).abs() / n[0].hypot(n[1])
3844            }
3845            Source::Axis => 0.0,
3846        }
3847    };
3848    // Breaks: corner heights, and where the farthest or nearest source changes.
3849    let mut heights: Vec<f64> = zs.clone();
3850    heights.sort_by(|a, b| a.total_cmp(b));
3851    heights.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * scale);
3852    let mut pieces_far: Vec<(f64, f64, Source)> = Vec::new();
3853    let mut pieces_near: Vec<(f64, f64, Source)> = Vec::new();
3854    for window in heights.windows(2) {
3855        let (za, zb) = (window[0], window[1]);
3856        let samples = 400;
3857        let inner = |k: usize| za + (zb - za) * (k as f64 + 0.5) / samples as f64;
3858        for near in [false, true] {
3859            let source_at = |z: f64| -> Result<Source, KernelRefusal> { Ok(if near { nearest(z)?.0 } else { farthest(z).0 }) };
3860            let mut runs: Vec<(f64, Source)> = vec![(za, source_at(inner(0))?)];
3861            for k in 1..samples {
3862                let (z0, z1) = (inner(k - 1), inner(k));
3863                let (s0, s1) = (source_at(z0)?, source_at(z1)?);
3864                // Two sources tied over the stretch (edges equally far from
3865                // the axis) are one piece of the outline.
3866                let tied = [z0, 0.5 * (z0 + z1), z1].iter().all(|&z| (value(s0, z) - value(s1, z)).abs() <= 1e-12 * scale);
3867                if s0 == s1 || tied {
3868                    continue;
3869                }
3870                // Where the source changes, by bisection (a side handing over
3871                // to its corner touches it, so their values do not cross).
3872                let (mut lo, mut hi) = (z0, z1);
3873                for _ in 0..200 {
3874                    let midz = 0.5 * (lo + hi);
3875                    if source_at(midz)? == s0 { lo = midz } else { hi = midz }
3876                }
3877                runs.push((0.5 * (lo + hi), s1));
3878            }
3879            let list = if near { &mut pieces_near } else { &mut pieces_far };
3880            for k in 0..runs.len() {
3881                let z_end = if k + 1 < runs.len() { runs[k + 1].0 } else { zb };
3882                list.push((runs[k].0, z_end, runs[k].1));
3883            }
3884        }
3885    }
3886    // Exact pieces: a pair's ρ(z) is a conic arc, a side's a segment.
3887    let piece = |source: Source, za: f64, zb: f64| -> Vec<ShadowPiece> {
3888        let (ra, rb) = (value(source, za), value(source, zb));
3889        if matches!(source, Source::Face(..) | Source::Axis) {
3890            return vec![vec![(ra, za, 1.0), (rb, zb, 1.0)]];
3891        }
3892        // ρ² = α z² + β z + γ; split so each arc turns little.
3893        let rho = |z: f64| value(source, z);
3894        // Differences kept inside the piece (an edge through the axis has a
3895        // corner in ρ at its end there).
3896        let (z_min, z_max) = (za.min(zb), za.max(zb));
3897        let slope = |z: f64| {
3898            let h = 1e-6 * (zb - za).abs().max(1e-300);
3899            let (zp, zm) = ((z + h).min(z_max), (z - h).max(z_min));
3900            (rho(zp) - rho(zm)) / (zp - zm)
3901        };
3902        let parts = 4;
3903        let mut out = Vec::new();
3904        for k in 0..parts {
3905            let (z0, z1) = (za + (zb - za) * k as f64 / parts as f64, za + (zb - za) * (k + 1) as f64 / parts as f64);
3906            let (a, b) = ((rho(z0), z0), (rho(z1), z1));
3907            // Straight (an edge meeting the axis): a segment.
3908            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);
3909            if bend <= 1e-12 * scale {
3910                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3911                continue;
3912            }
3913            let (ta, tb) = ((slope(z0), 1.0), (slope(z1), 1.0));
3914            // Tangent lines' intersection.
3915            let det = ta.0 * (-tb.1) - ta.1 * (-tb.0);
3916            if det.abs() < 1e-12 {
3917                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3918                continue;
3919            }
3920            let rhs = (b.0 - a.0, b.1 - a.1);
3921            let s = (rhs.0 * (-tb.1) - rhs.1 * (-tb.0)) / det;
3922            let c = (a.0 + ta.0 * s, a.1 + ta.1 * s);
3923            // Shoulder: the conic's point on the line from the chord's middle to c.
3924            let m = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
3925            let on = |u: f64| {
3926                let p = (m.0 + (c.0 - m.0) * u, m.1 + (c.1 - m.1) * u);
3927                p.0 - rho(p.1)
3928            };
3929            let (mut lo, mut hi) = (0.0, 1.0);
3930            let sign_lo = on(lo);
3931            for _ in 0..200 {
3932                let mid = 0.5 * (lo + hi);
3933                if (on(mid) > 0.0) == (sign_lo > 0.0) { lo = mid } else { hi = mid }
3934            }
3935            let u = 0.5 * (lo + hi);
3936            let weight = u / (1.0 - u);
3937            out.push(vec![(a.0, a.1, 1.0), (c.0, c.1, weight), (b.0, b.1, 1.0)]);
3938        }
3939        out
3940    };
3941    // Outline: up the near side, across the top, down the far side, across the bottom.
3942    let mut outline: Vec<ShadowPiece> = Vec::new();
3943    for &(za, zb, source) in &pieces_near {
3944        outline.extend(piece(source, za, zb));
3945    }
3946    let (near_top, far_top) = (value(pieces_near.last().expect("near").2, z_high), value(pieces_far.last().expect("far").2, z_high));
3947    if far_top - near_top > 1e-12 * scale {
3948        outline.push(vec![(near_top, z_high, 1.0), (far_top, z_high, 1.0)]);
3949    }
3950    for &(za, zb, source) in pieces_far.iter().rev() {
3951        for mut arc in piece(source, za, zb).into_iter().rev() {
3952            arc.reverse();
3953            outline.push(arc);
3954        }
3955    }
3956    let (near_bottom, far_bottom) = (value(pieces_near[0].2, z_low), value(pieces_far[0].2, z_low));
3957    if far_bottom - near_bottom > 1e-12 * scale {
3958        outline.push(vec![(far_bottom, z_low, 1.0), (near_bottom, z_low, 1.0)]);
3959    }
3960    // Snap consecutive ends together.
3961    for k in 0..outline.len() {
3962        let next = (k + 1) % outline.len();
3963        let end = *outline[k].last().expect("piece");
3964        outline[next][0] = (end.0, end.1, 1.0);
3965    }
3966    Ok(outline)
3967}
3968
3969/// A ball TURNED about an axis that passes through it. Its grazing circle (in
3970/// the plane of the axis and the centre) crosses the axis at two poles N and S;
3971/// the part beyond the axis turns inside the sweep, and near the axis the ends
3972/// overlap. So the sweep has three faces: the wall, the outer arc of that
3973/// circle turned (a spindle torus's outer part, pinched at N and S); the
3974/// ball's back at the start less the ball at the end; and its front at the end
3975/// less the ball at the start. The two caps meet along the far arc, from S to
3976/// N, of the circle where the two spheres meet. None when the motion or tool
3977/// is not of that kind.
3978fn ball_whole_turn_on() -> bool {
3979    crate::switch!("BREP_SWEEP_BALL_WHOLE_TURN", true)
3980}
3981
3982fn ball_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
3983    let [OutlinePiece::Arc { centre, radius, start, end }, OutlinePiece::Line { .. }] = meridian else { return Ok(None) };
3984    let (centre, r) = (*centre, *radius);
3985    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 {
3986        return Ok(None);
3987    }
3988    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
3989    let centre_tool = origin.add(w.scale(centre[1]));
3990    let turned = screw.omega * (screw.t1 - screw.t0);
3991    if turned.abs() >= TAU - 1e-9 {
3992        // `BREP_SWEEP_BALL_WHOLE_TURN` (default on; `=0` restores the refusal): a ball turned a whole
3993        // turn about an axis that misses it sweeps the torus its great circle
3994        // in the axis' half-plane turns: that circle, revolved about the axis.
3995        let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
3996        let unit = |p: Vec3| finite(p) && (p.length() - 1.0).abs() <= 1e-9;
3997        if ball_whole_turn_on() && turned.is_finite() && finite(radial) && finite(origin) && finite(axis) && unit(w) && finite(screw.a) && unit(screw.e) {
3998            // The tool's own frame must be one (as every route reads it), and
3999            // its meridian the half disc: the arc closed by the diameter back
4000            // from the arc's end to its start.
4001            radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
4002            let [_, OutlinePiece::Line { from, to }] = meridian else { return Ok(None) };
4003            let at = |angle: f64| [centre[0] + r * angle.cos(), centre[1] + r * angle.sin()];
4004            let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-12 * r;
4005            if !(near(*from, at(*end)) && near(*to, at(*start)) && from[0].abs() <= 1e-12 * r && to[0].abs() <= 1e-12 * r) {
4006                return Err(input("meridian", "the ball's meridian is not the half disc closed by its diameter on the axis".into()));
4007            }
4008            let e = screw.e;
4009            let off = centre_tool.sub(screw.a);
4010            let radial = off.sub(e.scale(off.dot(e)));
4011            // Whole only if the shortfall leaves no gap the ball's own size
4012            // would see: the arc it misses, out at the ball's far side.
4013            let gap = (TAU - turned.abs()).max(0.0) * (radial.length() + r);
4014            if radial.length() > r * (1.0 + 1e-9) && gap <= 1e-9 * r {
4015                let normal = frag(e.cross(radial).normalized(), "ball_turn")?;
4016                let circle = frag(crate::make_circle(centre_tool, normal, r), "ball_turn")?;
4017                return Ok(Some(frag(crate::revolve_profile_brep(&[circle], screw.a, e, TAU), "ball_turn")?));
4018            }
4019        }
4020        return Ok(None);
4021    }
4022    let e = screw.e.scale(screw.omega.signum()); // the sense the ball turns about
4023    let c0 = screw.apply(screw.t0, centre_tool);
4024    let c1 = screw.apply(screw.t1, centre_tool);
4025    let foot = |c: Vec3| screw.a.add(e.scale(c.sub(screw.a).dot(e)));
4026    let rho = c0.sub(foot(c0)).length();
4027    if rho >= r * (1.0 - 1e-9) || rho <= 1e-9 * r {
4028        return Ok(None);
4029    }
4030    let h0 = frag(c0.sub(foot(c0)).normalized(), "radial")?;
4031    let height = (r * r - rho * rho).sqrt();
4032    let (north, south) = (foot(c0).add(e.scale(height)), foot(c0).sub(e.scale(height)));
4033    // An arc from `from` turned about `axis` through `centre` by `angle`.
4034    let arc = |about: Vec3, k: Vec3, from: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
4035        let surface = frag(make_revolution(about, k, &frag(make_line(from, from.add(k)), "line")?, angle), "arc")?;
4036        frag(surface.iso_curve_v(0.0), "arc")
4037    };
4038    // The outer arc of the grazing circle, S -> N through c0 + r h0: in the
4039    // (h0, e) plane about c0, from angle -α to α through 0, α = atan2(height, -ρ).
4040    let alpha = height.atan2(-rho);
4041    let outer = arc(c0, h0.cross(e), south, 2.0 * alpha)?;
4042    let wall = frag(make_revolution(screw.a, e, &outer, turned.abs()), "wall")?;
4043    let outer_end = frag(wall.iso_curve_u(1.0), "wall_end")?;
4044    // The far arc where the spheres meet, S -> N beyond the axis.
4045    let mid = c0.add(c1).scale(0.5);
4046    let towards = frag(mid.sub(foot(mid)).normalized(), "bisector")?;
4047    let rho_mid = mid.sub(foot(mid)).length();
4048    let beta = height.atan2(rho_mid); // S and N seen from mid, off the far direction
4049    // From S at angle β − π (in the (towards, e) plane about mid) down through
4050    // π to N at π − β: the decreasing sense, about e × towards.
4051    let meet = arc(mid, e.cross(towards), south, 2.0 * beta)?;
4052    {
4053        // The arc must pass beyond the axis (its middle on the far side).
4054        let [d0, d1] = frag(meet.domain(), "domain")?;
4055        let middle = frag(meet.evaluate(0.5 * (d0 + d1)), "middle")?;
4056        if middle.sub(foot(middle)).dot(towards) > 0.0 {
4057            return Err(refuse("ball_across_axis", "the spheres' common circle runs the wrong way round".into()));
4058        }
4059    }
4060    // A trimmed sphere cap: a chart whose poles and seam lie where the cap is not.
4061    let cap = |c: Vec3, inward: Vec3, side: Vec3, other: Vec3| -> Result<(NurbsSurface, Box<dyn Fn(Vec3) -> Vec3>), KernelRefusal> {
4062        // South pole just off the far end of the grazing circle, on the removed
4063        // side (inside the other end's ball); the seam crosses the grazing
4064        // circle beyond the axis only.
4065        let toward_south = frag(inward.add(side.scale(-0.3)).normalized(), "pole")?;
4066        let polar = toward_south.scale(-1.0);
4067        let seam = frag(side.sub(polar.scale(side.dot(polar))).normalized(), "seam")?;
4068        for k in 0..=64 {
4069            // The seam's part on the cap's side of the grazing circle must lie
4070            // inside the other ball (where the cap is not).
4071            let a = PI * k as f64 / 64.0;
4072            let q = c.add(polar.scale(-r * a.cos())).add(seam.scale(r * a.sin()));
4073            if q.sub(c).dot(side) < 0.0 && q.sub(other).length() >= r * (1.0 - 1e-9) {
4074                return Err(refuse("ball_across_axis", "no seam place for a cap".into()));
4075            }
4076        }
4077        let south_pole = c.sub(polar.scale(r));
4078        if south_pole.sub(other).length() >= r * (1.0 - 1e-6) {
4079            return Err(refuse("ball_across_axis", "no pole place for a cap".into()));
4080        }
4081        let generatrix = arc(c, polar.scale(-1.0).cross(seam), south_pole, PI)?;
4082        let surface = frag(make_revolution(c, polar, &generatrix, TAU), "cap")?;
4083        let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
4084        let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
4085        let around = polar.cross(seam);
4086        let inverse = move |x: Vec3| -> Vec3 {
4087            let d = x.sub(c).scale(1.0 / r);
4088            let latitude = d.dot(polar).clamp(-1.0, 1.0).asin();
4089            let longitude = d.dot(around).atan2(d.dot(seam)).rem_euclid(TAU);
4090            Vec3::new(
4091                crate::circle_angle_to_parameter(spans_u, TAU, longitude),
4092                crate::circle_angle_to_parameter(spans_v, PI, latitude + 0.5 * PI),
4093                0.0,
4094            )
4095        };
4096        Ok((surface, Box::new(inverse)))
4097    };
4098    let moving0 = e.cross(h0);
4099    let h1 = frag(c1.sub(foot(c1)).normalized(), "radial")?;
4100    let moving1 = e.cross(h1);
4101    // The back cap at the start (its removed part near c0 − r h0 on the back);
4102    // the front cap at the end.
4103    let (back, back_inverse) = cap(c0, h0.scale(-1.0), moving0.scale(1.0), c1)?;
4104    let (front, front_inverse) = cap(c1, h1.scale(-1.0), moving1.scale(-1.0), c0)?;
4105    let (back_joints, front_joints) = (surface_joints(&back), surface_joints(&front));
4106    let pcurve = |inverse: &dyn Fn(Vec3) -> Vec3, curve: &NurbsCurve, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
4107        let [d0, d1] = frag(curve.domain(), "domain")?;
4108        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
4109        let uv: Vec<Vec3> = ts.iter().map(|&t| curve.evaluate(t).map(|x| inverse(x))).collect::<Result<_, _>>().map_err(|e| refuse("pcurve", e))?;
4110        if pcurve_joints_on() {
4111            // The two caps share their structure (one make_revolution each).
4112            let (ju, jv) = (&back_joints.0, &back_joints.1);
4113            debug_assert_eq!(back_joints, front_joints);
4114            let at = |t: f64| -> Result<[f64; 2], KernelRefusal> {
4115                let p = inverse(frag(curve.evaluate(t), "point")?);
4116                Ok([p.x, p.y])
4117            };
4118            if let Some(fitted) = jointed_pcurve(&ts, &uv, at, ju, jv, curve)? {
4119                return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
4120            }
4121        }
4122        let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "cap_pcurve")?;
4123        if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
4124    };
4125    let mut shell = Shell::new();
4126    let (vn, vs) = (shell.vertex(north), shell.vertex(south));
4127    let k0 = shell.edge(outer.clone(), vs, vn, false)?;
4128    let k1 = shell.edge(outer_end.clone(), vs, vn, false)?;
4129    let c = shell.edge(meet.clone(), vs, vn, false)?;
4130    let ds = shell.edge(frag(make_line(south, south), "point")?, vs, vs, true)?;
4131    let dn = shell.edge(frag(make_line(north, north), "point")?, vn, vn, true)?;
4132    // Wall: u turns, v runs S -> N; outward needs v the other way round the
4133    // circle's normal, so test and pick the loop's sense.
4134    let wall_outward = {
4135        let p = frag(wall.evaluate(0.5, 0.5), "probe")?;
4136        let su = frag(wall.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(wall.evaluate(0.5 - 1e-6, 0.5), "probe")?);
4137        let sv = frag(wall.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(wall.evaluate(0.5, 0.5 - 1e-6), "probe")?);
4138        su.cross(sv).dot(p.sub(foot(p))) > 0.0
4139    };
4140    let [g0, g1] = frag(outer.domain(), "domain")?;
4141    let wall_loop = vec![
4142        (ds, true, uv_line([0.0, g0], [1.0, g0])?),
4143        (k1, true, uv_line([1.0, g0], [1.0, g1])?),
4144        (dn, true, uv_line([1.0, g1], [0.0, g1])?),
4145        (k0, false, uv_line([0.0, g1], [0.0, g0])?),
4146    ];
4147    let reversed = |list: Vec<(u64, bool, NurbsCurve)>| -> Result<Vec<(u64, bool, NurbsCurve)>, KernelRefusal> {
4148        list.into_iter().rev().map(|(e, f, p)| Ok((e, !f, frag(p.reversed(), "reversed")?))).collect()
4149    };
4150    shell.face(wall.clone(), if wall_outward { wall_loop } else { reversed(wall_loop)? });
4151    // Caps: loop (grazing arc S -> N, then the meeting arc N -> S), sense by
4152    // the signed area of its parameters (the charts' u × v points outward).
4153    for (surface, inverse, k_edge, k_curve) in [(back, &back_inverse, k0, &outer), (front, &front_inverse, k1, &outer_end)] {
4154        let mut lp = vec![(k_edge, true, pcurve(inverse.as_ref(), k_curve, true)?), (c, false, pcurve(inverse.as_ref(), &meet, false)?)];
4155        let mut area = 0.0;
4156        for (_, _, pc) in &lp {
4157            let [d0, d1] = frag(pc.domain(), "domain")?;
4158            for j in 0..64 {
4159                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")?);
4160                area += a.x * b.y - b.x * a.y;
4161            }
4162        }
4163        if area < 0.0 {
4164            lp = reversed(lp)?;
4165        }
4166        shell.face(surface, lp);
4167    }
4168    let body = shell.solid();
4169    let issues = body.validate();
4170    if !issues.is_empty() {
4171        return Err(refuse("assembly", format!("the turned ball's sweep is not valid: {:?}", issues.first())));
4172    }
4173    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() } };
4174    check_single_pass(screw, &probe, &body, &std::collections::HashSet::new())?;
4175    Ok(Some(body))
4176}
4177
4178/// A frame riding a cubic Bézier curve (`control`, in a plane square to
4179/// `up`): its origin on the curve, its first axis along the curve's tangent,
4180/// `up` fixed. The tool is given in the frame at the curve's start and carried
4181/// by it over the whole curve.
4182#[derive(Clone, Copy, Debug)]
4183pub struct FrameCurve {
4184    pub control: [Vec3; 4],
4185    pub up: Vec3,
4186}
4187
4188/// The whole sweep of a solid of revolution carried by a frame along a
4189/// curve. In the riding frame the velocity field is the speed along the
4190/// tangent plus the turn about `up`, so the grazing loop moves on the tool with
4191/// the curve's curvature. It is split at sample times (its structure must not
4192/// change), each piece sampled exactly, and the walls lofted through those
4193/// samples (quintic both ways; the samples' count doubles until the wall is
4194/// within `LOFT_TARGET` of the exact loop at the times between). Caps are the tool's
4195/// back at the start and front at the end.
4196pub fn sweep_solid_along(tool: &SolidTool, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
4197    // An upright solid of revolution on a planar curve is translated by it:
4198    // its sweep is the planar distance to the curve within the tool's radius,
4199    // folds and crossings included (`BREP_SWEEP_UPRIGHT_SLOT`). With the
4200    // direct build on (`BREP_SWEEP_UPRIGHT_DIRECT`) the route answers only
4201    // where the general routes refuse and the curve may turn tighter than the
4202    // tool, built face by face; every sweep the general routes build is theirs
4203    // as before, and where the direct build declines their refusal stands.
4204    // With the direct build off the route takes every upright sweep.
4205    if crate::solid_sweep_upright::upright_slot_on() {
4206        if let Some(slot) = crate::solid_sweep_upright::upright_slot(tool, path) {
4207            if !crate::solid_sweep_upright::upright_direct_on() {
4208                return slot.solid();
4209            }
4210            let general = sweep_solid_along_general(tool, path);
4211            if general.is_err() && slot.turns_tighter() {
4212                if let Ok(solid) = slot.direct_solid() {
4213                    return Ok(solid);
4214                }
4215            }
4216            return general;
4217        }
4218    }
4219    sweep_solid_along_general(tool, path)
4220}
4221
4222/// [`sweep_solid_along`] by its general routes (the planar ring, the lofted
4223/// grazing loop), without the upright route.
4224fn sweep_solid_along_general(tool: &SolidTool, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
4225    // A ring on a planar curve, from its slices (`BREP_SWEEP_PLANAR_RING`).
4226    if let Some(ring) = crate::solid_sweep_planar_ring::planar_ring_on().then(|| crate::solid_sweep_planar_ring::planar_ring_sweep(tool, path)).flatten() {
4227        return ring;
4228    }
4229    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
4230    let base = path.control[0];
4231    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
4232        return Err(input("plane", "the curve is not in a plane square to up".into()));
4233    }
4234    let tangent = path.control[1].sub(base);
4235    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
4236    let start_tangent = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
4237    let frame = Frame { control: path.control, up, start_tangent };
4238    let (mut speed, mut rate, mut extent) = (0.0f64, 0.0f64, 0.0f64);
4239    let mut previous = 0.0;
4240    for k in 0..=512 {
4241        let t = k as f64 / 512.0;
4242        let first = frame.first(t);
4243        if first.length() <= 1e-12 {
4244            return Err(input("tangent", "the curve stops (zero tangent)".into()));
4245        }
4246        speed = speed.max(first.length());
4247        rate = rate.max(frame.angle_rate(t).abs());
4248        extent = extent.max(frame.point(t).sub(base).length());
4249        let angle = frame.angle(t);
4250        if (angle - previous).abs() > 0.5 {
4251            return Err(refuse("frame_turns", "the frame turns half way round".into()));
4252        }
4253        previous = angle;
4254    }
4255    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,
4256        loop_samples: LOFT_SAMPLES, extent };
4257    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
4258        return Err(refuse("along_tool", "a frame along a curve carries a solid of revolution only".into()));
4259    };
4260    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
4261    // The splits name their pieces by angle about the tool's axis from its
4262    // radial direction: a grazing angle passing that reference renames them,
4263    // so try a few references.
4264    let mut last = None;
4265    for k in 0..8 {
4266        let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
4267        match lofted(&screw, *axis_origin, axis, reference, meridian) {
4268            Err(error) if refused_as(&error) == Some("loft_structure") => last = Some(error),
4269            other => return other,
4270        }
4271    }
4272    Err(last.expect("tried"))
4273}
4274
4275/// The whole sweep of a prism carried by a frame along a planar curve (its
4276/// axis along the frame's up): the prism `outline` (a convex polygon in the
4277/// start frame: first coordinate along the start tangent, second along
4278/// up × tangent) between `from` and `to` along up. The motion is planar, so the
4279/// sweep is the plane region the moving outline covers, extruded. That region
4280/// is found exactly: its boundary lies on the outline's corner paths, the paths
4281/// of each edge's grazing point (where the edge's normal is square to the
4282/// velocity), and the outline's edges at the two ends; these are split where
4283/// they meet, and a piece is kept where one side of it is covered and the other
4284/// not (folds, where a corner digs past a side, come out right).
4285pub fn sweep_prism_along(outline: &[[f64; 2]], from: f64, to: f64, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
4286    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
4287    let base = path.control[0];
4288    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
4289        return Err(input("plane", "the curve is not in a plane square to up".into()));
4290    }
4291    let tangent = path.control[1].sub(base);
4292    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
4293    let e1 = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
4294    let e2 = up.cross(e1);
4295    let frame = Frame { control: path.control, up, start_tangent: e1 };
4296    // The frame in plane coordinates: origin c(s), turned by φ(s).
4297    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
4298    let pose = |s: f64| (flat(frame.point(s)), frame.angle(s));
4299    let rates = |s: f64| {
4300        let first = frame.first(s);
4301        ([first.dot(e1), first.dot(e2)], frame.angle_rate(s))
4302    };
4303    prism_region_sweep(outline, from, to, base, e1, e2, up, &pose, &rates, false)
4304}
4305
4306/// The whole sweep of a prism (the convex polygon `outline` in the plane
4307/// through `base` spanned by `e1`, `e2`, between `from` and `to` along `up`)
4308/// under a planar rigid motion: at s ∈ [0, 1] a point q of the plane (in the
4309/// tool's own coordinates) is at origin(s) + R(angle(s)) q, `pose` giving
4310/// (origin, angle) and `rates` their derivatives in s. The sweep is the plane
4311/// region the moving outline covers, extruded. That region is found exactly:
4312/// its boundary lies on the outline's corner paths, the paths of each edge's
4313/// grazing point (where the edge's normal is square to the velocity), and,
4314/// unless the motion is `closed` (it ends where it starts), the outline's
4315/// edges at the two ends; these are split where they meet or cross
4316/// themselves, and a piece is kept where one side of it is covered and the
4317/// other not. The region may have holes.
4318#[allow(clippy::too_many_arguments)]
4319pub fn prism_region_sweep(
4320    outline: &[[f64; 2]],
4321    from: f64,
4322    to: f64,
4323    base: Vec3,
4324    e1: Vec3,
4325    e2: Vec3,
4326    up: Vec3,
4327    pose: &dyn Fn(f64) -> ([f64; 2], f64),
4328    rates: &dyn Fn(f64) -> ([f64; 2], f64),
4329    closed: bool,
4330) -> Result<BrepSolid, KernelRefusal> {
4331    if outline.len() < 3 || !(to > from) {
4332        return Err(input("prism", "a prism needs three corners and a positive height".into()));
4333    }
4334    // Counter-clockwise, convex.
4335    let n = outline.len();
4336    let mut corners = outline.to_vec();
4337    let area: f64 = (0..n).map(|k| corners[k][0] * corners[(k + 1) % n][1] - corners[(k + 1) % n][0] * corners[k][1]).sum();
4338    if area < 0.0 {
4339        corners.reverse();
4340    }
4341    for k in 0..n {
4342        let (a, b, c) = (corners[k], corners[(k + 1) % n], corners[(k + 2) % n]);
4343        if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) <= 0.0 {
4344            return Err(input("prism", "the outline is not convex".into()));
4345        }
4346    }
4347    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
4348    let place = |s: f64, q: [f64; 2]| -> [f64; 2] {
4349        let (o, angle) = pose(s);
4350        let (sn, cs) = angle.sin_cos();
4351        [o[0] + cs * q[0] - sn * q[1], o[1] + sn * q[0] + cs * q[1]]
4352    };
4353    let local = |s: f64, p: [f64; 2]| -> [f64; 2] {
4354        let (o, angle) = pose(s);
4355        let (sn, cs) = angle.sin_cos();
4356        let d = [p[0] - o[0], p[1] - o[1]];
4357        [cs * d[0] + sn * d[1], -sn * d[0] + cs * d[1]]
4358    };
4359    // Edges: outward normals and offsets in the start frame.
4360    let edges: Vec<([f64; 2], f64)> = (0..n)
4361        .map(|k| {
4362            let (a, b) = (corners[k], corners[(k + 1) % n]);
4363            let d = [b[0] - a[0], b[1] - a[1]];
4364            let length = d[0].hypot(d[1]);
4365            let normal = [d[1] / length, -d[0] / length];
4366            (normal, normal[0] * a[0] + normal[1] * a[1])
4367        })
4368        .collect();
4369    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);
4370    // Is p covered at some time? The least signed distance over the motion.
4371    let depth = |p: [f64; 2]| -> f64 {
4372        let samples = 2000;
4373        let f = |s: f64| inside(local(s, p));
4374        let mut best = (f64::INFINITY, 0usize);
4375        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
4376        for (k, &v) in values.iter().enumerate() {
4377            if v < best.0 {
4378                best = (v, k);
4379            }
4380        }
4381        // Refine every local minimum near the least.
4382        let mut least = best.0;
4383        for k in 0..=samples {
4384            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
4385            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
4386            if values[k] <= left && values[k] <= right && values[k] < best.0 + 1e-3 * scale {
4387                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);
4388                for _ in 0..80 {
4389                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4390                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
4391                }
4392                least = least.min(f(0.5 * (lo + hi)));
4393            }
4394        }
4395        least
4396    };
4397    // Candidate boundary paths, each a map [0, 1] -> plane.
4398    #[derive(Clone, Copy)]
4399    enum Path {
4400        Corner(usize),
4401        /// Edge k's grazing point over the times [s0, s1].
4402        Graze(usize, f64, f64),
4403        /// Edge k at the start (false) or end (true).
4404        End(usize, bool),
4405    }
4406    // Where along edge k's line (0 at its start corner, 1 at its end) the
4407    // grazing point is at s, on the edge or beyond it.
4408    let graze_at = |k: usize, s: f64| -> Option<f64> {
4409        // Along edge k at x (in the tool's coordinates) the velocity's part
4410        // along the edge's normal n is w·n + φ' (ẑ × x)·n, w the origin's
4411        // velocity read in the tool's frame.
4412        let (a, b) = (corners[k], corners[(k + 1) % n]);
4413        let (nn, _) = edges[k];
4414        let (velocity, rate) = rates(s);
4415        let (sn, cs) = pose(s).1.sin_cos();
4416        let w = [cs * velocity[0] + sn * velocity[1], -sn * velocity[0] + cs * velocity[1]];
4417        let along = w[0] * nn[0] + w[1] * nn[1];
4418        let rot = |x: [f64; 2]| -x[1] * nn[0] + x[0] * nn[1]; // (ẑ × x)·n
4419        // An edge the origin moves along grazes where (ẑ × x)·n = 0 whatever
4420        // the turning rate (also where it is zero, at an inflection).
4421        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)) };
4422        if ga == gb {
4423            return None;
4424        }
4425        Some(ga / (ga - gb))
4426    };
4427    let graze_point = |k: usize, s: f64| -> Option<f64> { graze_at(k, s).filter(|&u| u > 0.0 && u < 1.0) };
4428    let mut paths: Vec<Path> = (0..n).map(Path::Corner).collect();
4429    // Where a grazing point enters or leaves its edge it is at a corner:
4430    // (that corner, the time), a place its path is split at.
4431    let mut junctions: Vec<(usize, f64)> = Vec::new();
4432    for k in 0..n {
4433        // Where along the motion edge k has a grazing point inside it, each
4434        // run's ends found where the point passes a corner.
4435        let steps = 2000;
4436        let mut run: Option<f64> = None;
4437        let mut passes = |inside: f64, outside: f64| -> f64 {
4438            let (mut a, mut b) = (inside, outside);
4439            for _ in 0..80 {
4440                let mid = 0.5 * (a + b);
4441                if graze_point(k, mid).is_some() { a = mid } else { b = mid }
4442            }
4443            let corner = if graze_at(k, a).is_some_and(|u| u < 0.5) { k } else { (k + 1) % n };
4444            junctions.push((corner, a));
4445            a
4446        };
4447        for j in 0..=steps {
4448            let s = j as f64 / steps as f64;
4449            let on = graze_point(k, s).is_some();
4450            match (on, run) {
4451                (true, None) => run = Some(if j == 0 { s } else { passes(s, s - 1.0 / steps as f64) }),
4452                (false, Some(s0)) => {
4453                    paths.push(Path::Graze(k, s0, passes(s - 1.0 / steps as f64, s)));
4454                    run = None;
4455                }
4456                _ => {}
4457            }
4458        }
4459        if let Some(s0) = run {
4460            paths.push(Path::Graze(k, s0, 1.0));
4461        }
4462        if !closed {
4463            paths.push(Path::End(k, false));
4464            paths.push(Path::End(k, true));
4465        }
4466    }
4467    let eval = |path: Path, t: f64| -> [f64; 2] {
4468        match path {
4469            Path::Corner(k) => place(t, corners[k]),
4470            Path::Graze(k, s0, s1) => {
4471                let s = s0 + (s1 - s0) * t;
4472                let u = graze_at(k, s).map_or(0.5, |u| u.clamp(0.0, 1.0));
4473                let (a, b) = (corners[k], corners[(k + 1) % n]);
4474                place(s, [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u])
4475            }
4476            Path::End(k, at_end) => {
4477                let (a, b) = (corners[k], corners[(k + 1) % n]);
4478                place(if at_end { 1.0 } else { 0.0 }, [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t])
4479            }
4480        }
4481    };
4482    let count = paths.len();
4483    region_from_paths(
4484        count,
4485        &|index: usize, t: f64| eval(paths[index], t),
4486        &|index: usize| matches!(paths[index], Path::End(..)),
4487        &|_: usize| closed,
4488        &junctions,
4489        &depth,
4490        scale,
4491        (base, e1, e2, up),
4492        (from, to),
4493    )
4494}
4495
4496/// Everything a tube (the ball of `radius` swept along the curve
4497/// `centreline(s)`, s ∈ [0, 1], its ends included) passes through as it slides
4498/// by `slide`, inside the slab `slab[0] ≤ (x − slab_origin)·n ≤ slab[1]` (`n` =
4499/// `slab_normal` normalised), which the tube must cross wholly: before the
4500/// slab at the start, past it at the end (checked at 8001 points of the
4501/// centreline, with a margin of the longest step between them). The
4502/// returned prism along the slide agrees with the sweep inside the slab; the
4503/// caller cuts a workpiece that lies within it.
4504///
4505/// The centreline must be resolved by its samples (as every path of the plane
4506/// region arrangement is): smooth, its height changing between two of the
4507/// 8001 checking samples by no more than the step between them, so that the
4508/// samples bound it. A curve that wanders between samples is outside this
4509/// contract.
4510///
4511/// Why a prism: a point x of the slab is in the sweep iff the line through x
4512/// along the slide meets the tube. If it does, `n·` grows along the line, so
4513/// its topmost point y of the starting tube lies before x, and y + slide (a
4514/// point of the final tube) past it: x − y is a multiple of the slide in
4515/// [0, 1). So the sweep in the slab is the slab's part of the prism over the
4516/// tube's shadow along the slide: in the plane square to it the union of the
4517/// discs of `radius` about the shadow γ of the centreline. That region is
4518/// bounded by γ's two offset curves (each disc's grazing points, γ ± radius
4519/// along its normal) and the end discs' circles, built exactly by the plane
4520/// region arrangement of [`sweep_prism_along`].
4521pub fn sweep_tube_slid_across(
4522    centreline: &dyn Fn(f64) -> Vec3,
4523    radius: f64,
4524    slide: Vec3,
4525    slab_origin: Vec3,
4526    slab_normal: Vec3,
4527    slab: [f64; 2],
4528) -> Result<BrepSolid, KernelRefusal> {
4529    if !(radius.is_finite() && radius > 0.0) {
4530        return Err(input("tube_radius", "the tube's radius must be positive".into()));
4531    }
4532    let up = slide.normalized().map_err(|_| input("slide", "the slide has no length".into()))?;
4533    let normal = slab_normal.normalized().map_err(|_| input("slab", "the slab's normal has no direction".into()))?;
4534    if !(slab[1] > slab[0]) || up.dot(normal).abs() < 1e-9 {
4535        return Err(input("slab", "the slab must have thickness and the slide must cross it".into()));
4536    }
4537    // Orient so the slide runs up the slab's normal.
4538    let (normal, slab) = if up.dot(normal) > 0.0 { (normal, slab) } else { (normal.scale(-1.0), [-slab[1], -slab[0]]) };
4539    let points: Vec<Vec3> = (0..=8000).map(|k| centreline(k as f64 / 8000.0)).collect();
4540    if points.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) {
4541        return Err(input("centreline", "the centreline has a point that is not finite".into()));
4542    }
4543    let step = points.windows(2).map(|w| w[1].sub(w[0]).length()).fold(0.0f64, f64::max);
4544    let heights: Vec<f64> = points.iter().map(|q| q.sub(slab_origin).dot(normal)).collect();
4545    let (low, high) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &h| (a.min(h), b.max(h)));
4546    let rise = slide.dot(normal);
4547    if !(high + radius + step < slab[0] && low - radius - step + rise > slab[1]) {
4548        return Err(refuse("tube_slab", "the tube does not pass wholly through the slab (it starts or ends within reach of it)".into()));
4549    }
4550    let e1 = {
4551        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) };
4552        seed.sub(up.scale(seed.dot(up))).normalized().map_err(|_| input("slide", "no frame".into()))?
4553    };
4554    let e2 = up.cross(e1);
4555    // The plane's origin on the centreline itself, so that every tolerance
4556    // reads the tube's own size, wherever it lies.
4557    let base = points[0];
4558    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
4559    let centre = |s: f64| -> [f64; 2] { flat(centreline(s)) };
4560    let velocity = |s: f64| -> [f64; 2] {
4561        let h = 1e-7;
4562        let (a, b) = ((s - h).max(0.0), (s + h).min(1.0));
4563        let (p, q) = (centre(a), centre(b));
4564        [(q[0] - p[0]) / (b - a), (q[1] - p[1]) / (b - a)]
4565    };
4566    // The shadow must keep moving (a disc standing still has no grazing points).
4567    for k in 0..=2000 {
4568        let w = velocity(k as f64 / 2000.0);
4569        if w[0].hypot(w[1]) < 1e-9 * (1.0 + radius) {
4570            return Err(refuse("tube_shadow", "the tube's shadow along the slide stops (its centreline runs along the slide)".into()));
4571        }
4572    }
4573    // Tolerances read the tube's radius (a probe beside a boundary must stay
4574    // within the tube), never more than its extent; a tube longer than 1e6
4575    // radii is beyond what the coordinates resolve at that size.
4576    let extent = (0..=64).map(|k| { let c = centre(k as f64 / 64.0); c[0].hypot(c[1]) }).fold(radius, f64::max);
4577    if extent > 1e6 * radius {
4578        return Err(refuse("tube_shadow", "the tube is too long for its radius (over a million radii)".into()));
4579    }
4580    let scale = extent.min(1e3 * radius);
4581    // Paths: the two offset curves, then the two end circles.
4582    let eval = |index: usize, t: f64| -> [f64; 2] {
4583        match index {
4584            0 | 1 => {
4585                let c = centre(t);
4586                let w = velocity(t);
4587                let length = w[0].hypot(w[1]);
4588                let side = if index == 0 { 1.0 } else { -1.0 };
4589                [c[0] - side * radius * w[1] / length, c[1] + side * radius * w[0] / length]
4590            }
4591            _ => {
4592                let c = centre(if index == 2 { 0.0 } else { 1.0 });
4593                let angle = TAU * t;
4594                [c[0] + radius * angle.cos(), c[1] + radius * angle.sin()]
4595            }
4596        }
4597    };
4598    // Inside: nearer than `radius` to the shadow at some time.
4599    let depth = |p: [f64; 2]| -> f64 {
4600        let samples = 4000;
4601        let f = |s: f64| { let c = centre(s); (p[0] - c[0]).hypot(p[1] - c[1]) - radius };
4602        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
4603        let mut least = values.iter().cloned().fold(f64::INFINITY, f64::min);
4604        for k in 0..=samples {
4605            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
4606            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
4607            if values[k] <= left && values[k] <= right && values[k] < least + 1e-3 * scale {
4608                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);
4609                for _ in 0..80 {
4610                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4611                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
4612                }
4613                least = least.min(f(0.5 * (lo + hi)));
4614            }
4615        }
4616        least
4617    };
4618    // The prism spans the slab's crossing of every line through the region:
4619    // from below the starting tube to past the final one, along the slide.
4620    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)));
4621    let margin = radius + step + 1e-3 * scale;
4622    // Each offset curve ends on its end circle, tangent to it there (both run
4623    // along the velocity), which no crossing test finds: split the circles at
4624    // those points (the angles of ±the normal there).
4625    let mut touches: Vec<(usize, f64)> = Vec::new();
4626    for (circle, s) in [(2usize, 0.0f64), (3, 1.0)] {
4627        let w = velocity(s);
4628        for side in [1.0f64, -1.0] {
4629            let angle = (side * w[0]).atan2(-side * w[1]);
4630            touches.push((circle, angle.rem_euclid(TAU) / TAU));
4631        }
4632    }
4633    region_from_paths(
4634        4,
4635        &eval,
4636        &|_| false,
4637        &|index| index >= 2,
4638        &touches,
4639        &depth,
4640        scale,
4641        (base, e1, e2, up),
4642        (a0 - margin, a1 + slide.length() + margin),
4643    )
4644}
4645
4646/// The crossing search's box culling in [`region_from_paths`]
4647/// (`BREP_SWEEP_REGION_CROSS_BOXES`, default on; `=0` visits every segment
4648/// pair, the same crossings found more slowly: square-on-a-planet-carrier
4649/// tests 74.4M pairs without it, 0.75M with it, for the same 74 Newton runs).
4650fn region_cross_boxes_on() -> bool {
4651    crate::switch!("BREP_SWEEP_REGION_CROSS_BOXES", true)
4652}
4653
4654/// The plane region bounded by pieces of the candidate `count` paths (each
4655/// `eval(index, t)`, t ∈ [0, 1]), extruded along `up` from `heights.0` to
4656/// `heights.1`: the paths are split where they cross each other or
4657/// themselves (and at `extra_cuts`), a piece is kept where `depth` (negative
4658/// inside the region) reads one side covered and the other not, and the kept
4659/// pieces chain into one outer loop and its holes. `straight_path(index)`: the
4660/// path is a segment (built as a line); `closed_path(index)`: its two ends
4661/// meet (neighbours for the self-crossing test).
4662#[allow(clippy::too_many_arguments)]
4663fn region_from_paths(
4664    count: usize,
4665    eval: &dyn Fn(usize, f64) -> [f64; 2],
4666    straight_path: &dyn Fn(usize) -> bool,
4667    closed_path: &dyn Fn(usize) -> bool,
4668    extra_cuts: &[(usize, f64)],
4669    depth: &dyn Fn([f64; 2]) -> f64,
4670    scale: f64,
4671    frame: (Vec3, Vec3, Vec3, Vec3),
4672    heights: (f64, f64),
4673) -> Result<BrepSolid, KernelRefusal> {
4674    let (base, e1, e2, up) = frame;
4675    let (from, to) = heights;
4676    // Split parameters: mutual crossings (polyline, then Newton), and each
4677    // path's ends lying on another.
4678    let m = 400;
4679    let polylines: Vec<Vec<[f64; 2]>> = (0..count).map(|p| (0..=m).map(|i| eval(p, i as f64 / m as f64)).collect()).collect();
4680    let mut cuts: Vec<Vec<f64>> = vec![vec![0.0, 1.0]; count];
4681    let tol = 1e-10 * scale;
4682    // Under `BREP_SWEEP_REGION_CROSS_BOXES` the segment pairs are visited
4683    // chunk by chunk (16 segments each), a chunk pair only where their boxes,
4684    // grown by 1e-6 of the scale and by the pair test's own reach past a
4685    // segment's ends, overlap: a crossing the test takes lies in both boxes,
4686    // and none is missed. The cuts are
4687    // sorted after, so the order they are found in does not matter.
4688    const CHUNK: usize = 16;
4689    let boxed = region_cross_boxes_on();
4690    let chunks = (m + CHUNK - 1) / CHUNK;
4691    let grow = 1e-6 * scale;
4692    let boxes: Vec<Vec<[f64; 4]>> = polylines
4693        .iter()
4694        .filter(|_| boxed)
4695        .map(|line| {
4696            (0..chunks)
4697                .map(|c| {
4698                    let (lo, hi) = (c * CHUNK, ((c + 1) * CHUNK).min(m));
4699                    let b = line[lo..=hi].iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);
4700                    // The pair test takes a crossing up to 1e-9 of a segment's
4701                    // length past its end: grow by twice that of the chunk's
4702                    // longest segment, so every crossing it takes lies in both
4703                    // segments' boxes.
4704                    let longest = line[lo..=hi].windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).fold(0.0f64, f64::max);
4705                    let g = grow + 2e-9 * longest;
4706                    [b[0] - g, b[1] - g, b[2] + g, b[3] + g]
4707                })
4708                .collect()
4709        })
4710        .collect();
4711    let overlap = |a: &[f64; 4], b: &[f64; 4]| a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3];
4712    for a in 0..count {
4713        for b in a..count {
4714            // One segment pair: a crossing of the polylines, polished by Newton on the exact paths.
4715            let mut test = |i: usize, j: usize| {
4716                    // A path against itself: only where it crosses over
4717                    // (stretches apart along it; a closed path's ends are
4718                    // neighbours too).
4719                    if a == b && (j < i + 3 || (closed_path(a) && i < 3 && j + 3 > m)) {
4720                        return;
4721                    }
4722                    let (p0, p1, q0, q1) = (polylines[a][i], polylines[a][i + 1], polylines[b][j], polylines[b][j + 1]);
4723                    let d1 = [p1[0] - p0[0], p1[1] - p0[1]];
4724                    let d2 = [q1[0] - q0[0], q1[1] - q0[1]];
4725                    let det = d1[0] * d2[1] - d1[1] * d2[0];
4726                    if det.abs() < 1e-300 {
4727                        return;
4728                    }
4729                    let r = [q0[0] - p0[0], q0[1] - p0[1]];
4730                    let (x, y) = ((r[0] * d2[1] - r[1] * d2[0]) / det, (r[0] * d1[1] - r[1] * d1[0]) / det);
4731                    if !(-1e-9..=1.0 + 1e-9).contains(&x) || !(-1e-9..=1.0 + 1e-9).contains(&y) {
4732                        return;
4733                    }
4734                    // Newton on the exact paths.
4735                    let (mut ta, mut tb) = ((i as f64 + x) / m as f64, (j as f64 + y) / m as f64);
4736                    for _ in 0..50 {
4737                        let (pa, pb) = (eval(a, ta), eval(b, tb));
4738                        let h = 1e-7;
4739                        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] };
4740                        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] };
4741                        let f = [pa[0] - pb[0], pa[1] - pb[1]];
4742                        let det = -da[0] * db[1] + da[1] * db[0];
4743                        if det.abs() < 1e-300 {
4744                            break;
4745                        }
4746                        let dta = (-f[0] * db[1] + f[1] * db[0]) / det;
4747                        let dtb = (da[0] * f[1] - da[1] * f[0]) / det;
4748                        ta = (ta - dta).clamp(0.0, 1.0);
4749                        tb = (tb - dtb).clamp(0.0, 1.0);
4750                        if dta.abs() + dtb.abs() < 1e-15 {
4751                            break;
4752                        }
4753                    }
4754                    let (pa, pb) = (eval(a, ta), eval(b, tb));
4755                    if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < tol && !(a == b && (ta - tb).abs() < 1.0 / m as f64) {
4756                        cuts[a].push(ta);
4757                        cuts[b].push(tb);
4758                    }
4759            };
4760            if boxed {
4761                // Only the segment pairs of chunks whose boxes overlap.
4762                for ca in 0..chunks {
4763                    for cb in 0..chunks {
4764                        if !overlap(&boxes[a][ca], &boxes[b][cb]) {
4765                            continue;
4766                        }
4767                        for i in ca * CHUNK..((ca + 1) * CHUNK).min(m) {
4768                            for j in cb * CHUNK..((cb + 1) * CHUNK).min(m) {
4769                                test(i, j);
4770                            }
4771                        }
4772                    }
4773                }
4774            } else {
4775                for i in 0..m {
4776                    for j in 0..m {
4777                        test(i, j);
4778                    }
4779                }
4780            }
4781        }
4782    }
4783    // Extra splits the caller names (a corner's path where a grazing point passes it).
4784    for &(path, t) in extra_cuts {
4785        cuts[path].push(t);
4786    }
4787    for c in &mut cuts {
4788        c.sort_by(|x, y| x.total_cmp(y));
4789        c.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
4790    }
4791    // Pieces on the boundary: covered on exactly one side.
4792    struct Piece {
4793        path: usize,
4794        t0: f64,
4795        t1: f64,
4796    }
4797    let eps = 1e-7 * scale;
4798    let mut pieces: Vec<Piece> = Vec::new();
4799    for (index, c) in cuts.iter().enumerate() {
4800        for w in c.windows(2) {
4801            let (t0, t1) = (w[0], w[1]);
4802            if t1 - t0 < 1e-9 {
4803                continue;
4804            }
4805            let (pa, pb) = (eval(index, t0), eval(index, t1));
4806            if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < 1e-9 * scale {
4807                continue;
4808            }
4809            let tm = 0.5 * (t0 + t1);
4810            let (p, q) = (eval(index, tm), eval(index, (tm + 1e-6).min(1.0)));
4811            let d = [q[0] - p[0], q[1] - p[1]];
4812            let length = d[0].hypot(d[1]);
4813            if length == 0.0 {
4814                continue;
4815            }
4816            let left = [p[0] - d[1] / length * eps, p[1] + d[0] / length * eps];
4817            let right = [p[0] + d[1] / length * eps, p[1] - d[0] / length * eps];
4818            let (l, r) = (depth(left) < -1e-12 * scale, depth(right) < -1e-12 * scale);
4819            match (l, r) {
4820                (true, false) => pieces.push(Piece { path: index, t0, t1 }),
4821                (false, true) => pieces.push(Piece { path: index, t0: t1, t1: t0 }),
4822                _ => {}
4823            }
4824        }
4825    }
4826    // Chain into loops, the region on their left (the outer one runs
4827    // counter-clockwise, a hole's clockwise).
4828    if pieces.is_empty() {
4829        return Err(refuse("prism_along", "no boundary found".into()));
4830    }
4831    let mut used = vec![false; pieces.len()];
4832    let mut loops: Vec<Vec<usize>> = Vec::new();
4833    while let Some(first) = (0..pieces.len()).find(|&k| !used[k]) {
4834        let mut order = vec![first];
4835        used[first] = true;
4836        loop {
4837            let last = &pieces[*order.last().expect("order")];
4838            let end = eval(last.path, last.t1);
4839            let start = eval(pieces[order[0]].path, pieces[order[0]].t0);
4840            if (end[0] - start[0]).hypot(end[1] - start[1]) < 1e-8 * scale {
4841                break;
4842            }
4843            let next = (0..pieces.len()).filter(|&k| !used[k]).min_by(|&x, &y| {
4844                let (px, py) = (eval(pieces[x].path, pieces[x].t0), eval(pieces[y].path, pieces[y].t0));
4845                (px[0] - end[0]).hypot(px[1] - end[1]).total_cmp(&(py[0] - end[0]).hypot(py[1] - end[1]))
4846            });
4847            let Some(next) = next else {
4848                return Err(refuse("prism_along", "the boundary does not close".into()));
4849            };
4850            let p = eval(pieces[next].path, pieces[next].t0);
4851            if (p[0] - end[0]).hypot(p[1] - end[1]) > 1e-8 * scale {
4852                return Err(refuse("prism_along", format!("the boundary does not close (gap {:e})", (p[0] - end[0]).hypot(p[1] - end[1]))));
4853            }
4854            used[next] = true;
4855            order.push(next);
4856        }
4857        loops.push(order);
4858    }
4859    // The outer loop first: the one of greatest area.
4860    let area_of = |order: &Vec<usize>| -> f64 {
4861        let mut points: Vec<[f64; 2]> = Vec::new();
4862        for &k in order {
4863            let piece = &pieces[k];
4864            for i in 0..32 {
4865                points.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 32.0));
4866            }
4867        }
4868        (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
4869    };
4870    let areas: Vec<f64> = loops.iter().map(area_of).collect();
4871    let outer = (0..loops.len()).max_by(|&x, &y| areas[x].abs().total_cmp(&areas[y].abs())).expect("loops");
4872    if areas[outer] <= 0.0 || (0..loops.len()).any(|k| k != outer && areas[k] >= 0.0) {
4873        return Err(refuse("prism_along", "the swept region is not one region with holes".into()));
4874    }
4875    loops.swap(0, outer);
4876    // Plane curves of the loops, then the extrusion.
4877    let world = |q: [f64; 2], h: f64| base.add(e1.scale(q[0])).add(e2.scale(q[1])).add(up.scale(h));
4878    let mut shell = Shell::new();
4879    let mut top_loops = Vec::with_capacity(loops.len());
4880    let mut bottom_loops = Vec::with_capacity(loops.len());
4881    let mut extent: Vec<[f64; 2]> = Vec::new();
4882    for order in &loops {
4883        let mut loop_points: Vec<[f64; 2]> = order.iter().map(|&k| eval(pieces[k].path, pieces[k].t0)).collect();
4884        loop_points.push(loop_points[0]);
4885        let count = order.len();
4886        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();
4887        let mut bottom_e = Vec::with_capacity(count);
4888        let mut top_e = Vec::with_capacity(count);
4889        let mut curves2d = Vec::with_capacity(count);
4890        for (slot, &k) in order.iter().enumerate() {
4891            let piece = &pieces[k];
4892            let straight = straight_path(piece.path);
4893            let next = (slot + 1) % count;
4894            for i in 0..=16 {
4895                extent.push(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * i as f64 / 16.0));
4896            }
4897            let curve_at = |h: f64| -> Result<NurbsCurve, KernelRefusal> {
4898                if straight {
4899                    return frag(make_line(world(loop_points[slot], h), world(loop_points[next], h)), "line");
4900                }
4901                let samples = 192;
4902                let ts: Vec<f64> = (0..=samples).map(|i| i as f64 / samples as f64).collect();
4903                let mut points: Vec<Vec3> = ts.iter().map(|&t| world(eval(piece.path, piece.t0 + (piece.t1 - piece.t0) * t), h)).collect();
4904                points[0] = world(loop_points[slot], h);
4905                points[samples] = world(loop_points[next], h);
4906                frag(crate::interpolate_curve(&points, 5, &ts), "plane_path")
4907            };
4908            let (cb, ct) = (curve_at(from)?, curve_at(to)?);
4909            bottom_e.push(shell.edge(cb.clone(), bottom_v[slot], bottom_v[next], false)?);
4910            top_e.push(shell.edge(ct.clone(), top_v[slot], top_v[next], false)?);
4911            curves2d.push((cb, ct));
4912        }
4913        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<_, _>>()?;
4914        // Top (outward up) and bottom (outward down) loops.
4915        let mut coedges = Vec::with_capacity(count);
4916        for k in 0..count {
4917            coedges.push((top_e[k], true, plane_pcurve(world([0.0, 0.0], to), e1, e2, &curves2d[k].1, true)?));
4918        }
4919        top_loops.push(coedges);
4920        let mut coedges = Vec::with_capacity(count);
4921        for k in (0..count).rev() {
4922            coedges.push((bottom_e[k], false, plane_pcurve(world([0.0, 0.0], from), e2, e1, &curves2d[k].0, false)?));
4923        }
4924        bottom_loops.push(coedges);
4925        // Sides: the bottom curve extruded (u along it, v up), outward on its right.
4926        for k in 0..count {
4927            let next = (k + 1) % count;
4928            let (cb, _) = &curves2d[k];
4929            let rows: Vec<Vec<Vec4>> = cb
4930                .control_points
4931                .iter()
4932                .map(|p| {
4933                    let x = p.point().expect("point");
4934                    vec![Vec4::from_point(x, p.w), Vec4::from_point(x.add(up.scale(to - from)), p.w)]
4935                })
4936                .collect();
4937            let surface = frag(NurbsSurface::new(cb.degree, 1, cb.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows), "side")?;
4938            let [u0, u1] = frag(cb.domain(), "domain")?;
4939            let coedges = vec![
4940                (bottom_e[k], true, uv_line([u0, 0.0], [u1, 0.0])?),
4941                (verticals[next], true, uv_line([u1, 0.0], [u1, 1.0])?),
4942                (top_e[k], false, uv_line([u1, 1.0], [u0, 1.0])?),
4943                (verticals[k], false, uv_line([u0, 1.0], [u0, 0.0])?),
4944            ];
4945            shell.face(surface, coedges);
4946        }
4947    }
4948    let top_points: Vec<Vec3> = extent.iter().map(|&q| world(q, to)).collect();
4949    shell.face_loops(plane_patch(world([0.0, 0.0], to), e1, e2, &top_points)?, top_loops);
4950    let bottom_points: Vec<Vec3> = extent.iter().map(|&q| world(q, from)).collect();
4951    shell.face_loops(plane_patch(world([0.0, 0.0], from), e2, e1, &bottom_points)?, bottom_loops);
4952    let body = shell.solid();
4953    let issues = body.validate();
4954    if !issues.is_empty() {
4955        return Err(refuse("assembly", format!("the swept prism is not valid: {:?}", issues.first())));
4956    }
4957    Ok(body)
4958}
4959
4960/// A prism whose section is a convex polygon, carried by turns about axes
4961/// all along its own (a planar motion: a planet on its carrier) that ends
4962/// where it starts: its whole sweep (`prism_region_sweep`), or None when the
4963/// tool or motion is not of that kind. `steps`: each turn's axis point,
4964/// direction and rate, applied in order at every t ∈ [t0, t1].
4965#[allow(clippy::too_many_arguments)]
4966pub fn closed_planar_prism(
4967    origin: Vec3,
4968    normal: Vec3,
4969    x_axis: Vec3,
4970    outline: &[OutlinePiece],
4971    from: f64,
4972    to: f64,
4973    steps: &[(Vec3, Vec3, f64, f64)],
4974    t0: f64,
4975    t1: f64,
4976) -> Result<Option<BrepSolid>, KernelRefusal> {
4977    let Ok(up) = normal.normalized() else { return Ok(None) };
4978    let Ok(e1) = x_axis.sub(up.scale(x_axis.dot(up))).normalized() else { return Ok(None) };
4979    let e2 = up.cross(e1);
4980    // A polygon of straight sides, in order.
4981    let mut corners: Vec<[f64; 2]> = Vec::with_capacity(outline.len());
4982    for (k, piece) in outline.iter().enumerate() {
4983        let OutlinePiece::Line { from: a, to: b } = piece else { return Ok(None) };
4984        let OutlinePiece::Line { from: next, .. } = &outline[(k + 1) % outline.len()] else { return Ok(None) };
4985        if (b[0] - next[0]).hypot(b[1] - next[1]) > 1e-9 * (1.0 + b[0].hypot(b[1])) {
4986            return Ok(None);
4987        }
4988        corners.push(*a);
4989    }
4990    if corners.len() < 3 || steps.is_empty() || !(t1 > t0) {
4991        return Ok(None);
4992    }
4993    // Convex (either way round), or it is another engine's.
4994    let turn_of = |k: usize| {
4995        let (a, b, c) = (corners[k], corners[(k + 1) % corners.len()], corners[(k + 2) % corners.len()]);
4996        (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
4997    };
4998    let first_turn = turn_of(0);
4999    if first_turn == 0.0 || (1..corners.len()).any(|k| turn_of(k) * first_turn <= 0.0) {
5000        return Ok(None);
5001    }
5002    // Turns only, about axes along the prism's own: (centre in the plane, rate about +up).
5003    let mut turns: Vec<([f64; 2], f64)> = Vec::with_capacity(steps.len());
5004    for &(point, direction, turn, advance) in steps {
5005        let Ok(axis) = direction.normalized() else { return Ok(None) };
5006        if advance != 0.0 || axis.cross(up).length() > 1e-12 {
5007            return Ok(None);
5008        }
5009        let r = point.sub(origin);
5010        turns.push(([r.dot(e1), r.dot(e2)], turn * axis.dot(up).signum()));
5011    }
5012    let moved = |t: f64, q: [f64; 2]| -> [f64; 2] {
5013        let mut x = q;
5014        for &(c, rate) in &turns {
5015            let (sn, cs) = (rate * t).sin_cos();
5016            let d = [x[0] - c[0], x[1] - c[1]];
5017            x = [c[0] + cs * d[0] - sn * d[1], c[1] + sn * d[0] + cs * d[1]];
5018        }
5019        x
5020    };
5021    let total: f64 = turns.iter().map(|t| t.1).sum();
5022    // The turns compose to one rigid motion of the plane: a point q (where
5023    // it stands before any motion) is at moved(t, 0) + R(total t) q.
5024    let pose = |s: f64| -> ([f64; 2], f64) {
5025        let t = t0 + (t1 - t0) * s;
5026        (moved(t, [0.0, 0.0]), total * t)
5027    };
5028    // The turns are defined at every t, so the origin's velocity is a
5029    // centred difference at the motion's ends too.
5030    let rates = |s: f64| -> ([f64; 2], f64) {
5031        let h = 1e-6;
5032        let (pa, pb) = (pose(s - h).0, pose(s + h).0);
5033        ([(pb[0] - pa[0]) / (2.0 * h), (pb[1] - pa[1]) / (2.0 * h)], total * (t1 - t0))
5034    };
5035    // Ends where it starts: the same turn (mod 2π) and place.
5036    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
5037    let closes = corners.iter().all(|&c| {
5038        let (a, b) = (moved(t0, c), moved(t1, c));
5039        (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-9 * scale
5040    });
5041    if !closes {
5042        return Ok(None);
5043    }
5044    prism_region_sweep(&corners, from, to, origin, e1, e2, up, &pose, &rates, true).map(Some)
5045}
5046
5047/// Two turns driven by one parameter t: first by `rates[0]·t` about the
5048/// first axis (point, direction), then by `rates[1]·t` about the second; both
5049/// axes fixed in the world; t from `from` to `to`.
5050#[derive(Clone, Copy, Debug)]
5051pub struct TwoTurns {
5052    pub axes: [(Vec3, Vec3); 2],
5053    pub rates: [f64; 2],
5054    pub from: f64,
5055    pub to: f64,
5056}
5057
5058/// The whole sweep of a solid of revolution tumbled by two turns about skew
5059/// axes. The grazing loop moves on the tool (the instantaneous screw changes
5060/// with t), so the walls are lofted through exact samples. Where the tumble
5061/// passes over a point twice (the one-pass probe), the time is bisected into
5062/// spans each passing once, and the spans' sweeps are joined (consecutive
5063/// spans meet along a grazing loop; distant ones overlap).
5064pub fn sweep_solid_tumbled(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
5065    // A ring whose swept tube K bounds the solid outright, by the tube route
5066    // (BREP_SWEEP_TORUS_TUBE, default off); it declines anything else.
5067    if crate::solid_sweep_tube::torus_tube_on() {
5068        if let Some(tube) = ring_tube(tool, motion) {
5069            if let Ok(solid) = crate::solid_sweep_tube::sweep_torus_tube(&tube) {
5070                return Ok(solid);
5071            }
5072        }
5073    }
5074    let lofted = sweep_solid_tumbled_lofted(tool, motion);
5075    // A ring (a whole circle off its axis) the lofted walls refuse, by the
5076    // trim engine (BREP_SWEEP_RING_TRIM); the lofted refusal stands where it
5077    // refuses too. Rows the walls build are left to them.
5078    let Err(refusal) = lofted else {
5079        return lofted.map(|mut solid| {
5080            if cusp_first_on() {
5081                start_loops_at_cusps(&mut solid);
5082            }
5083            solid
5084        });
5085    };
5086    // A wall whose double curve reaches a corner: the trim route meets that
5087    // double curve's tip, which it does not yet write so a reader integrates
5088    // round it, and refuses after the work; declined before it.
5089    if !crate::solid_sweep_trim::ring_trim_on() || (refusal.to_string().contains(DOUBLE_CURVE_CORNER) && !crate::solid_sweep_trim::tip_splice_on()) {
5090        return Err(refusal);
5091    }
5092    let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool else { return Err(refusal) };
5093    let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() else { return Err(refusal) };
5094    if !(((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius) {
5095        return Err(refusal);
5096    }
5097    let (Ok(axis), Ok(d0), Ok(d1)) = (axis_direction.normalized(), motion.axes[0].1.normalized(), motion.axes[1].1.normalized()) else { return Err(refusal) };
5098    let two = crate::solid_sweep_trim::TwoTurnMotion { points: [motion.axes[0].0, motion.axes[1].0], directions: [d0, d1], rates: motion.rates };
5099    let ring_centre = axis_origin.add(axis.scale(centre[1]));
5100    crate::solid_sweep_trim::sweep_ring_tumbled(ring_centre, axis, centre[0], *radius, &two, motion.from, motion.to).or(Err(refusal))
5101}
5102
5103/// `BREP_SWEEP_CUSP_FIRST` (on unless =0): each loop of a tumbled sweep starts
5104/// at its cusp corner, where it has one.
5105fn cusp_first_on() -> bool {
5106    crate::switch!("BREP_SWEEP_CUSP_FIRST", true)
5107}
5108
5109/// Each loop rotated to start at its cusp corner (a zero-angle corner: the
5110/// edge leaving it runs back along the edge arriving, within 0.05 rad), where
5111/// it has one; the sharpest such corner where it has several. Topology and
5112/// geometry are unchanged. A reader that places a loop on its surface by
5113/// inverting the edges' points, each edge seeded from the last one's end,
5114/// mislays a corner where an edge creeps into a cusp (its point all but still
5115/// while its parameters still move): from the cusp it starts clean.
5116pub(crate) fn start_loops_at_cusps(solid: &mut BrepSolid) {
5117    let ends: HashMap<u64, [(Vec3, Vec3); 2]> = solid
5118        .edges
5119        .iter()
5120        .filter_map(|e| {
5121            let span = e.t1 - e.t0;
5122            let at = |t: f64| e.curve.evaluate(t).ok();
5123            let (p0, p1) = (at(e.t0)?, at(e.t1)?);
5124            let (q0, q1) = (at(e.t0 + 1e-2 * span)?, at(e.t1 - 1e-2 * span)?);
5125            // (point, direction into the edge) at its start and at its end
5126            Some((e.id, [(p0, q0.sub(p0)), (p1, q1.sub(p1))]))
5127        })
5128        .collect();
5129    for face in solid.shells.iter_mut().flat_map(|s| s.faces.iter_mut()) {
5130        for l in face.loops.iter_mut() {
5131            let n = l.coedges.len();
5132            if n < 2 {
5133                continue;
5134            }
5135            let mut best: Option<(f64, usize)> = None;
5136            for k in 0..n {
5137                let (before, after) = (&l.coedges[(k + n - 1) % n], &l.coedges[k]);
5138                let (Some(b), Some(a)) = (ends.get(&before.edge_id), ends.get(&after.edge_id)) else { continue };
5139                // into the corner back along the edge arriving, and out along the edge leaving
5140                let back = if before.forward { b[1].1 } else { b[0].1 };
5141                let out = if after.forward { a[0].1 } else { a[1].1 };
5142                let (lb, lo) = (back.length(), out.length());
5143                if !(lb > 0.0 && lo > 0.0) {
5144                    continue;
5145                }
5146                let along = back.dot(out) / (lb * lo);
5147                if along > (0.05f64).cos() && best.map_or(true, |(x, _)| along > x) {
5148                    best = Some((along, k));
5149                }
5150            }
5151            if let Some((_, k)) = best {
5152                l.coedges.rotate_left(k);
5153            }
5154        }
5155    }
5156}
5157
5158/// The tube route's reading of a ring tool (a whole circle off its axis) under two turns.
5159fn ring_tube(tool: &SolidTool, motion: &TwoTurns) -> Option<crate::solid_sweep_tube::Tube> {
5160    let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool else { return None };
5161    let [OutlinePiece::Arc { centre, radius, start, end }] = meridian.as_slice() else { return None };
5162    if !(((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius && motion.from.is_finite() && motion.to > motion.from) {
5163        return None;
5164    }
5165    let (axis, d0, d1) = (axis_direction.normalized().ok()?, motion.axes[0].1.normalized().ok()?, motion.axes[1].1.normalized().ok()?);
5166    let two = crate::solid_sweep_trim::TwoTurnMotion { points: [motion.axes[0].0, motion.axes[1].0], directions: [d0, d1], rates: motion.rates };
5167    crate::solid_sweep_tube::Tube::new(axis_origin.add(axis.scale(centre[1])), axis, centre[0], *radius, two, motion.from, motion.to)
5168}
5169
5170/// The lofted walls' refusal where a wall's double curve reaches a corner of
5171/// its grazing loop (the tumbled sweep reads it to skip the ring's trim route).
5172#[doc(hidden)]
5173pub const DOUBLE_CURVE_CORNER: &str = "the double curve of a wall reaches a corner of its grazing loop";
5174
5175/// The tumbled sweep by the lofted walls (a polyhedron by the trim engine).
5176fn sweep_solid_tumbled_lofted(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
5177    if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
5178        return Err(input("range", "the motion's range must run forward".into()));
5179    }
5180    let mut points = [Vec3::new(0.0, 0.0, 0.0); 2];
5181    let mut directions = [Vec3::new(0.0, 0.0, 1.0); 2];
5182    for k in 0..2 {
5183        points[k] = motion.axes[k].0;
5184        directions[k] = motion.axes[k].1.normalized().map_err(|_| input("axis", "a turn's axis has no direction".into()))?;
5185    }
5186    let turns = Turns { points, directions, rates: motion.rates };
5187    // A convex polyhedron, by the trim engine (default off).
5188    if let SolidTool::Polyhedron { vertices, faces } = tool {
5189        if crate::solid_sweep_trim::trim_engine_on() {
5190            let two = crate::solid_sweep_trim::TwoTurnMotion { points, directions, rates: motion.rates };
5191            return crate::solid_sweep_trim::sweep_convex_tumbled(vertices, faces, &two, motion.from, motion.to);
5192        }
5193    }
5194    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
5195        return Err(refuse("tumble_tool", "a tumble sweeps a solid of revolution only".into()));
5196    };
5197    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
5198    let base = Screw {
5199        a: points[0],
5200        e: directions[0],
5201        omega: motion.rates[0].abs() + motion.rates[1].abs(),
5202        c: 0.0,
5203        c2: 0.0,
5204        t0: motion.from,
5205        t1: motion.to,
5206        frame: None,
5207        turns: Some(turns),
5208        frozen: None,
5209        loop_samples: LOFT_SAMPLES,
5210        extent: points[1].sub(points[0]).length(),
5211    };
5212    let span = |t0: f64, t1: f64| -> Result<BrepSolid, KernelRefusal> {
5213        let mut screw = base;
5214        screw.t0 = t0;
5215        screw.t1 = t1;
5216        let mut last = None;
5217        // The loop's sampling doubles while the walls' rows miss between
5218        // samples (a thin ring's loop bends sharply before it folds).
5219        'samples: while screw.loop_samples <= 16 * LOFT_SAMPLES {
5220            for k in 0..8 {
5221                let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
5222                match lofted(&screw, *axis_origin, axis, reference, meridian) {
5223                    // A bulge that crosses a seam high up reads on the next
5224                    // wall as a part held away from its end: other seams too.
5225                    Err(error) if matches!(refused_as(&error), Some("loft_structure") | Some("end_trim_corner") | Some("end_trim_deep")) => last = Some(error),
5226                    Err(error) if refused_as(&error) == Some("loft_rows") => {
5227                        last = Some(error);
5228                        screw.loop_samples *= 2;
5229                        continue 'samples;
5230                    }
5231                    other => return other,
5232                }
5233            }
5234            break;
5235        }
5236        Err(last.expect("tried"))
5237    };
5238    // Bisect where the sweep folds over itself.
5239    let mut pending = vec![(motion.from, motion.to, 0usize)];
5240    let mut spans: Vec<(f64, BrepSolid)> = Vec::new();
5241    while let Some((t0, t1, depth)) = pending.pop() {
5242        match span(t0, t1) {
5243            Ok(body) => spans.push((t0, body)),
5244            Err(error) if refused_as(&error) == Some("folds") && depth < 6 => {
5245                let middle = 0.5 * (t0 + t1);
5246                pending.push((middle, t1, depth + 1));
5247                pending.push((t0, middle, depth + 1));
5248            }
5249            Err(error) => return Err(error),
5250        }
5251    }
5252    spans.sort_by(|a, b| a.0.total_cmp(&b.0));
5253    let mut bodies: Vec<BrepSolid> = spans.into_iter().map(|(_, body)| body).collect();
5254    if bodies.len() == 1 {
5255        return Ok(bodies.pop().expect("one"));
5256    }
5257    crate::boolean_operation_nary(&bodies, crate::BooleanOperation::Union)
5258}
5259
5260/// A cap's pcurve for a lofted edge through the cap's exact chart (the edge
5261/// read back into the tool's frame at the cap's time).
5262fn charted_pcurve(chart: &Chart, screw: &Screw, t: f64, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
5263    let [d0, d1] = frag(curve.domain(), "domain")?;
5264    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
5265    let mut uv = Vec::with_capacity(ts.len());
5266    let mut poles = Vec::with_capacity(ts.len());
5267    for &tt in &ts {
5268        let x = screw.invert(t, frag(curve.evaluate(tt), "point")?);
5269        let [u, v] = chart.invert(x);
5270        uv.push(Vec3::new(u, v, 0.0));
5271        poles.push(chart.at_pole(x));
5272    }
5273    // Where the path crosses a span joint of the chart, one quintic through
5274    // it rings between samples (the parameter's second derivative jumps
5275    // there): by the run between joints instead (`BREP_SWEEP_PCURVE_JOINTS`).
5276    if pcurve_joints_on() && !poles.iter().any(|&p| p) {
5277        let (joints_u, joints_v) = chart.joints();
5278        let at = |tt: f64| -> Result<[f64; 2], KernelRefusal> { Ok(chart.invert(screw.invert(t, frag(curve.evaluate(tt), "point")?))) };
5279        if let Some(fitted) = jointed_pcurve(&ts, &uv, at, &joints_u, &joints_v, curve)? {
5280            return if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") };
5281        }
5282    }
5283    continue_pole_angles(&mut uv, &ts, &poles)?;
5284    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "charted_pcurve")?;
5285    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
5286}
5287
5288/// A surface's joints in each parameter: its interior knots that leave it C1
5289/// or less (a rational circle's spans meet at double knots), where a chart's
5290/// parameter bends.
5291fn surface_joints(surface: &NurbsSurface) -> (Vec<f64>, Vec<f64>) {
5292    let joints = |knots: &[f64], degree: usize| -> Vec<f64> {
5293        let (first, last) = (knots[0], knots[knots.len() - 1]);
5294        let mut out: Vec<f64> = Vec::new();
5295        for (i, &k) in knots.iter().enumerate() {
5296            if k > first && k < last && (i == 0 || knots[i - 1] != k) && knots.iter().filter(|&&x| x == k).count() + 1 >= degree {
5297                out.push(k);
5298            }
5299        }
5300        out
5301    };
5302    (joints(&surface.knots_u, surface.degree_u), joints(&surface.knots_v, surface.degree_v))
5303}
5304
5305thread_local! {
5306    /// Set while a split is read only for its curves and structure (a loft's
5307    /// interior times): its caps' pcurves are then never used.
5308    static PCURVES_SKIPPED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
5309}
5310
5311/// The switch for skipping the cap pcurves of a loft's interior splits
5312/// (default on, `=0` fits them all; the body is the same either way).
5313fn loft_splits_lean_on() -> bool {
5314    crate::switch!("BREP_SWEEP_LOFT_SPLITS_LEAN", true)
5315}
5316
5317/// `action` with the split's cap pcurves read at their ends only: a split at
5318/// a loft's interior time is read for its curves, samples and structure, its
5319/// caps' pcurves never (only the end poses' caps are built).
5320fn with_pcurves_skipped<T>(action: impl FnOnce() -> T) -> T {
5321    // Restored on the way out, an unwind too, so a caught panic leaves no
5322    // later sweep on this thread building its end caps' pcurves as lines.
5323    struct Restore(bool);
5324    impl Drop for Restore {
5325        fn drop(&mut self) {
5326            PCURVES_SKIPPED.with(|cell| cell.set(self.0));
5327        }
5328    }
5329    let _restore = Restore(PCURVES_SKIPPED.with(|cell| cell.replace(true)));
5330    action()
5331}
5332
5333/// A grazing curve through its exact samples (quintic); in a split read only
5334/// for its curves' samples and structure ([`with_pcurves_skipped`]: a loft's
5335/// interior times), the line between its ends, never read as a curve.
5336fn fit_tool_curve(points: &[Vec3], params: &[f64]) -> Result<NurbsCurve, String> {
5337    if PCURVES_SKIPPED.with(|cell| cell.get()) && points.len() >= 2 && params.len() == points.len() {
5338        let (a, b) = (params[0], params[params.len() - 1]);
5339        return NurbsCurve::new(1, vec![a, a, b, b], vec![Vec4::from_point(points[0], 1.0), Vec4::from_point(points[points.len() - 1], 1.0)]);
5340    }
5341    crate::interpolate_curve(points, 5, params)
5342}
5343
5344/// A cap pcurve's stations: the whole set, or its two ends where the pcurve
5345/// is never used ([`with_pcurves_skipped`]).
5346fn pcurve_stations(d0: f64, d1: f64) -> Vec<f64> {
5347    if PCURVES_SKIPPED.with(|cell| cell.get()) {
5348        return vec![d0, d1];
5349    }
5350    (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect()
5351}
5352
5353/// The quintic through a cap pcurve's stations; through two (a skipped
5354/// pcurve), the line between its ends.
5355fn fit_pcurve(uv: &[Vec3], ts: &[f64]) -> Result<NurbsCurve, String> {
5356    if ts.len() == 2 {
5357        return NurbsCurve::new(1, vec![ts[0], ts[0], ts[1], ts[1]], uv.iter().map(|&p| Vec4::from_point(p, 1.0)).collect());
5358    }
5359    crate::interpolate_curve(uv, 5, ts)
5360}
5361
5362/// The switch for [`jointed_pcurve`] (default on; `=0` fits one quintic as before).
5363fn pcurve_joints_on() -> bool {
5364    crate::switch!("BREP_SWEEP_PCURVE_JOINTS", true)
5365}
5366
5367/// A cap's pcurve broken where its path crosses a span joint of its chart:
5368/// the edge's parameter at each crossing found by bisection (`at` reads the
5369/// path's chart parameters at an edge parameter), each run between them
5370/// sampled as densely as the whole and interpolated (quintic) on its own, the
5371/// runs joined C0 at the crossings, so each run interpolates a smooth function
5372/// and the trim keeps to its edge at the same parameter, not only at the
5373/// samples. `ts`, `uv`: the whole's samples; `edge`: the curve the path
5374/// reads (its own C1-or-less knots are cut too). None where the path crosses
5375/// no joint (the one quintic is smooth there).
5376fn jointed_pcurve(ts: &[f64], uv: &[Vec3], at: impl Fn(f64) -> Result<[f64; 2], KernelRefusal>, joints_u: &[f64], joints_v: &[f64], edge: &NurbsCurve) -> Result<Option<NurbsCurve>, KernelRefusal> {
5377    if ts.len() < 3 || ts.len() != uv.len() {
5378        return Ok(None);
5379    }
5380    let (d0, d1) = (ts[0], ts[ts.len() - 1]);
5381    // The edge's own joints: an interior knot that leaves it C1 or less (a
5382    // rational arc's spans) kinks its parameter, so the path's too.
5383    let mut cuts: Vec<f64> = Vec::new();
5384    for (index, &k) in edge.knots.iter().enumerate() {
5385        if k > d0 && k < d1 && (index == 0 || edge.knots[index - 1] != k) {
5386            let multiplicity = edge.knots.iter().filter(|&&x| x == k).count();
5387            if multiplicity + 1 >= edge.degree {
5388                cuts.push(k);
5389            }
5390        }
5391    }
5392    for j in 0..ts.len() - 1 {
5393        let (a, b) = (uv[j], uv[j + 1]);
5394        for (coord, joints) in [(0usize, joints_u), (1, joints_v)] {
5395            let (ca, cb) = if coord == 0 { (a.x, b.x) } else { (a.y, b.y) };
5396            for &k in joints {
5397                // A sample on the joint itself is the cut (a path that only
5398                // touches it is cut there too, harmlessly).
5399                if ca == k && j > 0 {
5400                    cuts.push(ts[j]);
5401                    continue;
5402                }
5403                if (ca - k) * (cb - k) < 0.0 {
5404                    // Bisect the edge's parameter for the crossing.
5405                    let (mut lo, mut hi) = (ts[j], ts[j + 1]);
5406                    let side = ca < k;
5407                    for _ in 0..80 {
5408                        let mid = 0.5 * (lo + hi);
5409                        if mid <= lo || mid >= hi {
5410                            break;
5411                        }
5412                        if (at(mid)?[coord] < k) == side { lo = mid } else { hi = mid }
5413                    }
5414                    cuts.push(0.5 * (lo + hi));
5415                }
5416            }
5417        }
5418    }
5419    if cuts.is_empty() {
5420        return Ok(None);
5421    }
5422    // Each run at least a millionth of the whole: a cut nearer an end or
5423    // another than that is dropped (its run would be too short to fit).
5424    let least = 1e-6 * (d1 - d0);
5425    cuts.sort_by(f64::total_cmp);
5426    let mut bounds = vec![d0];
5427    for c in cuts {
5428        if c - bounds[bounds.len() - 1] >= least && d1 - c >= least {
5429            bounds.push(c);
5430        }
5431    }
5432    if bounds.len() == 1 {
5433        return Ok(None);
5434    }
5435    bounds.push(d1);
5436    let samples = ts.len() - 1;
5437    let degree = 5;
5438    let mut knots: Vec<f64> = Vec::new();
5439    let mut poles: Vec<Vec4> = Vec::new();
5440    let runs = bounds.len() - 1;
5441    for (index, run) in bounds.windows(2).enumerate() {
5442        let (a, b) = (run[0], run[1]);
5443        let count = ((samples as f64 * (b - a) / (d1 - d0)).ceil() as usize).max(degree + 1);
5444        let params: Vec<f64> = (0..=count).map(|i| if i == count { b } else { a + (b - a) * i as f64 / count as f64 }).collect();
5445        let points: Vec<Vec3> = params.iter().map(|&tt| at(tt).map(|[u, v]| Vec3::new(u, v, 0.0))).collect::<Result<_, _>>()?;
5446        // A run that does not fit falls back to the one quintic, never a refusal.
5447        let Ok(piece) = crate::interpolate_curve(&points, degree, &params) else { return Ok(None) };
5448        if piece.degree != degree {
5449            return Ok(None);
5450        }
5451        let n = piece.knots.len();
5452        if index == 0 {
5453            knots.extend_from_slice(&piece.knots[..n - (degree + 1)]);
5454            poles.extend_from_slice(&piece.control_points);
5455        } else {
5456            // The joint: its parameter `degree` times (C0), this run's interior
5457            // knots; its first pole is the previous run's last.
5458            knots.extend(std::iter::repeat_n(a, degree));
5459            knots.extend_from_slice(&piece.knots[degree + 1..n - (degree + 1)]);
5460            poles.extend_from_slice(&piece.control_points[1..]);
5461        }
5462        if index + 1 == runs {
5463            knots.extend(std::iter::repeat_n(b, degree + 1));
5464        }
5465    }
5466    Ok(NurbsCurve::new(degree, knots, poles).ok())
5467}
5468
5469/// An edge through its surface's pole (a ball carried square to its own
5470/// axis: every grazing circle runs pole to pole) has no angle there, and the
5471/// inverse returns any. Each sample at a pole (`poles`) takes the first
5472/// parameter its neighbours run to, continued in a line.
5473fn continue_pole_angles(uv: &mut [Vec3], ts: &[f64], poles: &[bool]) -> Result<(), KernelRefusal> {
5474    for j in 0..uv.len() {
5475        if !poles[j] {
5476            continue;
5477        }
5478        let near = if j + 2 < uv.len() && !poles[j + 1] && !poles[j + 2] {
5479            [j + 1, j + 2]
5480        } else if j >= 2 && !poles[j - 1] && !poles[j - 2] {
5481            [j - 1, j - 2]
5482        } else {
5483            return Err(refuse("cap_pole", "a lofted edge stays on its cap's pole".into()));
5484        };
5485        let (a, b) = (uv[near[0]].x, uv[near[1]].x);
5486        uv[j].x = a + (a - b) * (ts[j] - ts[near[0]]) / (ts[near[0]] - ts[near[1]]);
5487    }
5488    Ok(())
5489}
5490
5491/// A cap's pcurve for a lofted edge: its dense image on the cap's surface.
5492fn projected_pcurve(surface: &NurbsSurface, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
5493    let [d0, d1] = frag(curve.domain(), "domain")?;
5494    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
5495    let mut uv = Vec::with_capacity(ts.len());
5496    let mut poles = Vec::with_capacity(ts.len());
5497    let [u0, u1] = frag(surface.domain_u(), "domain")?;
5498    let step = 1e-3 * (u1 - u0);
5499    for &t in &ts {
5500        let x = frag(curve.evaluate(t), "point")?;
5501        let foot = frag(crate::project_point_to_surface(surface, x), "project")?;
5502        if foot.distance > 1e-6 * (1.0 + x.length()) {
5503            return Err(refuse("loft_cap", format!("a lofted edge leaves its cap by {} at {x:?}", foot.distance)));
5504        }
5505        uv.push(Vec3::new(foot.u, foot.v, 0.0));
5506        // A pole of the surface: its points do not move with the first
5507        // parameter there.
5508        let aside = if foot.u + step <= u1 { foot.u + step } else { foot.u - step };
5509        let moved = frag(surface.evaluate(aside, foot.v), "point")?.sub(frag(surface.evaluate(foot.u, foot.v), "point")?).length();
5510        poles.push(moved <= 1e-9 * (1.0 + x.length()));
5511    }
5512    continue_pole_angles(&mut uv, &ts, &poles)?;
5513    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "projected_pcurve")?;
5514    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
5515}
5516
5517type Signature = (Vec<(usize, usize, bool)>, Vec<(bool, Vec<(usize, bool)>)>, Vec<(usize, bool)>);
5518
5519fn signature(split: &Split) -> Result<Signature, KernelRefusal> {
5520    Ok((
5521        split.curves.iter().map(|c| (c.start, c.end, c.degenerate)).collect(),
5522        split.caps.iter().map(|cap| (cap.front, cap.coedges.iter().map(|&(c, f, _)| (c, f)).collect())).collect(),
5523        split.grazing()?,
5524    ))
5525}
5526
5527fn lofted(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<BrepSolid, KernelRefusal> {
5528    let split_at = |t: f64| -> Result<Split, KernelRefusal> {
5529        let mut frozen = *screw;
5530        frozen.frozen = Some(t);
5531        split_revolved(&frozen, origin, axis, radial, meridian)
5532    };
5533    let mut lambdas: Vec<f64> = (0..=LOFT_SAMPLES).map(|i| i as f64 / LOFT_SAMPLES as f64).collect();
5534    // World samples of grazing curve c at time t, in the wall's direction.
5535    let samples_of = |split: &Split, c: usize, back_forward: bool, t: f64| -> Result<Vec<Vec3>, KernelRefusal> {
5536        let Some(list) = &split.curves[c].samples else {
5537            return Err(refuse("loft_samples", "a grazing curve has no exact samples to loft".into()));
5538        };
5539        let mut world: Vec<Vec3> = list.iter().map(|&x| screw.apply(t, x)).collect();
5540        if back_forward {
5541            world.reverse();
5542        }
5543        Ok(world)
5544    };
5545    // Time breaks start even and are refined only in the spans whose middle
5546    // misses, by the quintic's h^6 error: a smooth stretch of the motion keeps
5547    // its long spans (doubling everywhere tripled the wall for one bend).
5548    let mut fractions: Vec<f64> = (0..=15).map(|j| j as f64 / 15.0).collect();
5549    loop {
5550        let count = fractions.len() - 1;
5551        // The walls' second parameter runs 0 -> 1 over the motion.
5552        let times: Vec<f64> = fractions.iter().map(|&f| if f == 1.0 { screw.t1 } else { screw.t0 + (screw.t1 - screw.t0) * f }).collect();
5553        // Only the end poses' caps are built: the interior splits are read
5554        // for their curves and structure, their caps' pcurves skipped
5555        // (`BREP_SWEEP_LOFT_SPLITS_LEAN`).
5556        let lean = loft_splits_lean_on();
5557        let splits: Vec<Split> = times
5558            .iter()
5559            .enumerate()
5560            .map(|(j, &t)| if lean && j != 0 && j != count { with_pcurves_skipped(|| split_at(t)) } else { split_at(t) })
5561            .collect::<Result<_, _>>()?;
5562        if splits.iter().any(|split| !split.slides.is_empty() || !split.slide_sides.is_empty()) {
5563            return Err(refuse("loft_structure", "a flat end that slides within its own plane is not lofted".into()));
5564        }
5565        let shape = signature(&splits[0])?;
5566        for split in &splits[1..] {
5567            if signature(split)? != shape {
5568                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
5569            }
5570        }
5571        let grazing = shape.2.clone();
5572        if grazing.is_empty() {
5573            return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
5574        }
5575        let scale = splits[0].scale + screw.extent;
5576        let target = LOFT_TARGET * scale;
5577        // Walls: per grazing curve, rows along it at each time, then across time.
5578        let mut walls = Vec::with_capacity(grazing.len());
5579        // Every wall's exact samples at every time.
5580        let mut sampled: Vec<Vec<Vec<Vec3>>> = Vec::with_capacity(grazing.len());
5581        for &(c, back_forward) in &grazing {
5582            let mut at_times = Vec::with_capacity(times.len());
5583            for (j, split) in splits.iter().enumerate() {
5584                let points = samples_of(split, c, back_forward, times[j])?;
5585                if points.len() != lambdas.len() {
5586                    if points.len() < 13 || points.len() % 2 == 0 {
5587                        return Err(refuse("loft_samples", "a grazing curve's exact samples cannot be lofted".into()));
5588                    }
5589                    lambdas = (0..points.len()).map(|i| i as f64 / (points.len() - 1) as f64).collect();
5590                }
5591                at_times.push(points);
5592            }
5593            sampled.push(at_times);
5594        }
5595        // A row through every `stride`-th sample: its worst miss at the
5596        // samples it leaves out, over every wall and time.
5597        let thinned = |stride: usize| -> Result<f64, KernelRefusal> {
5598            let coarse_lambdas: Vec<f64> = lambdas.iter().step_by(stride).copied().collect();
5599            let mut worst = 0.0f64;
5600            for at_times in &sampled {
5601                for points in at_times {
5602                    let coarse_points: Vec<Vec3> = points.iter().step_by(stride).copied().collect();
5603                    let coarse = frag(crate::interpolate_curve(&coarse_points, 5, &coarse_lambdas), "loft_row")?;
5604                    for (i, x) in points.iter().enumerate().filter(|(i, _)| i % stride != 0) {
5605                        worst = worst.max(frag(coarse.evaluate(lambdas[i]), "loft_row")?.sub(*x).length());
5606                    }
5607                }
5608            }
5609            Ok(worst)
5610        };
5611        // Each wall's rows pass through as few of its samples as hold every
5612        // exact sample within a quarter of the target, at every time (a loop
5613        // smooth but for one sharp bend needs its samples only there, and the
5614        // wall's size is what the solid's users pay for): from every 16th,
5615        // a stretch that misses at a sample it leaves out gets its middle one.
5616        let spans = lambdas.len() - 1;
5617        let mut kept: Vec<Vec<usize>> = Vec::with_capacity(sampled.len());
5618        for at_times in &sampled {
5619            let coarsest = if spans % 16 == 0 && spans >= 96 { 16 } else { 1 };
5620            let mut subset: Vec<usize> = (0..=spans).step_by(coarsest).collect();
5621            loop {
5622                let subset_lambdas: Vec<f64> = subset.iter().map(|&i| lambdas[i]).collect();
5623                let mut misses = vec![0.0f64; subset.len() - 1];
5624                for points in at_times {
5625                    let row_points: Vec<Vec3> = subset.iter().map(|&i| points[i]).collect();
5626                    let row = frag(crate::interpolate_curve(&row_points, 5, &subset_lambdas), "loft_row")?;
5627                    for k in 0..subset.len() - 1 {
5628                        for i in subset[k] + 1..subset[k + 1] {
5629                            misses[k] = misses[k].max(frag(row.evaluate(lambdas[i]), "loft_row")?.sub(points[i]).length());
5630                        }
5631                    }
5632                }
5633                let mut refined = Vec::with_capacity(2 * subset.len());
5634                for k in 0..subset.len() - 1 {
5635                    refined.push(subset[k]);
5636                    if misses[k] > 0.25 * target {
5637                        refined.push((subset[k] + subset[k + 1]) / 2);
5638                    }
5639                }
5640                refined.push(spans);
5641                if refined.len() == subset.len() {
5642                    break;
5643                }
5644                subset = refined;
5645            }
5646            kept.push(subset);
5647        }
5648        // Where a wall keeps neighbouring samples there is none left out
5649        // between them to measure at: a row passes through its samples, and
5650        // between them it is as good as the loop is smooth at that spacing.
5651        // Its miss there is estimated from the rows through every other
5652        // sample, scaled by the quintic's 2^-6.
5653        let dense = kept.iter().any(|subset| subset.windows(2).any(|pair| pair[1] == pair[0] + 1));
5654        let between = if dense { thinned(2)? / 64.0 } else { 0.0 };
5655        for (index, &(c, back_forward)) in grazing.iter().enumerate() {
5656            let row_lambdas: Vec<f64> = kept[index].iter().map(|&i| lambdas[i]).collect();
5657            let mut rows: Vec<NurbsCurve> = Vec::with_capacity(times.len());
5658            for points in &sampled[index] {
5659                let row_points: Vec<Vec3> = kept[index].iter().map(|&i| points[i]).collect();
5660                rows.push(frag(crate::interpolate_curve(&row_points, 5, &row_lambdas), "loft_row")?);
5661            }
5662            let knots_u = rows[0].knots.clone();
5663            let mut net: Vec<Vec<Vec4>> = Vec::with_capacity(rows[0].control_points.len());
5664            let mut knots_v = Vec::new();
5665            for k in 0..rows[0].control_points.len() {
5666                let column: Vec<Vec3> = rows.iter().map(|row| row.control_points[k].point()).collect::<Result<_, _>>().map_err(|e| refuse("loft", e))?;
5667                let across = frag(crate::interpolate_curve(&column, 5, &fractions), "loft_column")?;
5668                knots_v = across.knots.clone();
5669                net.push(across.control_points.clone());
5670            }
5671            let surface = frag(NurbsSurface::new(5, 5, knots_u, knots_v, net), "loft_wall")?;
5672            walls.push((c, back_forward, surface, rows.first().cloned().expect("rows"), rows.last().cloned().expect("rows")));
5673        }
5674        if between > target {
5675            return Err(refuse("loft_rows", format!("the lofted wall's rows stay about {between:e} off the grazing loop between its samples")));
5676        }
5677        // Against the exact loop in the middle of each span, every sample.
5678        let mut misses = vec![0.0f64; count];
5679        for j in 0..count {
5680            let t = 0.5 * (times[j] + times[j + 1]);
5681            let fraction = 0.5 * (fractions[j] + fractions[j + 1]);
5682            let split = if lean { with_pcurves_skipped(|| split_at(t))? } else { split_at(t)? };
5683            if signature(&split)? != shape {
5684                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
5685            }
5686            for (c, back_forward, surface, _, _) in &walls {
5687                let exact = samples_of(&split, *c, *back_forward, t)?;
5688                for (i, x) in exact.iter().enumerate() {
5689                    misses[j] = misses[j].max(frag(surface.evaluate(lambdas[i], fraction), "loft_check")?.sub(*x).length());
5690                }
5691            }
5692        }
5693        let worst = misses.iter().copied().fold(0.0f64, f64::max);
5694        if worst > target {
5695            if count > 2000 {
5696                return Err(refuse("loft_accuracy", format!("the lofted wall stays {worst:e} off the grazing loop")));
5697            }
5698            // A span missing by more than half the target is cut into
5699            // ceil((e / (target / 4))^(1/6)) pieces; the rest stay.
5700            let mut refined = Vec::with_capacity(2 * fractions.len());
5701            for j in 0..count {
5702                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 };
5703                for k in 0..pieces {
5704                    refined.push(fractions[j] + (fractions[j + 1] - fractions[j]) * k as f64 / pieces as f64);
5705                }
5706            }
5707            refined.push(1.0);
5708            fractions = refined;
5709            continue;
5710        }
5711        // Each K corner's path through the sample times.
5712        let mut paths: HashMap<usize, Vec<Vec3>> = HashMap::new();
5713        for &(c, _) in &grazing {
5714            for r in [splits[0].curves[c].start, splits[0].curves[c].end] {
5715                paths.entry(r).or_insert_with(|| splits.iter().zip(&times).map(|(split, &t)| screw.apply(t, split.points[r])).collect());
5716            }
5717        }
5718        return assemble_lofted(screw, &splits[0], &splits[count], &walls, &fractions, &paths, target);
5719    }
5720}
5721
5722/// Refuse a lofted wall with an edge of regression: across one the wall's
5723/// normal turns over, and the band beside it lies inside nearby poses (the
5724/// sweep folds within a few degrees of the motion, which no probe walk is
5725/// dense enough to be sure of seeing). Normals are compared between
5726/// neighbours on every time row and between rows, outside what the end trims
5727/// take away (`removed`, chart rings) and a few columns off its edge (a fold
5728/// line meets the end at the cut's own ends). `fit`: how near the wall keeps
5729/// to its exact loop (a length).
5730fn wall_regular(surface: &NurbsSurface, fractions: &[f64], removed: &[&[[f64; 2]]], fit: f64) -> Result<(), KernelRefusal> {
5731    const COLUMNS: usize = 4 * LOFT_SAMPLES;
5732    let mut rows: Vec<f64> = Vec::with_capacity(2 * fractions.len());
5733    for j in 0..fractions.len() {
5734        rows.push(fractions[j]);
5735        if j + 1 < fractions.len() {
5736            rows.push(0.5 * (fractions[j] + fractions[j + 1]));
5737        }
5738    }
5739    let normal = |u: f64, v: f64| -> Result<Option<Vec3>, KernelRefusal> {
5740        let h = 1e-6;
5741        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));
5742        let du = frag(surface.evaluate(ub, v), "regular")?.sub(frag(surface.evaluate(ua, v), "regular")?).scale(1.0 / (ub - ua));
5743        let dv = frag(surface.evaluate(u, vb), "regular")?.sub(frag(surface.evaluate(u, va), "regular")?).scale(1.0 / (vb - va));
5744        // Where the wall's two directions all but line up, or it is no
5745        // wider than its own fit's ripple (a corner it pinches to), it has
5746        // no normal to speak of: the fit's noise would turn it.
5747        let cross = du.cross(dv);
5748        if cross.length() <= 1e-6 * du.length() * dv.length() || du.length().min(dv.length()) <= 1e3 * fit {
5749            return Ok(None);
5750        }
5751        Ok(cross.normalized().ok())
5752    };
5753    // Each trimmed-away ring's box, grown by the reach of `near_ring` and a hair: a point
5754    // outside it is neither inside the ring (a closed polygon) nor that near it, so the box
5755    // answers for it as the ring's own tests would.
5756    let reach = 4.0 / COLUMNS as f64;
5757    let boxes: Vec<[f64; 4]> = removed
5758        .iter()
5759        .map(|ring| {
5760            let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
5761            for p in ring.iter() {
5762                lo = [lo[0].min(p[0]), lo[1].min(p[1])];
5763                hi = [hi[0].max(p[0]), hi[1].max(p[1])];
5764            }
5765            let pad = reach * (1.0 + 1e-9) + 1e-12;
5766            [lo[0] - pad, hi[0] + pad, lo[1] - pad, hi[1] + pad]
5767        })
5768        .collect();
5769    let mut previous: Option<Vec<Option<Vec3>>> = None;
5770    for &v in &rows {
5771        // What a trim takes away is not part of the body.
5772        let row: Vec<Option<Vec3>> = (0..=COLUMNS)
5773            .map(|i| {
5774                let u = i as f64 / COLUMNS as f64;
5775                let taken = removed.iter().zip(&boxes).any(|(ring, b)| {
5776                    !(u < b[0] || u > b[1] || v < b[2] || v > b[3]) && (inside_ring(ring, [u, v]) || near_ring(ring, [u, v], reach))
5777                });
5778                if taken { Ok(None) } else { normal(u, v) }
5779            })
5780            .collect::<Result<_, _>>()?;
5781        for i in 0..COLUMNS {
5782            if let (Some(a), Some(b)) = (row[i], row[i + 1]) {
5783                if a.dot(b) < -0.5 {
5784                    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)));
5785                }
5786            }
5787            if let Some(Some(Some(a))) = previous.as_ref().map(|p| p.get(i).copied()) {
5788                if let Some(b) = row[i] {
5789                    if a.dot(b) < -0.5 {
5790                        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)));
5791                    }
5792                }
5793            }
5794        }
5795        previous = Some(row);
5796    }
5797    Ok(())
5798}
5799
5800/// A stretch of a wall's row at v, from u = a to u = b, as an edge's curve.
5801fn row_piece(wall: &NurbsSurface, v: f64, a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
5802    let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
5803    let along: Vec<Vec3> = ts.iter().map(|&s| frag(wall.evaluate((a + (b - a) * s).clamp(0.0, 1.0), v), "wall")).collect::<Result<_, _>>()?;
5804    frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
5805}
5806
5807/// A wall's end row in pieces around its trims and breaks (one more than the
5808/// spans), at v.
5809fn row_pieces(wall: &NurbsSurface, v: f64, spans: &[TrimSpan]) -> Result<Vec<NurbsCurve>, KernelRefusal> {
5810    let mut pieces = Vec::with_capacity(spans.len() + 1);
5811    let mut from = 0.0;
5812    for span in spans {
5813        pieces.push(row_piece(wall, v, from, span.lambdas[0])?);
5814        from = span.lambdas[1];
5815    }
5816    pieces.push(row_piece(wall, v, from, 1.0)?);
5817    Ok(pieces)
5818}
5819
5820/// The wall over u ∈ [a, b] only, in the same parameters.
5821/// Can `pcurve` (in a wall's chart) meet the split segment u = tip.u, v in
5822/// [v_lo, v_hi], anywhere but at the tip itself? A pcurve that ENDS at the
5823/// tip (a side of the double curve) touches it there: a short stub at that end
5824/// must leave the tip into one side of the line or away from the segment, and
5825/// the rest is tested. Every other piece is decided on the convex hull of its
5826/// control points (positive weights), halved where a hull straddles the
5827/// segment; one still straddling after 24 halvings counts as meeting it.
5828fn hull_meets_segment(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64) -> Result<bool, KernelRefusal> {
5829    let uv = |p: &Vec4| [p.x / p.w, p.y / p.w];
5830    let near_tip = |p: [f64; 2]| (p[0] - tip[0]).abs() <= 1e-9 && (p[1] - tip[1]).abs() <= 1e-9;
5831    let (first, last) = (uv(&pcurve.control_points[0]), uv(&pcurve.control_points[pcurve.control_points.len() - 1]));
5832    if !(near_tip(first) || near_tip(last)) {
5833        return hull_straddles(pcurve, tip, v_lo, v_hi, 0);
5834    }
5835    if near_tip(first) && near_tip(last) {
5836        return Ok(true);
5837    }
5838    let [d0, d1] = frag(pcurve.domain(), "domain")?;
5839    let at = if near_tip(first) { d0 + 1e-3 * (d1 - d0) } else { d1 - 1e-3 * (d1 - d0) };
5840    let (a, b) = frag(pcurve.split(at), "split")?;
5841    let (stub, rest) = if near_tip(first) { (a, b) } else { (b, a) };
5842    let side: Vec<f64> = stub.control_points.iter().map(|p| uv(p)[0] - tip[0]).collect();
5843    let one_side = side.iter().all(|d| *d >= -1e-12) || side.iter().all(|d| *d <= 1e-12);
5844    // The segment runs from the tip towards the far row: away is the other way.
5845    let segment_below = v_lo < tip[1] - 1e-12;
5846    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 });
5847    if !(one_side || away) {
5848        return Ok(true);
5849    }
5850    hull_straddles(&rest, tip, v_lo, v_hi, 0)
5851}
5852
5853fn hull_straddles(pcurve: &NurbsCurve, tip: &[f64; 2], v_lo: f64, v_hi: f64, depth: usize) -> Result<bool, KernelRefusal> {
5854    let points: Vec<[f64; 2]> = pcurve.control_points.iter().map(|p| [p.x / p.w, p.y / p.w]).collect();
5855    let (u_min, u_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[0]), hi.max(p[0])));
5856    let (w_min, w_max) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[1]), hi.max(p[1])));
5857    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 {
5858        return Ok(false);
5859    }
5860    if depth >= 24 {
5861        return Ok(true);
5862    }
5863    let [d0, d1] = frag(pcurve.domain(), "domain")?;
5864    match pcurve.split(0.5 * (d0 + d1)) {
5865        Ok((a, b)) => Ok(hull_straddles(&a, tip, v_lo, v_hi, depth + 1)? || hull_straddles(&b, tip, v_lo, v_hi, depth + 1)?),
5866        // Too short to halve: count it as meeting the segment.
5867        Err(_) => Ok(true),
5868    }
5869}
5870
5871/// `BREP_SWEEP_SPLIT_CROSSING` (default on; `=0` off): a lofted wall that
5872/// turns over near one end is split at its swallowtail's point whenever the
5873/// split segment to the far row crosses no trim curve, not only where the
5874/// trimmed row keeps to its side of the tip's u; otherwise the wall stays one
5875/// face carrying its double curve as a slot (one edge used twice), which
5876/// meshes poorly at the slot's tip.
5877fn split_crossing_on() -> bool {
5878    crate::switch!("BREP_SWEEP_SPLIT_CROSSING", true)
5879}
5880
5881fn restrict_u(surface: &NurbsSurface, a: f64, b: f64) -> Result<NurbsSurface, KernelRefusal> {
5882    let [u0, u1] = frag(surface.domain_u(), "domain")?;
5883    if a <= u0 + 1e-12 && b >= u1 - 1e-12 {
5884        return Ok(surface.clone());
5885    }
5886    let columns = surface.control_points[0].len();
5887    let mut knots = Vec::new();
5888    let mut net: Vec<Vec<Vec4>> = Vec::new();
5889    for j in 0..columns {
5890        let line: Vec<Vec4> = surface.control_points.iter().map(|row| row[j]).collect();
5891        let mut curve = frag(NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), line), "restrict")?;
5892        if b < u1 - 1e-12 {
5893            curve = frag(curve.split(b), "restrict")?.0;
5894        }
5895        if a > u0 + 1e-12 {
5896            curve = frag(curve.split(a), "restrict")?.1;
5897        }
5898        if j == 0 {
5899            knots = curve.knots.clone();
5900            net = vec![Vec::with_capacity(columns); curve.control_points.len()];
5901        }
5902        for (i, point) in curve.control_points.iter().enumerate() {
5903            net[i].push(*point);
5904        }
5905    }
5906    frag(NurbsSurface::new(surface.degree_u, surface.degree_v, knots, surface.knots_v.clone(), net), "restrict")
5907}
5908
5909/// One place a wall is cut back where an end pose bulges past it: the wall
5910/// parameter range [λa, λb] along the grazing loop where the trim leaves and
5911/// rejoins it, the cut (from the point at λa to the point at λb, on both the
5912/// wall and the pose), the wall's side of the trim from λa to λb (`chain`),
5913/// the double curve and its swallowtail point if the trim follows one, and
5914/// the part of the wall's chart it takes away (`removed`, (u, v) points
5915/// around it).
5916struct TrimSpan {
5917    lambdas: [f64; 2],
5918    points: [Vec3; 2],
5919    /// None: no cut at all, only a break in the end's row at λa = λb (where
5920    /// a line splitting the wall lands on it).
5921    cut: Option<NurbsCurve>,
5922    chain: Vec<(TrimPiece, bool, NurbsCurve)>,
5923    slot: Option<(NurbsCurve, Vec3)>,
5924    /// The swallowtail's point in the wall's chart (u, v), where the trim
5925    /// follows a double curve.
5926    tip: Option<[f64; 2]>,
5927    removed: Vec<[f64; 2]>,
5928}
5929
5930/// Every place an end pose bulges past one wall, in order along the loop, and
5931/// the loop's pieces around them (one more than the spans).
5932struct EndTrim {
5933    spans: Vec<TrimSpan>,
5934    pieces: Vec<NurbsCurve>,
5935}
5936
5937/// Which edge a piece of a trimmed wall's end runs on: the cut it shares with
5938/// the cap, or the wall's own double curve (both of the slot's sides).
5939#[derive(Clone, Copy, PartialEq, Eq, Debug)]
5940enum TrimPiece {
5941    Cut,
5942    Slot,
5943}
5944
5945/// The cut of a lofted wall (u along the grazing loop, v the motion's time
5946/// fraction) by the pose at its end (`end` 0: v = 0, 1: v = 1), if the pose
5947/// bulges past it, else None.
5948///
5949/// The wall meets the pose along K and leaves it to second order (K grazes),
5950/// so with ε the time fraction from the end, f = d / ε² (d the pose's signed
5951/// distance) is smooth up to the end. The part of the wall inside the pose is
5952/// where f < 0; its boundary is traced as the curve f = 0 from the end and back
5953/// to it. It need not be a graph over u: a tongue of it may run on past where
5954/// it left the end.
5955///
5956/// `fit`: how near the wall keeps to the exact loop (a length).
5957fn end_trim(screw: &Screw, split: &Split, t: f64, wall: &NurbsSurface, end: usize, fit: f64) -> Result<Option<EndTrim>, KernelRefusal> {
5958    let v_of = |e: f64| if end == 1 { 1.0 - e } else { e };
5959    let at = |u: f64, e: f64| -> Result<Vec3, KernelRefusal> { frag(wall.evaluate(u.clamp(0.0, 1.0), v_of(e)), "wall") };
5960    let f = |u: f64, e: f64| -> Result<f64, KernelRefusal> { Ok(split.distance(screw.invert(t, at(u, e)?)) / (e * e)) };
5961    // Below `floor` the walls' fit swamps d / ε².
5962    let floor = 1e-3;
5963    // How far into the motion (as a fraction of it) a trim may reach (a fold
5964    // band can run most of a span); past that the end pose meets a distant
5965    // part of the sweep (`end_trim_deep`).
5966    let window = 0.6;
5967    let noise = 2.0 * fit / (floor * floor);
5968    // Where the wall dips into the pose just off the end.
5969    let n = 2000;
5970    let edge: Vec<f64> = (0..=n).map(|i| f(i as f64 / n as f64, floor)).collect::<Result<_, _>>()?;
5971    // Inside: the stretches where f is negative, those that dip below the
5972    // fit's noise somewhere (a stretch that never does is the fit's own).
5973    let mut inside: Vec<bool> = edge.iter().map(|&x| x < 0.0).collect();
5974    let mut i = 0;
5975    while i <= n {
5976        if !inside[i] {
5977            i += 1;
5978            continue;
5979        }
5980        let mut j = i;
5981        while j < n && inside[j + 1] {
5982            j += 1;
5983        }
5984        if edge[i..=j].iter().all(|&x| x >= -noise) {
5985            for flag in &mut inside[i..=j] {
5986                *flag = false;
5987            }
5988        }
5989        i = j + 1;
5990    }
5991    if !inside.iter().any(|&x| x) {
5992        // Nothing near the end; a pocket deeper in is caught below.
5993        return pierced(&f, floor, window, noise, &[]);
5994    }
5995    if inside[0] || inside[n] || inside[1] || inside[n - 1] {
5996        return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
5997    }
5998    // Crossings of the floor line, by bisection between samples of either sign.
5999    let mut crossings: Vec<f64> = Vec::new();
6000    for i in 0..n {
6001        if inside[i] != inside[i + 1] {
6002            let (mut a, mut b) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
6003            let a_inside = inside[i];
6004            for _ in 0..60 {
6005                let mid = 0.5 * (a + b);
6006                if (f(mid, floor)? < 0.0) == a_inside { a = mid } else { b = mid }
6007            }
6008            crossings.push(0.5 * (a + b));
6009        }
6010    }
6011    if crossings.len() % 2 != 0 || crossings.is_empty() {
6012        return Err(refuse("end_trim", "an end pose's bulges past a wall do not pair up".into()));
6013    }
6014    // Trace f = 0 from the first crossing of each pair into the wall until it
6015    // returns to the floor; it must come back at the pair's other crossing.
6016    let gradient = |u: f64, e: f64| -> Result<[f64; 2], KernelRefusal> {
6017        let h = 1e-6;
6018        Ok([(f(u + h, e)? - f(u - h, e)?) / (2.0 * h), (f(u, e + h)? - f(u, e - h)?) / (2.0 * h)])
6019    };
6020    let settle = |mut p: [f64; 2]| -> Result<[f64; 2], KernelRefusal> {
6021        for _ in 0..30 {
6022            let value = f(p[0], p[1])?;
6023            let g = gradient(p[0], p[1])?;
6024            let norm = g[0] * g[0] + g[1] * g[1];
6025            if norm == 0.0 {
6026                return Err(refuse("end_trim", "the cut of an end pose has a flat point".into()));
6027            }
6028            p = [p[0] - value * g[0] / norm, p[1] - value * g[1] / norm];
6029            if value.abs() * p[1] * p[1] < 1e-14 * split.scale {
6030                break;
6031            }
6032        }
6033        Ok(p)
6034    };
6035    let step = 1e-3;
6036    let mut cuts: Vec<Vec<[f64; 2]>> = Vec::new();
6037    // Each cut starts at the lowest crossing not yet used and ends at the
6038    // unused one it comes back to.
6039    let mut unused: Vec<f64> = crossings.clone();
6040    while !unused.is_empty() {
6041        let start = unused.remove(0);
6042        let mut points: Vec<[f64; 2]> = vec![[start, floor]];
6043        let mut heading = [0.0, 1.0];
6044        loop {
6045            let last = *points.last().expect("points");
6046            let g = gradient(last[0], last[1])?;
6047            let length = g[0].hypot(g[1]);
6048            let mut tangent = [-g[1] / length, g[0] / length];
6049            if tangent[0] * heading[0] + tangent[1] * heading[1] < 0.0 {
6050                tangent = [-tangent[0], -tangent[1]];
6051            }
6052            let next = settle([last[0] + step * tangent[0], last[1] + step * tangent[1]])?;
6053            if next[1] < floor {
6054                break;
6055            }
6056            if next[0] <= 1e-3 || next[0] >= 1.0 - 1e-3 {
6057                return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
6058            }
6059            if next[1] > window {
6060                return Err(refuse("end_trim_deep", "an end pose holds a deep part of a wall".into()));
6061            }
6062            if points.len() > 20_000 {
6063                return Err(refuse("end_trim", "the cut of an end pose does not close".into()));
6064            }
6065            heading = [next[0] - last[0], next[1] - last[1]];
6066            points.push(next);
6067        }
6068        let back = *points.last().expect("points");
6069        let Some(at_end) = unused.iter().position(|&c| (back[0] - c).abs() <= 2.0 * step) else {
6070            return Err(refuse("end_trim", "the cut of an end pose does not come back where it should".into()));
6071        };
6072        let back_at = unused.remove(at_end);
6073        // A dip that never rises off the floor and comes straight back is
6074        // the fit's noise at the end, not a bulge.
6075        if points.len() == 1 && (back_at - start).abs() <= step {
6076            continue;
6077        }
6078        points.push([back_at, floor]);
6079        // Down to the end itself along the cut's direction at the floor (taken
6080        // from the first point clearly above it).
6081        let to_end = |p: [f64; 2], rest: &[[f64; 2]], reversed: bool| -> Result<[f64; 2], KernelRefusal> {
6082            // Along the cut's own tangent there (across the gradient of f), so
6083            // the run to the end continues it smoothly.
6084            let g = gradient(p[0], p[1])?;
6085            if g[0].abs() > 1e-3 * g[1].abs() {
6086                return Ok([p[0] + g[1] / g[0] * p[1], 0.0]);
6087            }
6088            let clear = |q: &&[f64; 2]| q[1] - p[1] > 0.25 * step;
6089            let found = if reversed { rest.iter().rev().find(clear) } else { rest.iter().find(clear) };
6090            Ok(match found {
6091                Some(q) => [p[0] - (q[0] - p[0]) / (q[1] - p[1]) * p[1], 0.0],
6092                None => [p[0], 0.0],
6093            })
6094        };
6095        let count = points.len();
6096        let (first, last) = (to_end(points[0], &points[1..], false)?, to_end(points[count - 1], &points[..count - 1], true)?);
6097        if [first[0], last[0]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
6098            return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
6099        }
6100        points.insert(0, first);
6101        points.push(last);
6102        if points[0][0] > points[points.len() - 1][0] {
6103            points.reverse();
6104        }
6105        cuts.push(points);
6106    }
6107    let rings: Vec<&[[f64; 2]]> = cuts.iter().map(|c| c.as_slice()).collect();
6108    pierced(&f, floor, window, noise, &rings)?;
6109    let chart = |p: [f64; 2]| [p[0], v_of(p[1])];
6110    // A curve on the wall through chart points and its pcurve, both on the
6111    // given parameters (normalized to [0, 1]); chart-length parameters by
6112    // default (the wall's own speed collapses near an edge of regression, so
6113    // 3D chord lengths would bunch them).
6114    let chart_lengths = |chart_points: &[[f64; 2]]| -> Vec<f64> {
6115        let mut params = vec![0.0];
6116        for k in 1..chart_points.len() {
6117            let gap = (chart_points[k][0] - chart_points[k - 1][0]).hypot(chart_points[k][1] - chart_points[k - 1][1]);
6118            params.push(params[k - 1] + gap.max(1e-15));
6119        }
6120        params
6121    };
6122    // Returns the curve, its pcurve, and how far the pcurve's image strays
6123    // from the curve between the points.
6124    let curve_through = |chart_points: &[[f64; 2]], params: &[f64], what: &'static str| -> Result<(NurbsCurve, NurbsCurve, f64), KernelRefusal> {
6125        let total = *params.last().expect("params");
6126        let params: Vec<f64> = params.iter().map(|x| x / total).collect();
6127        let world: Vec<Vec3> = chart_points.iter().map(|p| at(p[0], p[1])).collect::<Result<_, _>>()?;
6128        let uv: Vec<Vec3> = chart_points.iter().map(|p| Vec3::new(p[0], v_of(p[1]), 0.0)).collect();
6129        let (curve, pcurve) = (frag(crate::interpolate_curve(&world, 5, &params), what)?, frag(crate::interpolate_curve(&uv, 5, &params), what)?);
6130        // Between the points too: the pcurve's image stays on the curve.
6131        let mut worst = 0.0f64;
6132        for k in 0..params.len() - 1 {
6133            let s = 0.5 * (params[k] + params[k + 1]);
6134            let q = frag(pcurve.evaluate(s), "pcurve")?;
6135            let e = if end == 1 { 1.0 - q.y } else { q.y };
6136            worst = worst.max(at(q.x, e)?.sub(frag(curve.evaluate(s), "curve")?).length());
6137        }
6138        Ok((curve, pcurve, worst))
6139    };
6140    // A trim curve is refined until its pcurve's image is within `fine` of
6141    // it, and taken as near as it gets if within `loose` (a double curve has
6142    // a cusp at its swallowtail's point, where no finer trace helps; a
6143    // tighter bar costs a thin tool many rounds and buys no reader anything).
6144    let (fine, loose) = (1e-7 * split.scale, 1e-7 * split.scale);
6145    let missed = |what: &str| refuse("end_trim", format!("the {what}'s pcurve leaves it between its points however finely it is traced"));
6146    // The cut, refined where its fit misses: a settled point between each
6147    // pair of traced ones (on the stretches run straight to the end, their
6148    // middles).
6149    let cut_through = |mut chart_points: Vec<[f64; 2]>| -> Result<(NurbsCurve, NurbsCurve), KernelRefusal> {
6150        let mut best: Option<(NurbsCurve, NurbsCurve, f64)> = None;
6151        for _ in 0..7 {
6152            let fitted = curve_through(&chart_points, &chart_lengths(&chart_points), "cut")?;
6153            let done = fitted.2 <= fine;
6154            if best.as_ref().map_or(true, |b| fitted.2 < b.2) {
6155                best = Some(fitted);
6156            }
6157            if done {
6158                break;
6159            }
6160            let mut finer = Vec::with_capacity(2 * chart_points.len());
6161            for k in 0..chart_points.len() - 1 {
6162                finer.push(chart_points[k]);
6163                let (p, q) = (chart_points[k], chart_points[k + 1]);
6164                let middle = [0.5 * (p[0] + q[0]), 0.5 * (p[1] + q[1])];
6165                // Below the floor the cut runs straight to the end: split it there as a line.
6166                finer.push(if p[1] >= floor && q[1] >= floor { settle(middle)? } else { middle });
6167            }
6168            finer.push(chart_points[chart_points.len() - 1]);
6169            chart_points = finer;
6170        }
6171        match best {
6172            Some((curve, pcurve, worst)) if worst <= loose => Ok((curve, pcurve)),
6173            _ => Err(missed("cut")),
6174        }
6175    };
6176    let piece = |a: f64, b: f64| -> Result<NurbsCurve, KernelRefusal> {
6177        let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
6178        let along: Vec<Vec3> = ts.iter().map(|&s| at(a + (b - a) * s, 0.0)).collect::<Result<_, _>>()?;
6179        frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
6180    };
6181    // Where the wall turns over near the end (a swallowtail), the cut passes
6182    // through a point of the end's own loop K a second time, on the wall's far
6183    // sheet: there the wall's double curve starts, and the trim follows it to
6184    // the swallowtail's point and back instead of the cut's first stretch.
6185    let span_of = |points: &Vec<[f64; 2]>| -> Result<TrimSpan, KernelRefusal> {
6186        if let Some((k, ua, b)) = double_start(&at, points, floor)? {
6187            // The double curve, traced more finely while its fit misses.
6188            let mut traced: Option<(Vec<[f64; 2]>, Vec<[f64; 2]>, NurbsCurve, NurbsCurve, NurbsCurve, f64)> = None;
6189            for round in 0..5 {
6190                let (a_side, b_side) = double_curve(&at, [ua, 0.0], b, window, 2e-3 / f64::from(1u32 << round))?;
6191                // Both sides on the continuation's own arc length, so the double
6192                // curve and its two pcurves share one parameter.
6193                let mut sigma = vec![0.0];
6194                for k in 1..a_side.len() {
6195                    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]));
6196                    sigma.push(sigma[k - 1] + step.max(1e-15));
6197                }
6198                let ((slot, pa, miss_a), (_, pb, miss_b)) = (curve_through(&a_side, &sigma, "double_curve")?, curve_through(&b_side, &sigma, "double_curve")?);
6199                let worst = miss_a.max(miss_b);
6200                if traced.as_ref().map_or(true, |t| worst < t.5) {
6201                    traced = Some((a_side, b_side, slot, pa, pb, worst));
6202                }
6203                if worst <= fine {
6204                    break;
6205                }
6206            }
6207            let Some((a_side, b_side, slot, pa, pb, _)) = traced.filter(|t| t.5 <= loose) else { return Err(missed("double curve")) };
6208            // The cut keeps the stretch from the far sheet's point to its end away
6209            // from where the double curve leaves K.
6210            let low = ua < points[0][0];
6211            if !low && ua <= points[points.len() - 1][0] {
6212                return Err(refuse("end_trim", "the double curve of a wall leaves its end inside the cut".into()));
6213            }
6214            let mut kept: Vec<[f64; 2]> = if low { points[k..].to_vec() } else { points[..=k].to_vec() };
6215            if low { kept[0] = b } else { *kept.last_mut().expect("kept") = b }
6216            let (cut, cut_pcurve) = cut_through(kept.clone())?;
6217            let tip = at(a_side[a_side.len() - 1][0], a_side[a_side.len() - 1][1])?;
6218            // The wall's side of the trim from the low end to the high one.
6219            let chain = if low {
6220                vec![(TrimPiece::Slot, true, pa), (TrimPiece::Slot, false, frag(pb.reversed(), "reversed")?), (TrimPiece::Cut, true, cut_pcurve)]
6221            } else {
6222                vec![(TrimPiece::Cut, true, cut_pcurve), (TrimPiece::Slot, true, pb), (TrimPiece::Slot, false, frag(pa.reversed(), "reversed")?)]
6223            };
6224            let lambdas = if low { [ua, points[points.len() - 1][0]] } else { [points[0][0], ua] };
6225            let mut removed: Vec<[f64; 2]> = Vec::new();
6226            if low {
6227                removed.extend(a_side.iter().map(|&p| chart(p)));
6228                removed.extend(b_side.iter().rev().map(|&p| chart(p)));
6229                removed.extend(kept.iter().map(|&p| chart(p)));
6230            } else {
6231                removed.extend(kept.iter().map(|&p| chart(p)));
6232                removed.extend(b_side.iter().map(|&p| chart(p)));
6233                removed.extend(a_side.iter().rev().map(|&p| chart(p)));
6234            }
6235            // Everything the end pose holds must be in what goes.
6236            let dropped: Vec<[f64; 2]> = if low { points[..k].to_vec() } else { points[k + 1..].to_vec() };
6237            for p in dropped.iter().filter(|p| p[1] > 2.0 * floor && (p[0] - b[0]).hypot(p[1] - b[1]) > 5e-3) {
6238                if !inside_ring(&removed, chart(*p)) {
6239                    return Err(refuse("end_trim", "the cut of an end pose leaves the part of the wall its double curve takes away".into()));
6240                }
6241            }
6242            let points3 = [at(lambdas[0], 0.0)?, at(lambdas[1], 0.0)?];
6243            // The double curve's sides part about its end: one keeps to
6244            // each side of the swallowtail's point along the loop, so a
6245            // line through that point splits the wall between them.
6246            let tip_chart = chart(a_side[a_side.len() - 1]);
6247            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)));
6248            let ((a_lo, a_hi), (b_lo, b_hi)) = (side(&a_side), side(&b_side));
6249            let parted = (a_lo >= -1e-9 && b_hi <= 1e-9) || (a_hi <= 1e-9 && b_lo >= -1e-9);
6250            if !parted {
6251                return Err(refuse("end_trim", "the two sides of a wall's double curve do not keep to either side of its end".into()));
6252            }
6253            return Ok(TrimSpan { lambdas, points: points3, cut: Some(cut), chain, slot: Some((slot, tip)), tip: Some(tip_chart), removed });
6254        }
6255        let (cut, wall_pcurve) = cut_through(points.clone())?;
6256        let (la, lb) = (points[0][0], points[points.len() - 1][0]);
6257        let removed: Vec<[f64; 2]> = points.iter().map(|&p| chart(p)).collect();
6258        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 })
6259    };
6260    if cuts.is_empty() {
6261        return pierced(&f, floor, window, noise, &[]);
6262    }
6263    let mut spans = Vec::with_capacity(cuts.len());
6264    for points in &cuts {
6265        spans.push(span_of(points)?);
6266    }
6267    spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
6268    // A trim wholly inside what another takes away adds nothing (a bulge of
6269    // the end pose inside a swallowtail's slot).
6270    let edge_row = v_of(0.0);
6271    let within = |inner: &TrimSpan, outer: &TrimSpan| -> bool {
6272        inner.lambdas[0] >= outer.lambdas[0]
6273            && inner.lambdas[1] <= outer.lambdas[1]
6274            && 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))
6275    };
6276    let mut k = 0;
6277    while k < spans.len() {
6278        if (0..spans.len()).any(|j| j != k && within(&spans[k], &spans[j])) {
6279            spans.remove(k);
6280        } else {
6281            k += 1;
6282        }
6283    }
6284    for pair in spans.windows(2) {
6285        if pair[0].lambdas[1] >= pair[1].lambdas[0] {
6286            return Err(refuse("end_trim", "an end pose's trims of a wall overlap".into()));
6287        }
6288    }
6289    let mut pieces = Vec::with_capacity(spans.len() + 1);
6290    let mut from = 0.0;
6291    for span in &spans {
6292        pieces.push(piece(from, span.lambdas[0])?);
6293        from = span.lambdas[1];
6294    }
6295    pieces.push(piece(from, 1.0)?);
6296    Ok(Some(EndTrim { spans, pieces }))
6297}
6298
6299
6300
6301/// Is q within `reach` of the closed polygon `ring`'s sides?
6302fn near_ring(ring: &[[f64; 2]], q: [f64; 2], reach: f64) -> bool {
6303    (0..ring.len()).any(|k| {
6304        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
6305        let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
6306        let length = dx * dx + dy * dy;
6307        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 };
6308        (q[0] - a[0] - s * dx).hypot(q[1] - a[1] - s * dy) < reach
6309    })
6310}
6311
6312/// Is q inside the closed polygon `ring` (its last point joins its first)?
6313fn inside_ring(ring: &[[f64; 2]], q: [f64; 2]) -> bool {
6314    let mut crossings = 0;
6315    for k in 0..ring.len() {
6316        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
6317        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]) {
6318            crossings += 1;
6319        }
6320    }
6321    crossings % 2 == 1
6322}
6323
6324/// The point of an end pose's cut (chart points (u, ε), ε the time fraction
6325/// from the end) that lies on the end's own loop K a second time, away from
6326/// the cut's ends: (its index along the cut, the loop parameter u of the point
6327/// of K it meets, and the refined (u, ε) on the cut), if there is one.
6328fn double_start(at: &dyn Fn(f64, f64) -> Result<Vec3, KernelRefusal>, points: &[[f64; 2]], floor: f64) -> Result<Option<(usize, f64, [f64; 2])>, KernelRefusal> {
6329    let n = 4000;
6330    let row: Vec<Vec3> = (0..=n).map(|i| at(i as f64 / n as f64, 0.0)).collect::<Result<_, _>>()?;
6331    let scale = row.iter().fold(0.0f64, |m, p| m.max(p.sub(row[0]).length())).max(1e-300);
6332    let mut best: Option<(f64, usize, usize)> = None;
6333    for (k, p) in points.iter().enumerate() {
6334        if p[1] < 4.0 * floor {
6335            continue;
6336        }
6337        let x = at(p[0], p[1])?;
6338        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 });
6339        // The cut nears K at its own ends in proportion to ε; the second
6340        // meeting is where that ratio drops to nothing.
6341        if best.map_or(true, |b| d / p[1] < b.0 / points[b.1][1]) {
6342            best = Some((d, k, i));
6343        }
6344    }
6345    let Some((distance, k, i)) = best else { return Ok(None) };
6346    // Coarse: the cut's points are a few thousandths of the chart apart.
6347    if distance > 5e-3 * scale {
6348        return Ok(None);
6349    }
6350    // Newton on at(b) = at(u, 0) for (b_u, b_ε, u).
6351    let mut x = [points[k][0], points[k][1], i as f64 / n as f64];
6352    let h = 1e-7;
6353    for _ in 0..40 {
6354        let g = at(x[0], x[1])?.sub(at(x[2], 0.0)?);
6355        if g.length() < 1e-13 * scale {
6356            // Not the trivial meeting of the end row with itself.
6357            if x[1] < 2.0 * floor || !(0.0..=1.0).contains(&x[0]) || !(0.0..=1.0).contains(&x[2]) {
6358                return Ok(None);
6359            }
6360            return Ok(Some((k, x[2], [x[0], x[1]])));
6361        }
6362        let c0 = at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h);
6363        let c1 = at(x[0], x[1] + h)?.sub(at(x[0], x[1] - h)?).scale(0.5 / h);
6364        let c2 = at(x[2] + h, 0.0)?.sub(at(x[2] - h, 0.0)?).scale(-0.5 / h);
6365        let det = c0.dot(c1.cross(c2));
6366        if det.abs() < 1e-300 {
6367            break;
6368        }
6369        // Cramer's rule for [c0 c1 c2] d = -g.
6370        let r = g.scale(-1.0);
6371        let d = [r.dot(c1.cross(c2)) / det, c0.dot(r.cross(c2)) / det, c0.dot(c1.cross(r)) / det];
6372        x = [x[0] + d[0], x[1] + d[1], x[2] + d[2]];
6373    }
6374    if distance < 1e-6 * scale {
6375        return Err(refuse("end_trim", "an end pose's cut meets its own loop, but not exactly enough to follow".into()));
6376    }
6377    Ok(None)
6378}
6379
6380/// The double curve of a wall from where it leaves the end (a, on the end's
6381/// loop) and its partner b on the far sheet, traced by continuation of
6382/// at(a) = at(b) in (u, ε) for both, to the swallowtail point where the two
6383/// sides meet. Returns both sides' chart points, ending at the same point.
6384fn 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> {
6385    let h = 1e-7;
6386    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);
6387    let jacobian = |x: [f64; 4]| -> Result<[Vec3; 4], KernelRefusal> {
6388        Ok([
6389            at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h),
6390            at(x[0], x[1] + h)?.sub(at(x[0], (x[1] - h).max(0.0))?).scale(1.0 / (h + x[1].min(h))),
6391            at(x[2] + h, x[3])?.sub(at(x[2] - h, x[3])?).scale(-0.5 / h),
6392            at(x[2], x[3] + h)?.sub(at(x[2], (x[3] - h).max(0.0))?).scale(-1.0 / (h + x[3].min(h))),
6393        ])
6394    };
6395    let residual = |x: [f64; 4]| -> Result<Vec3, KernelRefusal> { Ok(at(x[0], x[1])?.sub(at(x[2], x[3])?)) };
6396    // The null direction of the 3x4 Jacobian: its signed 3x3 minors.
6397    let null = |j: &[Vec3; 4]| -> [f64; 4] {
6398        let minor = |p: usize, q: usize, r: usize| j[p].dot(j[q].cross(j[r]));
6399        let n = [minor(1, 2, 3), -minor(0, 2, 3), minor(0, 1, 3), -minor(0, 1, 2)];
6400        let length = n.iter().map(|x| x * x).sum::<f64>().sqrt().max(1e-300);
6401        [n[0] / length, n[1] / length, n[2] / length, n[3] / length]
6402    };
6403    // Minimum-norm Newton back onto at(a) = at(b).
6404    let correct = |mut x: [f64; 4]| -> Result<Option<[f64; 4]>, KernelRefusal> {
6405        for _ in 0..30 {
6406            let g = residual(x)?;
6407            if g.length() < 1e-13 * scale {
6408                return Ok(Some(x));
6409            }
6410            let j = jacobian(x)?;
6411            // J Jᵀ y = -g, step = Jᵀ y.
6412            let mut m = [[0.0; 3]; 3];
6413            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]];
6414            for p in 0..3 {
6415                for q in 0..3 {
6416                    m[p][q] = (0..4).map(|c| rows[p][c] * rows[q][c]).sum();
6417                }
6418            }
6419            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]);
6420            if det.abs() < 1e-300 {
6421                return Ok(None);
6422            }
6423            let r = [-g.x, -g.y, -g.z];
6424            let solve = |col: usize| -> f64 {
6425                let mut a = m;
6426                for p in 0..3 {
6427                    a[p][col] = r[p];
6428                }
6429                (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
6430            };
6431            let y = [solve(0), solve(1), solve(2)];
6432            for c in 0..4 {
6433                x[c] += (0..3).map(|p| rows[p][c] * y[p]).sum::<f64>();
6434            }
6435        }
6436        Ok(None)
6437    };
6438    let mut x = [a[0], a[1], b[0], b[1]];
6439    let mut a_side = vec![a];
6440    let mut b_side = vec![b];
6441    let mut heading: Option<[f64; 4]> = None;
6442    loop {
6443        let separation = (x[0] - x[2]).hypot(x[1] - x[3]);
6444        if separation < 3.0 * step && a_side.len() > 2 {
6445            let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
6446            a_side.push(tip);
6447            b_side.push(tip);
6448            return Ok((a_side, b_side));
6449        }
6450        let mut t = null(&jacobian(x)?);
6451        let reference = heading.unwrap_or([0.0, 1.0, 0.0, 0.0]);
6452        if (0..4).map(|c| t[c] * reference[c]).sum::<f64>() < 0.0 {
6453            t = [-t[0], -t[1], -t[2], -t[3]];
6454        }
6455        let mut next = None;
6456        let mut length = step;
6457        for _ in 0..6 {
6458            let guess = [x[0] + length * t[0], x[1] + length * t[1], x[2] + length * t[2], x[3] + length * t[3]];
6459            if let Some(y) = correct(guess)? {
6460                next = Some(y);
6461                break;
6462            }
6463            length *= 0.5;
6464        }
6465        let Some(y) = next else {
6466            // Near the swallowtail's point the two sheets turn tangent and
6467            // Newton gives out; close there if the sides are that near.
6468            if separation < 2e-2 && a_side.len() > 2 {
6469                let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
6470                a_side.push(tip);
6471                b_side.push(tip);
6472                return Ok((a_side, b_side));
6473            }
6474            return Err(refuse("end_trim", format!("the double curve of a wall cannot be followed (sides {separation:e} apart)")));
6475        };
6476        if [y[0], y[2]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
6477            return Err(refuse("end_trim_corner", DOUBLE_CURVE_CORNER.into()));
6478        }
6479        if y[1] > window || y[3] > window || y[1] < 0.0 || y[3] < 0.0 {
6480            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())));
6481        }
6482        if a_side.len() > 20_000 {
6483            return Err(refuse("end_trim", "the double curve of a wall does not close".into()));
6484        }
6485        heading = Some([y[0] - x[0], y[1] - x[1], y[2] - x[2], y[3] - x[3]]);
6486        x = y;
6487        a_side.push([x[0], x[1]]);
6488        b_side.push([x[2], x[3]]);
6489    }
6490}
6491
6492/// Refuse a wall the end pose holds a part of that no cut encloses: a pocket
6493/// of the wall inside the pose away from the end.
6494fn pierced(
6495    f: &dyn Fn(f64, f64) -> Result<f64, KernelRefusal>,
6496    floor: f64,
6497    window: f64,
6498    noise: f64,
6499    cuts: &[&[[f64; 2]]],
6500) -> Result<Option<EndTrim>, KernelRefusal> {
6501    let enclosed = |q: [f64; 2]| -> bool { cuts.iter().any(|ring| inside_ring(ring, q)) };
6502    for i in 1..200 {
6503        for j in 1..=40 {
6504            let (u, e) = (i as f64 / 200.0, floor + (window - floor) * (j as f64 / 40.0).powi(2));
6505            // d itself against the fit's noise: f grows as 1 / ε² near the end.
6506            if f(u, e)? * e * e < -noise * floor * floor && !enclosed([u, e]) {
6507                return Err(refuse("end_trim_deep", "an end pose holds a part of a wall away from its end".into()));
6508            }
6509        }
6510    }
6511    Ok(None)
6512}
6513
6514#[allow(clippy::too_many_arguments)]
6515fn assemble_lofted(
6516    screw: &Screw,
6517    first: &Split,
6518    last: &Split,
6519    walls: &[(usize, bool, NurbsSurface, NurbsCurve, NurbsCurve)],
6520    times: &[f64],
6521    paths: &HashMap<usize, Vec<Vec3>>,
6522    fit: f64,
6523) -> Result<BrepSolid, KernelRefusal> {
6524    let mut shell = Shell::new();
6525    let ends = [(first, screw.t0), (last, screw.t1)];
6526    // Where an end pose bulges past a wall near its grazing loop (a saddle side
6527    // curving past the wall it touches), cut the wall back to where it
6528    // re-enters the pose and carry the end cap across the loop to there.
6529    let mut trims: HashMap<(usize, usize), EndTrim> = HashMap::new();
6530    // Walls split into strips along lines through their swallowtails' points.
6531    let mut split_walls: std::collections::HashSet<usize> = std::collections::HashSet::new();
6532    for (index, (_, _, surface, _, _)) in walls.iter().enumerate() {
6533        for end in 0..2 {
6534            if let Some(trim) = end_trim(screw, ends[end].0, ends[end].1, surface, end, fit)? {
6535                trims.insert((index, end), trim);
6536            }
6537        }
6538        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();
6539        wall_regular(surface, times, &removed, fit)?;
6540        // A trim along a double curve has that curve as one edge on both its
6541        // sides: on one face its two uses could not be told apart from its
6542        // 3D curve alone (the wall passes through it twice). The wall is split
6543        // along the parameter line from each swallowtail's point to the far
6544        // end's row, which that row is broken at.
6545        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() };
6546        let (tips0, tips1) = (tips_at(0), tips_at(1));
6547        if !tips0.is_empty() && !tips1.is_empty() {
6548            return Err(refuse("wall_split", "a wall turns over near both its ends".into()));
6549        }
6550        let (far, tips) = if tips0.is_empty() { (0usize, tips1) } else { (1usize, tips0) };
6551        // A straight split line serves only where the trimmed row keeps to
6552        // its own side of it: all that comes before the swallowtail's point
6553        // along the row at or below its u, all after at or above. (A cut
6554        // that bulges across it would be crossed by the line; such a wall
6555        // stays one face.)
6556        let straight = |trim: &EndTrim| -> Result<bool, KernelRefusal> {
6557            for (k, span) in trim.spans.iter().enumerate() {
6558                let Some(tip) = span.tip else { continue };
6559                let first_slot = span.chain.iter().position(|piece| piece.0 == TrimPiece::Slot).unwrap_or(0);
6560                for (j, other) in trim.spans.iter().enumerate() {
6561                    for (n, (_, _, pcurve)) in other.chain.iter().enumerate() {
6562                        let before = j < k || (j == k && n <= first_slot);
6563                        let [d0, d1] = frag(pcurve.domain(), "domain")?;
6564                        for i in 0..=32 {
6565                            let u = frag(pcurve.evaluate(d0 + (d1 - d0) * i as f64 / 32.0), "pcurve")?.x;
6566                            if (before && u > tip[0] + 1e-9) || (!before && u < tip[0] - 1e-9) {
6567                                return Ok(false);
6568                            }
6569                        }
6570                    }
6571                }
6572            }
6573            Ok(true)
6574        };
6575        // Or, where the trimmed row strays across the tip's u only beyond the
6576        // tip (near its own end), the split segment itself: from the tip to
6577        // the far row, crossed by none of either end's trim curves. Each strip
6578        // then lies on the wall over the u its own pcurves span.
6579        let crossing_free = |trim_near: &EndTrim| -> Result<bool, KernelRefusal> {
6580            let v_far = far as f64;
6581            for tip in &tips {
6582                let (v_lo, v_hi) = if v_far < tip[1] { (v_far, tip[1]) } else { (tip[1], v_far) };
6583                let ends = [Some(trim_near), trims.get(&(index, far))];
6584                for trim in ends.into_iter().flatten() {
6585                    for span in &trim.spans {
6586                        for (_, _, pcurve) in &span.chain {
6587                            if hull_meets_segment(pcurve, tip, v_lo, v_hi)? {
6588                                return Ok(false);
6589                            }
6590                        }
6591                    }
6592                }
6593            }
6594            Ok(true)
6595        };
6596        let split_here = !tips.is_empty()
6597            && match trims.get(&(index, 1 - far)) {
6598                Some(trim) => straight(trim)? || (split_crossing_on() && crossing_free(trim)?),
6599                None => false,
6600            };
6601        if split_here {
6602            split_walls.insert(index);
6603            let v_far = far as f64;
6604            let mut spans = trims.remove(&(index, far)).map(|trim| trim.spans).unwrap_or_default();
6605            for tip in &tips {
6606                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 {
6607                    return Err(refuse("wall_split", "a wall's split line lands in a trim of its far end".into()));
6608                }
6609                let point = frag(surface.evaluate(tip[0], v_far), "wall")?;
6610                spans.push(TrimSpan { lambdas: [tip[0], tip[0]], points: [point, point], cut: None, chain: Vec::new(), slot: None, tip: None, removed: Vec::new() });
6611            }
6612            spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
6613            let pieces = row_pieces(surface, v_far, &spans)?;
6614            trims.insert((index, far), EndTrim { spans, pieces });
6615        }
6616    }
6617    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
6618    let mut vertex = |shell: &mut Shell, end: usize, p: usize| -> u64 {
6619        *vertex_at.entry((end, p)).or_insert_with(|| shell.vertex(screw.apply(ends[end].1, ends[end].0.points[p])))
6620    };
6621    let grazing: HashMap<usize, usize> = walls.iter().enumerate().map(|(index, w)| (w.0, index)).collect();
6622    // Edges at each end: K curves from the walls' end rows (in the tool
6623    // curve's direction), the rest the end split's own curves moved.
6624    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
6625    let mut edge_curve: HashMap<(usize, usize), NurbsCurve> = HashMap::new();
6626    // Per trimmed wall end: the loop's piece edges, and each span's cut and
6627    // double-curve edges (u64::MAX where a span has none).
6628    let mut trim_edges: HashMap<(usize, usize), (Vec<u64>, Vec<[u64; 2]>)> = HashMap::new();
6629    // Per trimmed wall end and span: the vertex at its low end, and at the
6630    // swallowtail's point where it has one.
6631    let mut trim_vertices: HashMap<(usize, usize), Vec<(u64, Option<u64>)>> = HashMap::new();
6632    for end in 0..2 {
6633        let (split, t) = ends[end];
6634        for (c, tool_curve) in split.curves.iter().enumerate() {
6635            let used = split.caps.iter().any(|cap| cap.front == (end == 1) && cap.coedges.iter().any(|e| e.0 == c));
6636            if !used {
6637                continue;
6638            }
6639            if let Some(&index) = grazing.get(&c) {
6640                if let Some(trim) = trims.get(&(index, end)) {
6641                    // Pieces in the wall's direction: K up to the cut, the cut, K after it.
6642                    let back_forward = walls[index].1;
6643                    let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
6644                    let (vf, vt) = (vertex(&mut shell, end, from), vertex(&mut shell, end, to));
6645                    let mut piece_edges = Vec::with_capacity(trim.pieces.len());
6646                    let mut span_edges = Vec::with_capacity(trim.spans.len());
6647                    let mut start = vf;
6648                    let mut span_vertices = Vec::with_capacity(trim.spans.len());
6649                    for (span, piece) in trim.spans.iter().zip(&trim.pieces) {
6650                        let va = shell.vertex(span.points[0]);
6651                        piece_edges.push(shell.edge(piece.clone(), start, va, false)?);
6652                        let Some(cut_curve) = &span.cut else {
6653                            // A break only: the row goes on from the same vertex.
6654                            span_edges.push([u64::MAX, u64::MAX]);
6655                            span_vertices.push((va, None));
6656                            start = va;
6657                            continue;
6658                        };
6659                        let vb = shell.vertex(span.points[1]);
6660                        let cut = shell.edge(cut_curve.clone(), va, vb, false)?;
6661                        // The double curve runs from where it leaves K (at
6662                        // the low end of the span if its chain starts with
6663                        // it) to the swallowtail's point.
6664                        let (slot, tip_vertex) = match &span.slot {
6665                            Some((curve, tip)) => {
6666                                let from = if span.chain[0].0 == TrimPiece::Slot { va } else { vb };
6667                                let tip = shell.vertex(*tip);
6668                                (shell.edge(curve.clone(), from, tip, false)?, Some(tip))
6669                            }
6670                            None => (u64::MAX, None),
6671                        };
6672                        span_edges.push([cut, slot]);
6673                        span_vertices.push((va, tip_vertex));
6674                        start = vb;
6675                    }
6676                    trim_vertices.insert((index, end), span_vertices);
6677                    piece_edges.push(shell.edge(trim.pieces[trim.pieces.len() - 1].clone(), start, vt, false)?);
6678                    trim_edges.insert((index, end), (piece_edges, span_edges));
6679                    continue;
6680                }
6681            }
6682            let curve = match grazing.get(&c) {
6683                Some(&index) => {
6684                    let (_, back_forward, _, row0, row1) = &walls[index];
6685                    let row = if end == 0 { row0 } else { row1 };
6686                    if *back_forward { frag(row.reversed(), "reversed")? } else { row.clone() }
6687                }
6688                None => screw.move_curve(t, &tool_curve.curve)?,
6689            };
6690            let (a, b) = (vertex(&mut shell, end, tool_curve.start), vertex(&mut shell, end, tool_curve.end));
6691            let edge = shell.edge(curve.clone(), a, b, tool_curve.degenerate)?;
6692            edge_at.insert((end, c), edge);
6693            edge_curve.insert((end, c), curve);
6694        }
6695    }
6696    for end in 0..2 {
6697        let (split, t) = ends[end];
6698        for cap in split.caps.iter().filter(|cap| cap.front == (end == 1)) {
6699            let surface = screw.move_surface(t, &cap.surface)?;
6700            let mut coedges = Vec::with_capacity(cap.coedges.len());
6701            for (c, forward, pcurve) in &cap.coedges {
6702                if let Some(&index) = grazing.get(c) {
6703                    if let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) {
6704                        let Some(chart) = cap.chart.as_ref() else {
6705                            return Err(refuse("end_trim", "an end pose bulges past a wall beside a cap without a chart".into()));
6706                        };
6707                        // The cap runs the tool's curve forward or back; the
6708                        // pieces run the wall's way: loop piece, cut, loop
6709                        // piece, ... loop piece.
6710                        let along = *forward != walls[index].1;
6711                        let mut pieces: Vec<(u64, &NurbsCurve)> = Vec::with_capacity(2 * trim.pieces.len());
6712                        for (k, piece) in trim.pieces.iter().enumerate() {
6713                            pieces.push((piece_edges[k], piece));
6714                            if let Some(cut) = trim.spans.get(k).and_then(|span| span.cut.as_ref()) {
6715                                pieces.push((span_edges[k][0], cut));
6716                            }
6717                        }
6718                        if !along {
6719                            pieces.reverse();
6720                        }
6721                        for (edge, curve) in pieces {
6722                            coedges.push((edge, along, charted_pcurve(chart, screw, t, curve, along)?));
6723                        }
6724                        continue;
6725                    }
6726                }
6727                let pcurve = if grazing.contains_key(c) && cap.chart.is_some() {
6728                    charted_pcurve(cap.chart.as_ref().expect("chart"), screw, t, &edge_curve[&(end, *c)], *forward)?
6729                } else if grazing.contains_key(c) {
6730                    match projected_pcurve(&surface, &edge_curve[&(end, *c)], *forward) {
6731                        Ok(p) => p,
6732                        Err(error) => {
6733                            // Which: the exact samples themselves, or the row between them?
6734                            let samples = split.curves[*c].samples.as_ref().map(|list| {
6735                                list.iter()
6736                                    .map(|&x| crate::project_point_to_surface(&surface, screw.apply(t, x)).map(|f| f.distance).unwrap_or(f64::NAN))
6737                                    .fold(0.0f64, f64::max)
6738                            });
6739                            let line = split.curves[*c].curve.degree;
6740                            return Err(KernelRefusal::unsupported(
6741                                KernelStage::Classify,
6742                                "loft_cap",
6743                                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),
6744                            ));
6745                        }
6746                    }
6747                } else {
6748                    pcurve.clone()
6749                };
6750                coedges.push((edge_at[&(end, *c)], *forward, pcurve));
6751            }
6752            shell.face(surface, coedges);
6753        }
6754    }
6755    // Orbits of K's corners: interpolated through the sample times as the
6756    // walls' end columns are.
6757    let mut orbits: HashMap<usize, u64> = HashMap::new();
6758    let mut keys: Vec<usize> = paths.keys().copied().collect();
6759    keys.sort_unstable();
6760    for r in keys {
6761        let curve = frag(crate::interpolate_curve(&paths[&r], 5, times), "orbit")?;
6762        let (a, b) = (vertex(&mut shell, 0, r), vertex(&mut shell, 1, r));
6763        orbits.insert(r, shell.edge(curve, a, b, false)?);
6764    }
6765    // One piece of a wall's end row in the direction of u: (edge, traversed
6766    // forward?, pcurve that way), and where a split line meets the row right
6767    // after it: (u, v, vertex).
6768    type RowPiece = (u64, bool, NurbsCurve, Option<(f64, f64, u64)>);
6769    for (index, (c, back_forward, surface, _, _)) in walls.iter().enumerate() {
6770        let tool_curve = &first.curves[*c];
6771        let (from, to) = if *back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
6772        let row = |end: usize| -> Result<Vec<RowPiece>, KernelRefusal> {
6773            let v = end as f64;
6774            let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) else {
6775                return Ok(vec![(edge_at[&(end, *c)], !*back_forward, uv_line([0.0, v], [1.0, v])?, None)]);
6776            };
6777            let vertices = &trim_vertices[&(index, end)];
6778            let mut list: Vec<RowPiece> = Vec::new();
6779            let mut at = 0.0;
6780            for (k, span) in trim.spans.iter().enumerate() {
6781                let broken = if span.cut.is_none() { Some((span.lambdas[0], v, vertices[k].0)) } else { None };
6782                list.push((piece_edges[k], true, uv_line([at, v], [span.lambdas[0], v])?, broken));
6783                for (n, (piece, forward, pcurve)) in span.chain.iter().enumerate() {
6784                    let edge = if *piece == TrimPiece::Cut { span_edges[k][0] } else { span_edges[k][1] };
6785                    // The swallowtail's point lies between the double curve's two uses.
6786                    let between = *piece == TrimPiece::Slot && span.chain.get(n + 1).is_some_and(|next| next.0 == TrimPiece::Slot);
6787                    let tip = match (span.tip, vertices[k].1) {
6788                        (Some(tip), Some(vertex)) if between && split_walls.contains(&index) => Some((tip[0], tip[1], vertex)),
6789                        _ => None,
6790                    };
6791                    list.push((edge, *forward, pcurve.clone(), tip));
6792                }
6793                at = span.lambdas[1];
6794            }
6795            list.push((piece_edges[trim.spans.len()], true, uv_line([at, v], [1.0, v])?, None));
6796            Ok(list)
6797        };
6798        let (bottom, top) = (row(0)?, row(1)?);
6799        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());
6800        if low.len() != high.len() || low.iter().zip(&high).any(|(a, b)| (a.0 - b.0).abs() > 1e-9) {
6801            return Err(refuse("wall_split", "a wall's split lines do not run from one end's row to the other's".into()));
6802        }
6803        // The split lines, each from its lower point to its upper.
6804        let mut lines: Vec<(u64, f64, f64, f64)> = Vec::with_capacity(low.len());
6805        for (below, above) in low.iter().zip(&high) {
6806            let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
6807            let along: Vec<Vec3> = ts.iter().map(|&s| frag(surface.evaluate(below.0, below.1 + (above.1 - below.1) * s), "wall")).collect::<Result<_, _>>()?;
6808            let edge = shell.edge(frag(crate::interpolate_curve(&along, 5, &ts), "split_line")?, below.2, above.2, false)?;
6809            lines.push((edge, below.0, below.1, above.1));
6810        }
6811        // Each row in the stretches between the split lines.
6812        let stretches = |list: Vec<RowPiece>| -> Vec<Vec<(u64, bool, NurbsCurve)>> {
6813            let mut out = vec![Vec::new()];
6814            for (edge, forward, pcurve, cut) in list {
6815                out.last_mut().expect("stretch").push((edge, forward, pcurve));
6816                if cut.is_some() {
6817                    out.push(Vec::new());
6818                }
6819            }
6820            out
6821        };
6822        let (bottoms, tops) = (stretches(bottom), stretches(top));
6823        // A strip between two split lines (or the wall's sides): along the
6824        // start row, up its far side, back along the end row, down its near
6825        // side; on the wall over its own stretch of u only.
6826        for j in 0..=lines.len() {
6827            let mut coedges = bottoms[j].clone();
6828            match lines.get(j) {
6829                Some(&(edge, u, v0, v1)) => coedges.push((edge, true, uv_line([u, v0], [u, v1])?)),
6830                None => coedges.push((orbits[&to], true, uv_line([1.0, 0.0], [1.0, 1.0])?)),
6831            }
6832            for (edge, forward, pcurve) in tops[j].iter().rev() {
6833                coedges.push((*edge, !*forward, frag(pcurve.reversed(), "reversed")?));
6834            }
6835            match j.checked_sub(1).map(|k| lines[k]) {
6836                Some((edge, u, v0, v1)) => coedges.push((edge, false, uv_line([u, v1], [u, v0])?)),
6837                None => coedges.push((orbits[&from], false, uv_line([0.0, 1.0], [0.0, 0.0])?)),
6838            }
6839            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));
6840            // A strip whose trim strays past its split line (beyond the tip)
6841            // takes the wall over that u too: the parameters are the wall's.
6842            if lines.len() > 0 && split_crossing_on() {
6843                // Its control points bound each pcurve (positive weights).
6844                for (_, _, pcurve) in &coedges {
6845                    for point in &pcurve.control_points {
6846                        let u = point.x / point.w;
6847                        if u < ua - 1e-9 {
6848                            ua = u.max(0.0);
6849                        }
6850                        if u > ub + 1e-9 {
6851                            ub = u.min(1.0);
6852                        }
6853                    }
6854                }
6855            }
6856            shell.face(restrict_u(surface, ua, ub)?, coedges);
6857        }
6858    }
6859    let body = shell.solid();
6860    let issues = body.validate();
6861    if !issues.is_empty() {
6862        // Name the faces whose coedges stray: their pcurves' ends on the surface
6863        // against their edges' ends.
6864        let mut notes = Vec::new();
6865        for face in body.shells.iter().flat_map(|s| &s.faces) {
6866            for coedge in &face.loops[0].coedges {
6867                let edge = body.edges.iter().find(|e| e.id == coedge.edge_id).expect("edge");
6868                let [p0, p1] = frag(coedge.pcurve.domain(), "domain")?;
6869                let a = frag(coedge.pcurve.evaluate(p0), "uv")?;
6870                let on = frag(face.surface.evaluate_extended(a.x, a.y), "on")?;
6871                let at = frag(edge.curve.evaluate(if coedge.forward { edge.t0 } else { edge.t1 }), "at")?;
6872                if on.sub(at).length() > 1e-6 {
6873                    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));
6874                }
6875                let _ = p1;
6876            }
6877        }
6878        return Err(refuse("assembly", format!("the lofted sweep is not valid: {:?}; {}", issues.first(), notes.iter().take(4).cloned().collect::<Vec<_>>().join("; "))));
6879    }
6880    check_single_pass(screw, first, &body, &std::collections::HashSet::new())?;
6881    Ok(body)
6882}
6883
6884/// Is the world point y inside the moving tool at some time of the motion?
6885/// Steps t by the distance over a bound on the speed of any tool point near y.
6886fn covered(screw: &Screw, split: &Split, reach: Option<&ToolReach>, y: Vec3, normal: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
6887    // A ball carried by a frame along a cubic: the question read off the cubic
6888    // (`BREP_SWEEP_BALL_COVER`, default on; its check mode walks as well).
6889    if crate::solid_sweep_one_pass::ball_cover_on() {
6890        if let (Some(frame), None, Shape::Revolved { origin, axis, meridian }) = (&screw.frame, &screw.turns, &split.shape) {
6891            if let Some((centre, r)) = crate::solid_sweep_one_pass::ball_of_revolved(*origin, *axis, meridian) {
6892                let offset = centre.sub(screw.a).length();
6893                if let Some(answer) = crate::solid_sweep_one_pass::ball_on_cubic_covered(frame.control, screw.t0, screw.t1, offset, r, y, margin) {
6894                    if !crate::solid_sweep_one_pass::ball_cover_check_on() {
6895                        return Ok(answer);
6896                    }
6897                    let walked = covered_walk(screw, split, reach, y, normal, margin)?;
6898                    crate::solid_sweep_one_pass::ball_cover_check_record(walked == answer);
6899                    return Ok(walked);
6900                }
6901            }
6902        }
6903    }
6904    covered_walk(screw, split, reach, y, normal, margin)
6905}
6906
6907/// [`covered`] by walking the motion.
6908fn covered_walk(screw: &Screw, split: &Split, reach: Option<&ToolReach>, y: Vec3, normal: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
6909    if reach.is_some_and(|reach| reach.never_inside(screw, y, normal, margin)) {
6910        return Ok(false);
6911    }
6912    if let Some(found) = reach.and_then(|reach| reach.turn_about_parallel_axis(screw, y, margin)) {
6913        return found;
6914    }
6915    let speed = preimage_speed_bound(screw, split, y);
6916    let floor = (screw.t1 - screw.t0) * 1e-7;
6917    let glide = Glide::of(screw, y);
6918    let mut t = screw.t0;
6919    let mut steps = 0usize;
6920    loop {
6921        let p = screw.invert(t, y);
6922        let d = split.distance(p);
6923        if d < -margin {
6924            return Ok(true);
6925        }
6926        if t >= screw.t1 {
6927            return Ok(false);
6928        }
6929        if steps > 2_000_000 {
6930            return Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into()));
6931        }
6932        let first = (d.abs() + margin) / speed;
6933        let second = glide.as_ref().map_or(0.0, |glide| glide.step(split, p, t, d, margin, speed, screw.t1 - t));
6934        let second = if second.is_finite() { second } else { 0.0 };
6935        t = (t + first.max(second).max(floor)).min(screw.t1);
6936        steps += 1;
6937    }
6938}
6939
6940/// The preimage of a probe under a plain screw, as an explicit curve: with
6941/// `u` the probe's offset from the axis square to it and `v = e × u`,
6942/// `p(t) = a + (e·(y − a) − advance(t))·e + cos(ωt)·u − sin(ωt)·v`. Its
6943/// second derivative is no longer than `ω²·|u| + 2|c₂|` (`curve`).
6944///
6945/// The walk in time steps by the tool's distance over the preimage's speed:
6946/// beside a wall the tool grazes (a thread's flank, a ball's groove) the
6947/// distance stays the probe's tiny offset through the whole contact and the
6948/// walk crawls, some π·√(2R/δ) steps a probe. Where the path runs along the
6949/// tool rather than into it, its tangent line stays clear of the tool for
6950/// far longer, and the path leaves that line by no more than `curve·h²/2`:
6951/// the second-order step is the longest `h` the tool's distance from the
6952/// tangent segment, less that, keeps above −margin. It is never shorter than
6953/// the first-order step, and skips no time the probe is deeper than the margin.
6954struct Glide {
6955    e: Vec3,
6956    u: Vec3,
6957    v: Vec3,
6958    omega: f64,
6959    c: f64,
6960    c2: f64,
6961    curve: f64,
6962    /// Under `frame_glide_on`, a frame riding a curve: the probe's preimage
6963    /// `a + R(−θ(t))(y − P(t))` read through the frame (frame, y).
6964    riding: Option<(Frame, Vec3)>,
6965    /// Under `turns_glide_on`, two turns about fixed axes: the probe's preimage under them (turns, y).
6966    turning: Option<(Turns, Vec3)>,
6967    /// Under `frame_windows_on`, the bound on |p''| over each of equal windows
6968    /// of the motion (start, width, bounds), each no looser than `curve`.
6969    windows: Option<(f64, f64, Vec<f64>)>,
6970}
6971
6972/// The riding frame's |p''| bound read window by window (default on; `=0`
6973/// keeps one bound over the whole motion). Either is a bound; a window's is
6974/// read where the step stays within it, so steps lengthen where the curve
6975/// bends gently.
6976fn frame_windows_on() -> bool {
6977    crate::switch!("BREP_SWEEP_FRAME_WINDOWS", true)
6978}
6979
6980/// The second-order step for two turns about fixed axes (`BREP_SWEEP_TURNS_GLIDE`, default on;
6981/// `=0` restores the first-order walk).
6982fn turns_glide_on() -> bool {
6983    crate::switch!("BREP_SWEEP_TURNS_GLIDE", true)
6984}
6985
6986/// The second-order step for frames riding a curve (default on; `=0` restores the first-order walk).
6987fn frame_glide_on() -> bool {
6988    crate::switch!("BREP_SWEEP_FRAME_GLIDE", true)
6989}
6990
6991impl Glide {
6992    fn of(screw: &Screw, y: Vec3) -> Option<Glide> {
6993        if let (Some(frame), None, true) = (&screw.frame, &screw.turns, frame_glide_on()) {
6994            return Glide::riding(screw, frame, y);
6995        }
6996        if let (Some(turns), true) = (&screw.turns, turns_glide_on()) {
6997            return Glide::turning(turns, y);
6998        }
6999        if screw.frame.is_some() || screw.turns.is_some() {
7000            return None;
7001        }
7002        let r = y.sub(screw.a);
7003        let u = r.sub(screw.e.scale(r.dot(screw.e)));
7004        let curve = screw.omega * screw.omega * u.length() + 2.0 * screw.c2.abs();
7005        // A bound rounded to nothing, or below the normal range, is not one:
7006        // only a slide (no turn, no rise) is straight.
7007        let straight = screw.omega == 0.0 && screw.c2 == 0.0;
7008        if !straight && !(curve >= f64::MIN_POSITIVE && curve.is_finite()) {
7009            return None;
7010        }
7011        Some(Glide { e: screw.e, u, v: screw.e.cross(u), omega: screw.omega, c: screw.c, c2: screw.c2, curve, riding: None, turning: None, windows: None })
7012    }
7013
7014    /// A frame riding a planar cubic: the preimage `p = a + R(−θ) q`,
7015    /// `q = y − P(t)`, turns about `up`, and its second derivative is
7016    /// `R(−θ)(θ'² up×(up×q) − θ'' up×q + 2θ' up×P' − P'')`, so
7017    /// `|p''| ≤ (θ'² + |θ''|)·|q| + 2|θ'|·|P'| + |P''|`. Over the motion's
7018    /// span |P'| and |P''| are bounded by their control polygons and |P'''|
7019    /// is a constant; `θ' = up·(P'×P'')/|P'|²` and θ'' are bounded through a
7020    /// lower bound on |P'| (its samples less |P''| times half their spacing;
7021    /// no glide where that is not positive); `|q| ≤ |y − P(t₀)| + |P'|·span`.
7022    fn riding(screw: &Screw, frame: &Frame, y: Vec3) -> Option<Glide> {
7023        let [p0, p1, p2, p3] = frame.control;
7024        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);
7025        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);
7026        let third = p3.sub(p2.scale(3.0)).add(p1.scale(3.0)).sub(p0).scale(6.0).length();
7027        let (t0, t1) = (screw.t0, screw.t1);
7028        let n = 256;
7029        let slowest = (0..=n).map(|k| frame.first(t0 + (t1 - t0) * k as f64 / n as f64).length()).fold(f64::INFINITY, f64::min);
7030        let floor = slowest - second * 0.5 * (t1 - t0) / n as f64;
7031        if !(floor > 0.0) {
7032            return None;
7033        }
7034        let w1 = first * second / (floor * floor);
7035        let w2 = third * first / (floor * floor) + 2.0 * first * first * second * second / floor.powi(4);
7036        let q = y.sub(frame.point(t0)).length() + first * (t1 - t0);
7037        let curve = (w1 * w1 + w2) * q + 2.0 * w1 * first + second;
7038        if !(curve.is_finite() && curve >= f64::MIN_POSITIVE) {
7039            return None;
7040        }
7041        // Window by window: |P'| by the hull of its quadratic over the window,
7042        // |P''| (linear) at the window's ends, the floor on |P'| from eight
7043        // samples less |P''| times half their spacing, |q| from the window's
7044        // start; each bound kept no looser than the whole motion's.
7045        let windows = frame_windows_on().then(|| {
7046            let count = 32usize;
7047            let width = (t1 - t0) / count as f64;
7048            let bounds = (0..count)
7049                .map(|i| {
7050                    let (a, b) = (t0 + width * i as f64, t0 + width * (i + 1) as f64);
7051                    let (da, db) = (frame.first(a), frame.first(b));
7052                    let middle = da.add(frame.second(a).scale(0.5 * (b - a)));
7053                    let first_w = da.length().max(db.length()).max(middle.length());
7054                    let second_w = frame.second(a).length().max(frame.second(b).length());
7055                    let m = 8;
7056                    let slow = (0..=m).map(|j| frame.first(a + (b - a) * j as f64 / m as f64).length()).fold(f64::INFINITY, f64::min);
7057                    let floor_w = slow - second_w * 0.5 * (b - a) / m as f64;
7058                    if !(floor_w > 0.0) {
7059                        return curve;
7060                    }
7061                    let w1 = first_w * second_w / (floor_w * floor_w);
7062                    let w2 = third * first_w / (floor_w * floor_w) + 2.0 * first_w * first_w * second_w * second_w / floor_w.powi(4);
7063                    let q_w = y.sub(frame.point(a)).length() + first_w * (b - a);
7064                    let c = (w1 * w1 + w2) * q_w + 2.0 * w1 * first_w + second_w;
7065                    if c.is_finite() && c >= f64::MIN_POSITIVE { c.min(curve) } else { curve }
7066                })
7067                .collect::<Vec<f64>>();
7068            (t0, width, bounds)
7069        });
7070        let zero = Vec3::new(0.0, 0.0, 0.0);
7071        Some(Glide { e: frame.up, u: zero, v: zero, omega: 0.0, c: 0.0, c2: 0.0, curve, riding: Some((*frame, y)), turning: None, windows })
7072    }
7073
7074    /// Two turns about fixed axes (unit `d₀`, `d₁` through `P₀`, `P₁` at rates `r₀`, `r₁`): the
7075    /// preimage `p = P₀ + R₀(−r₀t)(x − P₀)`, `x = P₁ + R₁(−r₁t)(y − P₁)`. With `x' = −r₁ d₁×(x − P₁)`
7076    /// and `x'' = −r₁ d₁×x'`, `p'' = R₀(x'') − 2r₀ d₀×R₀(x') + r₀² d₀×(d₀×(p − P₀))`, so
7077    /// `|p''| ≤ (r₁² + 2|r₀ r₁|)·|y − P₁| + r₀²·(|y − P₁| + |P₁ − P₀|)` (rotations keep lengths).
7078    fn turning(turns: &Turns, y: Vec3) -> Option<Glide> {
7079        let a = y.sub(turns.points[1]).length();
7080        let d = a + turns.points[1].sub(turns.points[0]).length();
7081        let (r0, r1) = (turns.rates[0].abs(), turns.rates[1].abs());
7082        let curve = (r1 * r1 + 2.0 * r0 * r1) * a + r0 * r0 * d;
7083        if !(curve.is_finite() && curve >= f64::MIN_POSITIVE) {
7084            return None;
7085        }
7086        let zero = Vec3::new(0.0, 0.0, 0.0);
7087        Some(Glide { e: zero, u: zero, v: zero, omega: 0.0, c: 0.0, c2: 0.0, curve, riding: None, turning: Some((*turns, y)), windows: None })
7088    }
7089
7090    /// The bound on |p''| over [t, t + h]: the most of the windows it meets,
7091    /// or the whole motion's.
7092    fn curve_over(&self, t: f64, h: f64) -> f64 {
7093        match &self.windows {
7094            Some((t0, width, bounds)) => {
7095                let last = bounds.len() - 1;
7096                let index = |x: f64| -> usize {
7097                    let k = ((x - t0) / width).floor();
7098                    if k.is_nan() || k <= 0.0 { 0 } else { (k as usize).min(last) }
7099                };
7100                bounds[index(t)..=index(t + h)].iter().fold(0.0f64, |a, &b| a.max(b))
7101            }
7102            None => self.curve,
7103        }
7104    }
7105
7106    /// `p'(t)`.
7107    fn velocity(&self, t: f64) -> Vec3 {
7108        if let Some((turns, y)) = &self.turning {
7109            let (p0, p1) = (turns.points[0], turns.points[1]);
7110            let (d0, d1) = (turns.directions[0], turns.directions[1]);
7111            let (r0, r1) = (turns.rates[0], turns.rates[1]);
7112            let arm1 = y.sub(p1).rotate_about(d1, -r1 * t);
7113            let x_rate = d1.cross(arm1).scale(-r1);
7114            let arm0 = p1.add(arm1).sub(p0).rotate_about(d0, -r0 * t);
7115            return x_rate.rotate_about(d0, -r0 * t).sub(d0.cross(arm0).scale(r0));
7116        }
7117        if let Some((frame, y)) = &self.riding {
7118            // p' = R(−θ)(−θ' up×q − P'), q = y − P(t).
7119            let q = y.sub(frame.point(t));
7120            let inner = frame.up.cross(q).scale(-frame.angle_rate(t)).sub(frame.first(t));
7121            return inner.rotate_about(frame.up, -frame.angle(t));
7122        }
7123        let (sin, cos) = (self.omega * t).sin_cos();
7124        self.e
7125            .scale(-(self.c + 2.0 * self.c2 * t))
7126            .sub(self.u.scale(self.omega * sin))
7127            .sub(self.v.scale(self.omega * cos))
7128    }
7129
7130    /// The second-order step from `t`, where the preimage is `p` at the
7131    /// tool's distance `d` (at most `left`; 0 when it finds none).
7132    #[allow(clippy::too_many_arguments)]
7133    fn step(&self, split: &Split, p: Vec3, t: f64, d: f64, margin: f64, speed: f64, left: f64) -> f64 {
7134        let velocity = self.velocity(t);
7135        // (the planes' root is read in closed form under one bound: the
7136        // windows' over the rest of the motion)
7137        let m = if self.windows.is_some() { self.curve_over(t, left) } else { self.curve };
7138        match &split.shape {
7139            // Each face's plane alone bounds the distance from below:
7140            // g(t + h) ≥ g + g'·h − m·h²/2, held above −margin up to the root.
7141            Shape::Planes(planes) => {
7142                let mut best = 0.0f64;
7143                for (n, offset) in planes {
7144                    let g = n.dot(p) - offset;
7145                    if g + margin <= 0.0 {
7146                        continue;
7147                    }
7148                    let slope = n.dot(velocity);
7149                    // The root, in the form that neither overflows nor cancels.
7150                    let h = if m > 0.0 {
7151                        let root = slope.hypot((2.0 * m * (g + margin)).sqrt());
7152                        if slope >= 0.0 { (slope + root) / m } else { 2.0 * (g + margin) / (root - slope) }
7153                    } else if slope >= 0.0 {
7154                        left
7155                    } else {
7156                        (g + margin) / -slope
7157                    };
7158                    if h.is_finite() {
7159                        best = best.max(h);
7160                    }
7161                }
7162                best.min(left)
7163            }
7164            // In the meridian plane: the path (ρ, z) about the tool's axis and
7165            // its tangent segment, whose distance from the outline is bounded
7166            // below piece by piece; the path leaves the segment by at most
7167            // m₂·h²/2, m₂ = 2m + speed²/ρ_min (the radius' bend), ρ_min > 0.
7168            Shape::Revolved { origin, axis, meridian } => {
7169                if d < 0.0 {
7170                    return 0.0;
7171                }
7172                let r = p.sub(*origin);
7173                let z = r.dot(*axis);
7174                let flat = r.sub(axis.scale(z));
7175                let rho = flat.length();
7176                if rho <= 0.0 {
7177                    return 0.0;
7178                }
7179                let dz = velocity.dot(*axis);
7180                let dflat = velocity.sub(axis.scale(dz));
7181                let drho = flat.dot(dflat) / rho;
7182                let q = [rho, z];
7183                let walk_sqrt = walk_sqrt_on();
7184                let mut best = 0.0f64;
7185                let mut h = (d + margin) / speed;
7186                for _ in 0..64 {
7187                    h *= 2.0;
7188                    if h > left {
7189                        h = left;
7190                    }
7191                    // Under the windows, the speed over [t, t + h] by the
7192                    // step's own: |p'| ≤ |p'(t)| + m·h, no more than `speed`.
7193                    let (m, speed) = if self.windows.is_some() {
7194                        let m = self.curve_over(t, h);
7195                        (m, (velocity.length() + m * h).min(speed))
7196                    } else {
7197                        (m, speed)
7198                    };
7199                    let low = rho - speed * h;
7200                    if low <= 0.0 {
7201                        break;
7202                    }
7203                    let bend = 2.0 * m + speed * speed / low;
7204                    let end = [rho + drho * h, z + dz * h];
7205                    let clear = if walk_sqrt {
7206                        meridian.iter().map(|piece| segment_clearance_sqrt(piece, q, end)).fold(f64::INFINITY, f64::min)
7207                    } else {
7208                        meridian.iter().map(|piece| segment_clearance(piece, q, end)).fold(f64::INFINITY, f64::min)
7209                    };
7210                    // A segment that touches the outline may enter the tool: no bound.
7211                    let held = clear - 0.5 * bend * h * h;
7212                    if !held.is_finite() || clear <= 0.0 || held < -margin {
7213                        break;
7214                    }
7215                    best = h;
7216                    if h >= left {
7217                        break;
7218                    }
7219                }
7220                best
7221            }
7222        }
7223    }
7224}
7225
7226/// A lower bound on the distance between the segment `a`–`b` and a meridian
7227/// piece: a line piece's exact distance (0 where they cross), an arc's from
7228/// its whole circle.
7229fn segment_clearance(piece: &OutlinePiece, a: [f64; 2], b: [f64; 2]) -> f64 {
7230    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
7231    let dot = |p: [f64; 2], q: [f64; 2]| p[0] * q[0] + p[1] * q[1];
7232    let cross = |p: [f64; 2], q: [f64; 2]| p[0] * q[1] - p[1] * q[0];
7233    let to_segment = |x: [f64; 2], s: [f64; 2], e: [f64; 2]| -> f64 {
7234        let d = sub(e, s);
7235        let len2 = dot(d, d);
7236        let w = if len2 > 0.0 { (dot(sub(x, s), d) / len2).clamp(0.0, 1.0) } else { 0.0 };
7237        let foot = [s[0] + d[0] * w, s[1] + d[1] * w];
7238        let gap = sub(x, foot);
7239        gap[0].hypot(gap[1])
7240    };
7241    match *piece {
7242        OutlinePiece::Line { from, to } => {
7243            let (d1, d2) = (sub(b, a), sub(to, from));
7244            let denom = cross(d1, d2);
7245            if denom != 0.0 {
7246                let w = sub(from, a);
7247                let (s, t) = (cross(w, d2) / denom, cross(w, d1) / denom);
7248                if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
7249                    return 0.0;
7250                }
7251            }
7252            to_segment(a, from, to).min(to_segment(b, from, to)).min(to_segment(from, a, b)).min(to_segment(to, a, b))
7253        }
7254        OutlinePiece::Arc { centre, radius, .. } => {
7255            let near = to_segment(centre, a, b);
7256            let far = { let (x, y) = (sub(a, centre), sub(b, centre)); x[0].hypot(x[1]).max(y[0].hypot(y[1])) };
7257            (near - radius).max(radius - far).max(0.0)
7258        }
7259        // no bound read for an ellipse: zero is one
7260        OutlinePiece::Ellipse { .. } => 0.0,
7261    }
7262}
7263
7264/// The switch for [`segment_clearance_sqrt`] in the walk's second-order step
7265/// (default on; `=0` reads `segment_clearance`).
7266fn walk_sqrt_on() -> bool {
7267    crate::switch!("BREP_SWEEP_WALK_SQRT", true)
7268}
7269
7270/// [`segment_clearance`] without `hypot`: a line piece's least squared gap,
7271/// one square root; an arc's lengths by `sqrt` (within a rounding of `hypot`).
7272/// A square outside the range where squaring is exact to a rounding (below
7273/// 1e-290, which takes in an underflow to zero, or above 1e290) reads the
7274/// piece by `segment_clearance` instead.
7275fn segment_clearance_sqrt(piece: &OutlinePiece, a: [f64; 2], b: [f64; 2]) -> f64 {
7276    let in_range = |x: f64| (1e-290..=1e290).contains(&x);
7277    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
7278    let dot = |p: [f64; 2], q: [f64; 2]| p[0] * q[0] + p[1] * q[1];
7279    let cross = |p: [f64; 2], q: [f64; 2]| p[0] * q[1] - p[1] * q[0];
7280    let to_segment_squared = |x: [f64; 2], s: [f64; 2], e: [f64; 2]| -> f64 {
7281        let d = sub(e, s);
7282        let len2 = dot(d, d);
7283        let w = if len2 > 0.0 { (dot(sub(x, s), d) / len2).clamp(0.0, 1.0) } else { 0.0 };
7284        let gap = sub(x, [s[0] + d[0] * w, s[1] + d[1] * w]);
7285        dot(gap, gap)
7286    };
7287    match *piece {
7288        OutlinePiece::Line { from, to } => {
7289            let (d1, d2) = (sub(b, a), sub(to, from));
7290            let denom = cross(d1, d2);
7291            if denom != 0.0 {
7292                let w = sub(from, a);
7293                let (s, t) = (cross(w, d2) / denom, cross(w, d1) / denom);
7294                if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
7295                    return 0.0;
7296                }
7297            }
7298            let least = to_segment_squared(a, from, to)
7299                .min(to_segment_squared(b, from, to))
7300                .min(to_segment_squared(from, a, b))
7301                .min(to_segment_squared(to, a, b));
7302            if !in_range(least) {
7303                return segment_clearance(piece, a, b);
7304            }
7305            least.sqrt()
7306        }
7307        OutlinePiece::Arc { centre, radius, .. } => {
7308            let near = to_segment_squared(centre, a, b);
7309            let (x, y) = (sub(a, centre), sub(b, centre));
7310            let far = dot(x, x).max(dot(y, y));
7311            if !(in_range(near) && in_range(far)) {
7312                return segment_clearance(piece, a, b);
7313            }
7314            (near.sqrt() - radius).max(radius - far.sqrt()).max(0.0)
7315        }
7316        OutlinePiece::Ellipse { .. } => 0.0,
7317    }
7318}
7319
7320/// A bound on how fast the tool-frame preimage `screw.invert(t, y)` of the
7321/// world point `y` moves per unit `t`; the tool's distance (1-Lipschitz)
7322/// changes no faster along it.
7323///
7324/// A plain screw about one fixed axis carries the preimage round that axis at
7325/// its distance from it, `ρ`, and along it at the advance's rate, two motions
7326/// square to each other: no faster than `hypot(|ω|·ρ, rate)`. A point near the axis barely moves, so a probe beside
7327/// a tool point on the axis (a coin turned about a line through its rim) walks
7328/// the motion in a few long steps, not millions of floor-sized ones. A riding
7329/// frame or two turns keep the coarser bound through `a`.
7330fn preimage_speed_bound(screw: &Screw, split: &Split, y: Vec3) -> f64 {
7331    let speed = if screw.frame.is_none() && screw.turns.is_none() {
7332        let r = y.sub(screw.a);
7333        let rho = r.sub(screw.e.scale(r.dot(screw.e))).length();
7334        (screw.omega.abs() * rho).hypot(screw.rate_bound())
7335    } else {
7336        let reach = y.sub(screw.a).length() + split.scale + screw.extent;
7337        screw.omega.abs() * reach + screw.rate_bound()
7338    };
7339    speed.max(1e-300)
7340}
7341
7342/// How far a revolved tool reaches about a plain screw's axis: its axial
7343/// coordinate `e·(x − a)` lies within `axial` and its distance from the axis
7344/// within `radial`, for every tool point `x` (bounds, not extremes: a meridian
7345/// line is bounded at its ends, an arc by its whole circle).
7346///
7347/// A plain screw keeps each point's distance from its axis and shifts its
7348/// axial coordinate only by the advance (a slide keeps every coordinate across
7349/// its direction), so a point `y` whose preimage stays outside these bounds
7350/// all through the motion is never inside the tool, and `covered` need not
7351/// walk the motion to say so. Without this a probe beside a face the tool runs
7352/// along all through the motion (the flat top of a coin turned about a line
7353/// through its rim, the floor of an end mill's pass) creeps through it in
7354/// steps of its own tiny distance from the tool.
7355struct ToolReach {
7356    /// The tool's revolution: its origin less the screw's point, its unit axis
7357    /// and its meridian (radius, height along the axis).
7358    base: Vec3,
7359    axis: Vec3,
7360    meridian: Vec<OutlinePiece>,
7361    axial: [f64; 2],
7362    radial: [f64; 2],
7363}
7364
7365/// The largest of |m₀|·p + m₁·q over a meridian (p ≥ 0): a line at its ends,
7366/// an arc by its circle (Cauchy–Schwarz on the offset from its centre).
7367fn meridian_most(meridian: &[OutlinePiece], p: f64, q: f64) -> f64 {
7368    meridian
7369        .iter()
7370        .map(|piece| match *piece {
7371            OutlinePiece::Line { from, to } => (from[0].abs() * p + from[1] * q).max(to[0].abs() * p + to[1] * q),
7372            OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() * p + centre[1] * q + radius * p.hypot(q),
7373            // within the circle of its larger semi-axis
7374            OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() * p + centre[1] * q + semi[0].max(semi[1]) * p.hypot(q),
7375        })
7376        .fold(f64::NEG_INFINITY, f64::max)
7377}
7378
7379impl ToolReach {
7380    fn of(screw: &Screw, split: &Split) -> Option<ToolReach> {
7381        if screw.frame.is_some() || screw.turns.is_some() {
7382            return None;
7383        }
7384        let Shape::Revolved { origin, axis, meridian } = &split.shape else { return None };
7385        let e = screw.e;
7386        // x − a = (origin − a) + m₁·axis + m₀·(unit vector ⊥ axis).
7387        let base = origin.sub(screw.a);
7388        let along = axis.dot(e);
7389        let across = axis.cross(e).length();
7390        let middle = base.dot(e);
7391        let top = middle + meridian_most(meridian, across, along);
7392        let bottom = middle - meridian_most(meridian, across, -along);
7393        // Off the axis: within |(origin − a)⊥| ± (|m₀| + |m₁|·|axis⊥e|).
7394        let off = base.sub(e.scale(middle)).length();
7395        let spread = meridian
7396            .iter()
7397            .map(|piece| match *piece {
7398                OutlinePiece::Line { from, to } => (from[0].abs() + from[1].abs() * across).max(to[0].abs() + to[1].abs() * across),
7399                OutlinePiece::Arc { centre, radius, .. } => centre[0].abs() + centre[1].abs() * across + radius * (1.0 + across * across).sqrt(),
7400                OutlinePiece::Ellipse { centre, semi, .. } => centre[0].abs() + centre[1].abs() * across + semi[0].max(semi[1]) * (1.0 + across * across).sqrt(),
7401            })
7402            .fold(f64::NEG_INFINITY, f64::max);
7403        let reach = ToolReach { base, axis: *axis, meridian: meridian.clone(), axial: [bottom, top], radial: [off - spread, off + spread] };
7404        (top.is_finite() && bottom.is_finite() && spread.is_finite()).then_some(reach)
7405    }
7406
7407    /// `covered` for a turn (no advance) about an axis along the tool's own,
7408    /// walked in the tool's radius instead of in time; `None` when the motion
7409    /// is not such a turn.
7410    ///
7411    /// The preimage keeps its height along the tool's axis, and its distance
7412    /// from that axis is `ρ_w² = ρ² + s² − 2·ρ·s·cos(θ − θ_W)`, `ρ` its own
7413    /// distance from the turn's axis, `s` the tool axis' and `θ − θ_W` the
7414    /// angle between them, which the turn sweeps through an interval. So the
7415    /// preimage takes every radius between the least and the most `ρ_w` over
7416    /// that interval, and no other: it is ever deeper than the margin inside
7417    /// the tool if and only if some radius in that range is, at that height.
7418    /// The meridian's distance is 1-Lipschitz in the radius, so the range is
7419    /// walked by it. Each radius is met once, where the walk in time crawls
7420    /// past a probe the tool grazes (by the probe's own tiny offset over the
7421    /// turn's speed at each step).
7422    fn turn_about_parallel_axis(&self, screw: &Screw, y: Vec3, margin: f64) -> Option<Result<bool, KernelRefusal>> {
7423        if screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 || self.axis.cross(screw.e).length() != 0.0 {
7424            return None;
7425        }
7426        let e = screw.e;
7427        let r = y.sub(screw.a);
7428        // From the tool's origin to the probe, and its height along the tool's
7429        // axis (the turn keeps it).
7430        let from_tool = r.sub(self.base);
7431        let height = from_tool.dot(self.axis);
7432        // In the plane square to the axis, from the turn's axis: the probe `P`
7433        // and the tool's axis `W`, and the probe from the tool's axis, `P − W`
7434        // (formed as one difference, not as two far points less each other).
7435        let flat = |x: Vec3| x.sub(e.scale(x.dot(e)));
7436        let (probe, tool, apart) = (flat(r), flat(self.base), flat(from_tool));
7437        let (rho, s) = (probe.length(), tool.length());
7438        // Rounding of the coordinates read here, a few ulps of the largest: past
7439        // a quarter of the margin, the walk in time decides instead.
7440        let slack = 64.0 * f64::EPSILON * (r.length() + self.base.length() + height.abs());
7441        if slack > 0.25 * margin {
7442            return None;
7443        }
7444        // The preimage at time t is R(−ω·t)·P: its distance from the tool's axis
7445        // is |R(φ)·(P − W) + (R(φ) − I)·W|, with R(φ) − I = −2 sin²(φ/2) + sin φ·(e ×).
7446        let radius = |phi: f64| -> f64 {
7447            let half = (0.5 * phi).sin();
7448            let turned = apart.rotate_about(e, phi).add(tool.scale(-2.0 * half * half)).add(e.cross(tool).scale(phi.sin()));
7449            turned.length()
7450        };
7451        let (phi0, phi1) = (-screw.omega * screw.t0, -screw.omega * screw.t1);
7452        // The angle from W to P; R(φ)·P lies along W at start + φ ≡ 0 and opposite it at ≡ π.
7453        let start = if rho == 0.0 || s == 0.0 { 0.0 } else { e.dot(tool.cross(probe)).atan2(tool.dot(probe)) };
7454        let (lo, hi) = ((start + phi0).min(start + phi1), (start + phi0).max(start + phi1));
7455        // Does [lo, hi] hold an angle ≡ `at` (mod 2π)?
7456        let holds = |at: f64| (lo - at).div_euclid(TAU) != (hi - at).div_euclid(TAU) || (lo - at).rem_euclid(TAU) == 0.0;
7457        let ends = [radius(phi0), radius(phi1)];
7458        // | |P| − |W| | as |(P − W)·(P + W)| / (|P| + |W|): no cancellation.
7459        let nearest = if rho + s > 0.0 { apart.dot(probe.add(tool)).abs() / (rho + s) } else { 0.0 };
7460        let mut least = if holds(0.0) { nearest } else { ends[0].min(ends[1]) };
7461        let mut most = if holds(PI) { rho + s } else { ends[0].max(ends[1]) };
7462        least = (least - slack).max(0.0);
7463        most += slack;
7464        let mut at = least;
7465        // No floor on the step (it is never less than the margin): a floor
7466        // could step over a wall thinner than itself.
7467        let mut steps = 0usize;
7468        loop {
7469            let d = outline_signed_distance(&self.meridian, [at, height]);
7470            if d < -margin {
7471                return Some(Ok(true));
7472            }
7473            if at >= most {
7474                return Some(Ok(false));
7475            }
7476            if steps > 2_000_000 {
7477                return Some(Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into())));
7478            }
7479            at = (at + d.abs() + margin).min(most);
7480            steps += 1;
7481        }
7482    }
7483
7484    /// A bound on `u·(x − a)` over the tool, `u` a unit direction.
7485    fn support(&self, u: Vec3) -> f64 {
7486        let along = u.dot(self.axis);
7487        let across = u.sub(self.axis.scale(along)).length();
7488        u.dot(self.base) + meridian_most(&self.meridian, across, along)
7489    }
7490
7491    /// Is `y`'s preimage outside the tool's reach, or within half the margin
7492    /// of its edge, at every time of the motion? Then the tool's boundary is
7493    /// within half the margin of every preimage inside (straight out of the
7494    /// bound), and none is deeper than the margin. `normal`: the probe's face
7495    /// normal, across which a slide is also tried.
7496    fn never_inside(&self, screw: &Screw, y: Vec3, normal: Vec3, margin: f64) -> bool {
7497        let r = y.sub(screw.a);
7498        let z = r.dot(screw.e);
7499        let rho = r.sub(screw.e.scale(z)).length();
7500        let mut advances = vec![screw.advance(screw.t0), screw.advance(screw.t1)];
7501        if screw.c2 != 0.0 {
7502            let vertex = -screw.c / (2.0 * screw.c2);
7503            if vertex > screw.t0 && vertex < screw.t1 {
7504                advances.push(screw.advance(vertex));
7505            }
7506        }
7507        let low = advances.iter().copied().fold(f64::INFINITY, f64::min);
7508        let high = advances.iter().copied().fold(f64::NEG_INFINITY, f64::max);
7509        // Half the margin, less what rounding may have cost the coordinates
7510        // and bounds compared (a few ulps of the largest of them).
7511        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());
7512        let half = 0.5 * margin - 1e-13 * size;
7513        if half <= 0.0 {
7514            return false;
7515        }
7516        if z - high >= self.axial[1] - half || z - low <= self.axial[0] + half {
7517            return true;
7518        }
7519        if rho >= self.radial[1] - half || (self.radial[0] > 0.0 && rho <= self.radial[0] + half) {
7520            return true;
7521        }
7522        // A slide carries the preimage along its direction only. `u` is meant
7523        // across it, but whatever of `e` rounding leaves in it moves `u·r`
7524        // with the advance: take the least `u·r` reaches over the motion.
7525        if screw.omega == 0.0 {
7526            if let Ok(u) = normal.sub(screw.e.scale(normal.dot(screw.e))).normalized() {
7527                let drift = u.dot(screw.e);
7528                let least = u.dot(r) - (drift * low).max(drift * high);
7529                if least >= self.support(u) - half {
7530                    return true;
7531                }
7532            }
7533        }
7534        false
7535    }
7536}
7537
7538/// Refuse a sweep that covers points just outside its own faces.
7539///
7540/// `sliding`: faces the tool slides within all through the motion. A probe
7541/// just off one stays that near the tool the whole way, and the walk's step
7542/// is that distance: it stands a thousand times further off them (whatever
7543/// of the tool rides higher than that over such a face is still found).
7544fn check_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
7545    let (on, check) = (parallel_turn_one_pass_on(), parallel_turn_one_pass_check_on());
7546    if (on || check) && parallel_turn_one_pass(screw, split) {
7547        if !check {
7548            return Ok(());
7549        }
7550        let walked = walk_single_pass(screw, split, body, sliding);
7551        PARALLEL_TURN_CHECK.with(|cell| {
7552            let (n, bad) = cell.get();
7553            cell.set((n + 1, bad + u64::from(walked.is_err())));
7554        });
7555        return walked;
7556    }
7557    walk_single_pass(screw, split, body, sliding)
7558}
7559
7560/// `BREP_SWEEP_PARALLEL_TURN_ONE_PASS` (default on, `=0` walks): the one-pass check
7561/// answered in closed form for a solid of revolution turned (no advance)
7562/// about an axis parallel to its own, `D` from it, whose every section square
7563/// to the axes is one disc of radius `r(z) <= r_max < D`. A point's
7564/// distance from the turn's axis stays fixed; the disc at its height covers,
7565/// of the circle it runs on, one arc of half-angle at most `asin(r_max / D)`
7566/// centred on the tool's axis, and that arc moves round with the turn. The
7567/// point is inside over one interval of the turn unless the arc comes round
7568/// to it again: never while the turn is short of `2π − 2 asin(r_max / D)`.
7569/// The sampled walk is then not needed.
7570pub(crate) fn parallel_turn_one_pass_on() -> bool {
7571    crate::switch!("BREP_SWEEP_PARALLEL_TURN_ONE_PASS", true)
7572}
7573
7574/// `BREP_SWEEP_PARALLEL_TURN_ONE_PASS_CHECK` (default off): where the closed
7575/// form says one pass, the walk runs too and decides; the tally counts the
7576/// walks that refused ([`parallel_turn_one_pass_check_take`]).
7577fn parallel_turn_one_pass_check_on() -> bool {
7578    crate::switch!("BREP_SWEEP_PARALLEL_TURN_ONE_PASS_CHECK", false)
7579}
7580
7581thread_local! {
7582    static PARALLEL_TURN_CHECK: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
7583}
7584
7585/// (closed-form one-pass answers walked, walks that refused) on this thread
7586/// since the last call.
7587pub fn parallel_turn_one_pass_check_take() -> (u64, u64) {
7588    PARALLEL_TURN_CHECK.with(|cell| cell.replace((0, 0)))
7589}
7590
7591/// Whether the closed form above proves the sweep one pass.
7592fn parallel_turn_one_pass(screw: &Screw, split: &Split) -> bool {
7593    if screw.frame.is_some() || screw.turns.is_some() || screw.c != 0.0 || screw.c2 != 0.0 || screw.omega == 0.0 {
7594        return false;
7595    }
7596    let Shape::Revolved { origin, axis, meridian } = &split.shape else { return false };
7597    if axis.cross(screw.e).length() > 1e-12 {
7598        return false;
7599    }
7600    let apart = origin.sub(screw.a);
7601    let d = apart.sub(screw.e.scale(apart.dot(screw.e))).length();
7602    // Every section one disc: the outline less its pieces on the axis is one
7603    // run whose axial coordinate never turns back (lines; arcs without a
7604    // turning point inside), and its largest radius.
7605    // On the axis exactly: a wall any way off it is a bore, however thin.
7606    let on_axis = |p: [f64; 2]| p[0] == 0.0;
7607    let axial: Vec<bool> = meridian.iter().map(|piece| matches!(*piece, OutlinePiece::Line { from, to } if on_axis(from) && on_axis(to))).collect();
7608    let changes = (0..axial.len()).filter(|&k| axial[k] != axial[(k + 1) % axial.len()]).count();
7609    if changes != 2 {
7610        return false; // the pieces on the axis are not one run of them
7611    }
7612    let mut direction = 0i32;
7613    let mut r_max = 0.0f64;
7614    let mut agree = |sign: i32| -> bool {
7615        if sign == 0 {
7616            return true;
7617        }
7618        if direction == 0 {
7619            direction = sign;
7620        }
7621        direction == sign
7622    };
7623    for piece in meridian {
7624        match *piece {
7625            OutlinePiece::Line { from, to } => {
7626                if on_axis(from) && on_axis(to) {
7627                    continue;
7628                }
7629                if from[0] < -1e-12 || to[0] < -1e-12 {
7630                    return false;
7631                }
7632                r_max = r_max.max(from[0]).max(to[0]);
7633                let rise = to[1] - from[1];
7634                if !agree(if rise > 0.0 { 1 } else if rise < 0.0 { -1 } else { 0 }) {
7635                    return false;
7636                }
7637            }
7638            OutlinePiece::Arc { centre, radius, start, end } => {
7639                let (lo, hi) = (start.min(end), start.max(end));
7640                if !(hi > lo) || !(radius > 0.0) {
7641                    return false;
7642                }
7643                // Turning points of the axial coordinate (cos a = 0) strictly inside.
7644                let first = ((lo - FRAC_PI_2) / PI).floor() as i64 + 1;
7645                if FRAC_PI_2 + first as f64 * PI < hi - 1e-12 {
7646                    return false;
7647                }
7648                // Its radial reach: the ends, and a = 0 (mod 2π) inside.
7649                let reach = |a: f64| centre[0] + radius * a.cos();
7650                r_max = r_max.max(reach(start)).max(reach(end));
7651                if (lo / TAU).ceil() * TAU < hi {
7652                    r_max = r_max.max(centre[0] + radius);
7653                }
7654                if centre[0] - radius < -1e-12 && (lo..hi).contains(&PI) {
7655                    return false;
7656                }
7657                let mid = 0.5 * (start + end);
7658                let rise = radius * mid.cos() * (end - start).signum();
7659                if !agree(if rise > 0.0 { 1 } else if rise < 0.0 { -1 } else { 0 }) {
7660                    return false;
7661                }
7662            }
7663            _ => return false,
7664        }
7665    }
7666    if !(r_max > 0.0 && r_max < d * (1.0 - 1e-9)) {
7667        return false;
7668    }
7669    let turn = (screw.omega * (screw.t1 - screw.t0)).abs();
7670    turn + 2.0 * (r_max / d).asin() < TAU * (1.0 - 1e-9)
7671}
7672
7673fn walk_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
7674    let margin = 1e-9 * split.scale;
7675    let reach = ToolReach::of(screw, split);
7676    for face in body.shells.iter().flat_map(|s| &s.faces) {
7677        let step = if sliding.contains(&face.id) { 1e-3 * split.scale } else { 1e-6 * split.scale };
7678        let surface = &face.surface;
7679        // Probe inside the face: towards each corner of its loop from the
7680        // average of its corners (caps are convex in their parameters), and on
7681        // a grid for the four-sided walls.
7682        let mut corners: Vec<[f64; 2]> = Vec::new();
7683        for coedge in &face.loops[0].coedges {
7684            let domain = frag(coedge.pcurve.domain(), "domain")?;
7685            for k in 0..4 {
7686                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 4.0), "pcurve")?;
7687                corners.push([p.x, p.y]);
7688            }
7689        }
7690        let middle = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
7691        let middle = [middle[0] / corners.len() as f64, middle[1] / corners.len() as f64];
7692        let mut probes: Vec<[f64; 2]> = vec![middle];
7693        for c in &corners {
7694            for w in [0.25, 0.5, 0.75, 0.9, 0.99] {
7695                probes.push([middle[0] + (c[0] - middle[0]) * w, middle[1] + (c[1] - middle[1]) * w]);
7696            }
7697        }
7698        if surface.degree_v == 5 {
7699            let [u0, u1] = frag(surface.domain_u(), "domain")?;
7700            for i in 1..8 {
7701                for j in 1..64 {
7702                    probes.push([u0 + (u1 - u0) * i as f64 / 8.0, j as f64 / 64.0]);
7703                }
7704            }
7705        }
7706        let ([u0, u1], [v0, v1]) = (frag(surface.domain_u(), "domain")?, frag(surface.domain_v(), "domain")?);
7707        // Keep the probes inside the face's own loop (a face under a grazing
7708        // curve that dips is not convex in its parameters).
7709        let mut ring: Vec<[f64; 2]> = Vec::new();
7710        for coedge in &face.loops[0].coedges {
7711            let domain = frag(coedge.pcurve.domain(), "domain")?;
7712            for k in 0..32 {
7713                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 32.0), "pcurve")?;
7714                ring.push([p.x, p.y]);
7715            }
7716        }
7717        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])]));
7718        for i in 1..12 {
7719            for j in 1..12 {
7720                probes.push([lo[0] + (hi[0] - lo[0]) * i as f64 / 12.0, lo[1] + (hi[1] - lo[1]) * j as f64 / 12.0]);
7721            }
7722        }
7723        let inside = |q: [f64; 2]| -> bool {
7724            let mut crossings = 0;
7725            for k in 0..ring.len() {
7726                let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
7727                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]) {
7728                    crossings += 1;
7729                }
7730            }
7731            crossings % 2 == 1
7732        };
7733        for [u, v] in probes.into_iter().filter(|&q| inside(q)) {
7734            let p = frag(surface.evaluate(u, v), "probe")?;
7735            let (hu, hv) = (1e-6 * (u1 - u0), 1e-6 * (v1 - v0));
7736            // Derivatives, not raw differences: their cross product is
7737            // measured against an absolute zero.
7738            let (ua, ub, va, vb) = ((u - hu).max(u0), (u + hu).min(u1), (v - hv).max(v0), (v + hv).min(v1));
7739            let du = frag(surface.evaluate(ub, v), "probe")?.sub(frag(surface.evaluate(ua, v), "probe")?).scale(1.0 / (ub - ua));
7740            let dv = frag(surface.evaluate(u, vb), "probe")?.sub(frag(surface.evaluate(u, va), "probe")?).scale(1.0 / (vb - va));
7741            let Ok(n) = du.cross(dv).normalized() else { continue };
7742            let n = if face.same_sense { n } else { n.scale(-1.0) };
7743            if covered(screw, split, reach.as_ref(), p.add(n.scale(step)), n, margin)? {
7744                return Err(refuse("folds", format!("the sweep passes over a point twice (just outside its own face at {p:?}); not one pass")));
7745            }
7746        }
7747    }
7748    Ok(())
7749}
7750
7751
7752#[path = "solid_sweep_ring_fold.rs"]
7753mod ring_fold;
7754
7755#[path = "solid_sweep_ball_screw.rs"]
7756mod ball_screw;
7757
7758
7759