Skip to main content

brep_construction/construction/
solid_sweep_caps.rs

1//! The WHOLE sweep of a solid along a one-parameter motion, ends included:
2//! caps and wall.
3//!
4//! Along a screw (a turn is a screw of zero advance, a slide one of zero turn)
5//! the velocity field, read in the tool's own frame, does not change with time:
6//! at a boundary point x with outward normal n it is
7//! `g(x, n) = (ω e × (x − a) + c e) · n`. So the tool's boundary splits once
8//! and for all into FRONT (g > 0) and BACK (g < 0) parts, and the GRAZING LOOP
9//! K between them (g = 0 inside a face, or a sharp edge whose two faces have
10//! opposite signs) is fixed on the tool. Where every point of space is inside
11//! the moving tool for ONE interval of time, the sweep over [t0, t1] is bounded
12//! by exactly
13//!
14//! - the back of the tool at t0 (where points start to be covered),
15//! - the front of the tool at t1 (where they stop),
16//! - the WALL: K carried by the motion from t0 to t1.
17//!
18//! The body is assembled directly from those faces with shared edges, never as
19//! a boolean of the tool with a tube (the two meet tangentially along K).
20//!
21//! The one-interval condition is CHECKED, not assumed: points just outside
22//! every built face are walked through the whole motion, and a sweep that
23//! covers any of them (a fold, a buried cap, a turn running into itself) is
24//! refused by name.
25//!
26//! Tools: a convex polyhedron (K a polygon of edges and face chords); a solid
27//! of revolution whose faces are cylinders or cones (split along standing
28//! generators, or along two grazing curves moving round them, fitted), flat
29//! ends wholly front or back, a hemisphere from a pole to an equator or a whole
30//! ball (split along a great circle), or a ring (torus, split along its two
31//! grazing curves round it). Caps keep the tool's exact surfaces; walls are
32//! the K curves carried by quintic splines through the exact motion and its
33//! first two derivatives (error h⁶, 48 spans a turn), a row per quarter turn.
34//!
35//! Moving grazing loops: [`sweep_solid_along`] (a solid of revolution carried
36//! by a frame along a planar curve) and [`sweep_solid_tumbled`] (two turns
37//! about skew axes) split the tool at sample times, sample each piece of K
38//! exactly and loft the walls through time; a tumble that passes over a point
39//! twice is built from one-pass spans of its time, joined.
40//! [`sweep_prism_along`] sweeps a prism along a frame by the plane region the
41//! moving outline covers (an arrangement of its corners', grazing points' and
42//! end positions' paths), extruded. [`sweep_solid_parts`] returns a folding
43//! polyhedron's sweep as the sweeps of its halves through the motion's axis.
44//!
45//! [`sweep_solid_clipped`] adds the case the caller only needs inside a
46//! region: a polyhedron TURNED about the region's axis with both end positions
47//! outside the region's wedge fills the wedge with its (ρ, z) shadow turned,
48//! bounded by exact conic arcs (edges) and segments (face chords).
49use crate::solid_sweep::outline_signed_distance;
50use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
51pub use crate::{make_line, make_revolution, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, OrRefuse, OutlinePiece, SolidMotion, Vec3, Vec4};
52use std::collections::HashMap;
53use std::f64::consts::{PI, TAU};
54
55/// A tool the whole sweep takes.
56#[derive(Clone, Debug)]
57pub enum SolidTool {
58    /// A convex polyhedron: its corners, and its faces as loops of corner
59    /// indices (either winding; outward is found from the centroid).
60    Polyhedron { vertices: Vec<Vec3>, faces: Vec<Vec<usize>> },
61    /// A solid of revolution: the region `meridian` bounds in the
62    /// half-plane spanned by `radial` (first coordinate, the distance from the
63    /// axis, ≥ 0) and `axis_direction` (second coordinate), turned about the
64    /// axis through `axis_origin` (as [`crate::SweptTool::Revolved`]).
65    Revolved { axis_origin: Vec3, axis_direction: Vec3, radial: Vec3, meridian: Vec<OutlinePiece> },
66}
67
68/// Samples of a fitted pcurve: the image of its edge through the surface's
69/// exact inverse, interpolated (quintic). A rational chart's parameter has a
70/// second-derivative jump at its span joints, so the interpolant errs there
71/// as h³; at 576 that is below 1e-10 of a face's area.
72const PCURVE_SAMPLES: usize = 576;
73
74/// The prefix of every refusal of this operation.
75pub const SOLID_SWEEP_WHOLE_REFUSAL: &str = "sweepSolid";
76
77fn refuse(what: &'static str, message: String) -> KernelRefusal {
78    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
79}
80
81/// The stable slug of an unsupported-geometry refusal of this module.
82fn refused_as(error: &KernelRefusal) -> Option<&str> {
83    match &error.class {
84        crate::RefusalClass::UnsupportedGeometry { what } => Some(what.as_str()),
85        _ => None,
86    }
87}
88
89fn input(what: &'static str, message: String) -> KernelRefusal {
90    KernelRefusal::input(KernelStage::Collect, what, format!("{SOLID_SWEEP_WHOLE_REFUSAL}: {message}"))
91}
92
93fn frag<T>(result: Result<T, String>, what: &'static str) -> Result<T, KernelRefusal> {
94    result.or_refuse(KernelStage::Fragment, what)
95}
96
97/// The motion `x ↦ a + R(ω t)(x − a) + (c t + c₂ t²) e`: a screw (c₂ = 0;
98/// a turn has c = 0, a slide ω = 0), or a turn whose rise grows as it turns.
99#[derive(Clone, Copy, Debug)]
100pub struct Screw {
101    pub a: Vec3,
102    pub e: Vec3,
103    pub omega: f64,
104    pub c: f64,
105    pub c2: f64,
106    pub t0: f64,
107    pub t1: f64,
108    /// A frame riding a curve instead (then `a` is the curve's start, `e` the
109    /// frame's fixed up direction, `omega` a bound on its turning rate and `c`
110    /// on its speed).
111    pub frame: Option<Frame>,
112    /// Two turns about fixed axes instead (then `a` is the first axis' point).
113    pub turns: Option<Turns>,
114    /// The time whose velocity field splits the tool (default: the middle).
115    pub frozen: Option<f64>,
116    /// How many spans a ring's grazing loop is sampled over, per half of the
117    /// ring (`LOFT_SAMPLES` unless a loft found its rows too coarse).
118    pub loop_samples: usize,
119    /// How far the frame's origin travels from `a` (for speed bounds).
120    pub extent: f64,
121}
122
123/// Two turns driven by one parameter: first `rates[0]·t` about the first
124/// axis, then `rates[1]·t` about the second; both axes fixed in the world.
125#[derive(Clone, Copy, Debug)]
126pub struct Turns {
127    points: [Vec3; 2],
128    directions: [Vec3; 2],
129    rates: [f64; 2],
130}
131
132impl Turns {
133    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
134        let y = self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t));
135        self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t))
136    }
137    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
138        let x = self.points[1].add(y.sub(self.points[1]).rotate_about(self.directions[1], -self.rates[1] * t));
139        self.points[0].add(x.sub(self.points[0]).rotate_about(self.directions[0], -self.rates[0] * t))
140    }
141    /// Velocity of the tool point x at t, read back in the tool's frame.
142    fn velocity(&self, t: f64, x: Vec3) -> Vec3 {
143        let first = x.sub(self.points[0]).rotate_about(self.directions[0], self.rates[0] * t);
144        let y = self.points[0].add(first);
145        let moved = y.sub(self.points[1]).rotate_about(self.directions[1], self.rates[1] * t);
146        let inner = self.directions[0].cross(first).scale(self.rates[0]);
147        let world = self.directions[1].cross(moved).scale(self.rates[1]).add(inner.rotate_about(self.directions[1], self.rates[1] * t));
148        world.rotate_about(self.directions[1], -self.rates[1] * t).rotate_about(self.directions[0], -self.rates[0] * t)
149    }
150}
151
152/// A frame riding a planar cubic Bézier curve: origin on the curve, first
153/// axis along its tangent, a fixed up direction square to its plane.
154#[derive(Clone, Copy, Debug)]
155pub struct Frame {
156    pub control: [Vec3; 4],
157    pub up: Vec3,
158    /// The tangent's direction at the start.
159    pub start_tangent: Vec3,
160}
161
162impl Frame {
163    fn point(&self, s: f64) -> Vec3 {
164        let [p0, p1, p2, p3] = self.control;
165        let r = 1.0 - s;
166        p0.scale(r * r * r).add(p1.scale(3.0 * r * r * s)).add(p2.scale(3.0 * r * s * s)).add(p3.scale(s * s * s))
167    }
168    fn first(&self, s: f64) -> Vec3 {
169        let [p0, p1, p2, p3] = self.control;
170        let r = 1.0 - s;
171        p1.sub(p0).scale(3.0 * r * r).add(p2.sub(p1).scale(6.0 * r * s)).add(p3.sub(p2).scale(3.0 * s * s))
172    }
173    fn second(&self, s: f64) -> Vec3 {
174        let [p0, p1, p2, p3] = self.control;
175        p2.sub(p1.scale(2.0)).add(p0).scale(6.0 * (1.0 - s)).add(p3.sub(p2.scale(2.0)).add(p1).scale(6.0 * s))
176    }
177    /// The frame's turn from its start, about `up`.
178    fn angle(&self, s: f64) -> f64 {
179        let t = self.first(s);
180        self.up.dot(self.start_tangent.cross(t)).atan2(self.start_tangent.dot(t))
181    }
182    fn angle_rate(&self, s: f64) -> f64 {
183        let (d1, d2) = (self.first(s), self.second(s));
184        self.up.dot(d1.cross(d2)) / d1.dot(d1)
185    }
186}
187
188/// A turn about an axis whose rise along it grows as it turns: turned by t
189/// (radians, right-handed about `axis_direction`) the tool has risen
190/// `rise[0] t + rise[1] t²`, for t from `from` to `to` (a variable-lead
191/// screw).
192#[derive(Clone, Copy, Debug)]
193pub struct RisingTurn {
194    pub axis_origin: Vec3,
195    pub axis_direction: Vec3,
196    pub rise: [f64; 2],
197    pub from: f64,
198    pub to: f64,
199}
200
201impl Screw {
202    pub fn from_motion(motion: &SolidMotion) -> Result<Self, KernelRefusal> {
203        let [step] = motion.steps.as_slice() else {
204            return Err(refuse("motion_steps", "only a single screw, turn or slide is swept whole here".into()));
205        };
206        let e = step
207            .axis_direction
208            .normalized()
209            .map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
210        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
211            return Err(input("range", "the motion's range must run forward".into()));
212        }
213        if step.turn == 0.0 && step.advance == 0.0 {
214            return Err(input("still", "the motion does not move".into()));
215        }
216        Ok(Self { a: step.axis_origin, e, omega: step.turn, c: step.advance, c2: 0.0, t0: motion.from, t1: motion.to, frame: None, turns: None, frozen: None,
217        loop_samples: LOFT_SAMPLES, extent: 0.0 })
218    }
219
220    fn from_rising(motion: &RisingTurn) -> Result<Self, KernelRefusal> {
221        let e = motion.axis_direction.normalized().map_err(|_| input("axis", "the motion's axis has no direction".into()))?;
222        if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
223            return Err(input("range", "the motion's range must run forward".into()));
224        }
225        // The rise's rate must keep one sign, or the tool's front and back swap.
226        let rate = |t: f64| motion.rise[0] + 2.0 * motion.rise[1] * t;
227        if rate(motion.from) * rate(motion.to) <= 0.0 {
228            return Err(refuse("rise_turns", "the rise stops or turns back within the motion".into()));
229        }
230        Ok(Self { a: motion.axis_origin, e, omega: 1.0, c: motion.rise[0], c2: motion.rise[1], t0: motion.from, t1: motion.to, frame: None, turns: None, frozen: None,
231        loop_samples: LOFT_SAMPLES, extent: 0.0 })
232    }
233
234    fn advance(&self, t: f64) -> f64 {
235        self.c * t + self.c2 * t * t
236    }
237
238    /// The fastest the motion advances along its axis.
239    fn rate_bound(&self) -> f64 {
240        (self.c + 2.0 * self.c2 * self.t0).abs().max((self.c + 2.0 * self.c2 * self.t1).abs())
241    }
242
243    fn apply(&self, t: f64, x: Vec3) -> Vec3 {
244        if let Some(turns) = &self.turns {
245            return turns.apply(t, x);
246        }
247        if let Some(frame) = &self.frame {
248            return frame.point(t).add(x.sub(self.a).rotate_about(frame.up, frame.angle(t)));
249        }
250        self.a.add(x.sub(self.a).rotate_about(self.e, self.omega * t)).add(self.e.scale(self.advance(t)))
251    }
252
253    fn invert(&self, t: f64, y: Vec3) -> Vec3 {
254        if let Some(turns) = &self.turns {
255            return turns.invert(t, y);
256        }
257        if let Some(frame) = &self.frame {
258            return self.a.add(y.sub(frame.point(t)).rotate_about(frame.up, -frame.angle(t)));
259        }
260        self.a.add(y.sub(self.e.scale(self.advance(t))).sub(self.a).rotate_about(self.e, -self.omega * t))
261    }
262
263    /// Velocity, in the tool's frame, of the tool point x (the same at every t
264    /// for a screw; for a growing rise, at the middle of the motion; the split
265    /// it gives is checked against both ends).
266    pub fn velocity(&self, x: Vec3) -> Vec3 {
267        self.velocity_at(self.frozen.unwrap_or(0.5 * (self.t0 + self.t1)), x)
268    }
269
270    fn velocity_at(&self, t: f64, x: Vec3) -> Vec3 {
271        if let Some(turns) = &self.turns {
272            return turns.velocity(t, x);
273        }
274        if let Some(frame) = &self.frame {
275            // In the riding frame: the speed along the start tangent and the
276            // turn about up through the frame's origin.
277            return frame.start_tangent.scale(frame.first(t).length()).add(frame.up.cross(x.sub(self.a)).scale(frame.angle_rate(t)));
278        }
279        self.e.cross(x.sub(self.a)).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t))
280    }
281
282    /// Value, first and second t-derivative of the path of the tool point x.
283    fn jet(&self, t: f64, x: Vec3) -> (Vec3, Vec3, Vec3) {
284        let r = x.sub(self.a).rotate_about(self.e, self.omega * t);
285        let axial = self.e.scale(r.dot(self.e));
286        let radial = r.sub(axial);
287        let value = self.a.add(r).add(self.e.scale(self.advance(t)));
288        let first = self.e.cross(radial).scale(self.omega).add(self.e.scale(self.c + 2.0 * self.c2 * t));
289        let second = radial.scale(-self.omega * self.omega).add(self.e.scale(2.0 * self.c2));
290        (value, first, second)
291    }
292
293    fn move_point(&self, t: f64, p: &Vec4) -> Result<Vec4, KernelRefusal> {
294        let x = frag(p.point(), "control_point")?;
295        Ok(Vec4::from_point(self.apply(t, x), p.w))
296    }
297
298    fn move_curve(&self, t: f64, curve: &NurbsCurve) -> Result<NurbsCurve, KernelRefusal> {
299        let points = curve.control_points.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?;
300        frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "moved_curve")
301    }
302
303    fn move_surface(&self, t: f64, surface: &NurbsSurface) -> Result<NurbsSurface, KernelRefusal> {
304        let mut rows = Vec::with_capacity(surface.control_points.len());
305        for row in &surface.control_points {
306            rows.push(row.iter().map(|p| self.move_point(t, p)).collect::<Result<Vec<_>, _>>()?);
307        }
308        frag(
309            NurbsSurface::new(surface.degree_u, surface.degree_v, surface.knots_u.clone(), surface.knots_v.clone(), rows),
310            "moved_surface",
311        )
312    }
313}
314
315/// The motion's times at the ends of its rows: each row of wall turns at most
316/// a quarter turn (long thin faces cost every later reading, and the cut).
317fn row_times(screw: &Screw) -> Vec<f64> {
318    let turned = (screw.omega * (screw.t1 - screw.t0)).abs();
319    let rows = ((turned / (0.5 * PI)).ceil() as usize).max(1);
320    // Breaks off the round fractions of the range, where a caller's workpiece
321    // faces tend to lie (a precaution: an edge lying in a face makes a
322    // degenerate cut).
323    let at = |k: usize| match k {
324        0 => screw.t0,
325        k if k == rows => screw.t1,
326        k => screw.t0 + (screw.t1 - screw.t0) * (k as f64 - 0.381966011250105) / rows as f64,
327    };
328    (0..=rows).map(at).collect()
329}
330
331/// Spans of the quintic carry over [ta, tb]: 48 per turn (error ≈ r·h⁶/46080
332/// ≈ 1e-10·r), at least 4.
333fn carry_segments(screw: &Screw, ta: f64, tb: f64) -> usize {
334    let turned = (screw.omega * (tb - ta)).abs();
335    ((turned / TAU * 48.0).ceil() as usize).max(4)
336}
337
338/// Knots of the C² quintic carry on [0, 1].
339fn carry_knots(segments: usize) -> Vec<f64> {
340    let mut knots = vec![0.0; 6];
341    for k in 1..segments {
342        knots.extend([k as f64 / segments as f64; 3]);
343    }
344    knots.extend([1.0; 6]);
345    knots
346}
347
348/// Control points of the C² quintic spline through the exact path of the tool
349/// point x, its first and second derivatives at `segments + 1` times. Affine
350/// in x, so carrying a rational curve's control points carries the curve.
351fn carry_points(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Vec<Vec3> {
352    let h = (tb - ta) / segments as f64;
353    let at = |k: usize| screw.jet(ta + h * k as f64, x);
354    let piece = |k: usize| {
355        let ((f0, d0, a0), (f1, d1, a1)) = (at(k), at(k + 1));
356        [
357            f0,
358            f0.add(d0.scale(h / 5.0)),
359            f0.add(d0.scale(2.0 * h / 5.0)).add(a0.scale(h * h / 20.0)),
360            f1.sub(d1.scale(2.0 * h / 5.0)).add(a1.scale(h * h / 20.0)),
361            f1.sub(d1.scale(h / 5.0)),
362            f1,
363        ]
364    };
365    let mut points = Vec::with_capacity(3 * segments + 3);
366    let first = piece(0);
367    points.extend_from_slice(&first[..3]);
368    for k in 0..segments - 1 {
369        let (here, next) = (piece(k), piece(k + 1));
370        points.push(here[3]);
371        points.push(here[4].scale(2.0).sub(here[3]));
372        points.push(next[2]);
373    }
374    let last = piece(segments - 1);
375    points.extend_from_slice(&last[3..]);
376    points
377}
378
379fn carry_curve(screw: &Screw, x: Vec3, ta: f64, tb: f64, segments: usize) -> Result<NurbsCurve, KernelRefusal> {
380    frag(
381        NurbsCurve::new(5, carry_knots(segments), carry_points(screw, x, ta, tb, segments).into_iter().map(|p| Vec4::from_point(p, 1.0)).collect()),
382        "carry_curve",
383    )
384}
385
386/// A boundary curve of the tool (in its own frame), from point `start` to
387/// point `end` along its parameter.
388struct ToolCurve {
389    curve: NurbsCurve,
390    start: usize,
391    end: usize,
392    degenerate: bool,
393    /// Exact points at `LOFT_SAMPLES + 1` even steps of a natural parameter
394    /// from start to end (meridian place, angle), where a grazing curve
395    /// moves on the tool and its wall is lofted through time.
396    samples: Option<Vec<Vec3>>,
397}
398
399/// Steps of a grazing curve's exact samples for a lofted wall.
400pub const LOFT_SAMPLES: usize = 128;
401
402/// How near a lofted wall keeps to its exact grazing loop, as a fraction of
403/// the sweep's size: every exact sample of the loop, in the middle of every
404/// time span, is within this of the wall.
405///
406/// It was 5e-10. A wall that tight is heavy (a quintic's miss falls as the
407/// sixth power of its span, so each tenfold costs half again as many spans
408/// each way), and whoever reads the solid pays for every span. The measures
409/// do not need it: an interpolant's miss changes sign from span to span and
410/// all but cancels in a volume or an area. Over this hundredfold the lofted
411/// cases' volumes and areas moved by 2e-10 or less.
412const LOFT_TARGET: f64 = 5e-8;
413
414/// A face of the tool after the split along K: its exact surface (normal
415/// outward), its side, and its loop (curve, traversed forward?, pcurve in the
416/// direction of traversal).
417struct Cap {
418    surface: NurbsSurface,
419    front: bool,
420    coedges: Vec<(usize, bool, NurbsCurve)>,
421    /// The surface's exact parameters of a point (in the tool's frame), where
422    /// known: a lofted edge's pcurve is then its exact image.
423    chart: Option<Chart>,
424}
425
426/// How a cap's surface is parameterized, to invert it exactly.
427#[derive(Clone, Copy, Debug)]
428enum Chart {
429    /// `plane_patch(origin, u, v, …)`: (x − origin)·u, (x − origin)·v.
430    Plane { origin: Vec3, u: Vec3, v: Vec3 },
431    /// `make_revolution(origin, w, generatrix, theta)` with the generatrix in the
432    /// meridian half-plane at angle `alpha` (from u1 towards u2).
433    Revolution { origin: Vec3, w: Vec3, u1: Vec3, u2: Vec3, alpha: f64, theta: f64, spans_u: usize, meridian: MeridianChart },
434}
435
436#[derive(Clone, Copy, Debug)]
437enum MeridianChart {
438    /// A segment from m0 to m1 in (ρ, z), parameter 0 -> 1.
439    Line { m0: [f64; 2], m1: [f64; 2] },
440    /// An arc about `centre` in (ρ, z) from angle `start` through `sweep`, as
441    /// `make_revolution` of a point makes it (`spans` arcs).
442    Arc { centre: [f64; 2], start: f64, sweep: f64, spans: usize },
443}
444
445impl Chart {
446    /// Is `x` on the chart's own axis, where its first parameter (the angle
447    /// about the axis) is not defined? A ball's pole.
448    fn at_pole(&self, x: Vec3) -> bool {
449        match *self {
450            Chart::Plane { .. } => false,
451            Chart::Revolution { origin, w, .. } => {
452                let r = x.sub(origin);
453                r.sub(w.scale(r.dot(w))).length() <= 1e-6 * r.length()
454            }
455        }
456    }
457
458    fn invert(&self, x: Vec3) -> [f64; 2] {
459        match *self {
460            Chart::Plane { origin, u, v } => {
461                let d = x.sub(origin);
462                [d.dot(u), d.dot(v)]
463            }
464            Chart::Revolution { origin, w, u1, u2, alpha, theta, spans_u, meridian } => {
465                let r = x.sub(origin);
466                let z = r.dot(w);
467                let rho = r.sub(w.scale(z)).length();
468                let mid = alpha + 0.5 * theta;
469                let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
470                let u = crate::circle_angle_to_parameter(spans_u, theta, psi - alpha);
471                let v = match meridian {
472                    MeridianChart::Line { m0, m1 } => {
473                        let (a, b) = (m1[0] - m0[0], m1[1] - m0[1]);
474                        ((rho - m0[0]) * a + (z - m0[1]) * b) / (a * a + b * b)
475                    }
476                    MeridianChart::Arc { centre, start, sweep, spans } => {
477                        let mid = start + 0.5 * sweep;
478                        let angle = mid + ((z - centre[1]).atan2(rho - centre[0]) - mid + PI).rem_euclid(TAU) - PI;
479                        crate::circle_angle_to_parameter(spans, sweep, angle - start)
480                    }
481                };
482                [u, v]
483            }
484        }
485    }
486}
487
488/// The spans `make_revolution` gives a sweep of `theta`.
489fn spans_of(surface_knots_u: &[f64]) -> usize {
490    (surface_knots_u.len() - 6) / 2 + 1
491}
492
493/// The tool's boundary split along K, in the tool's own frame.
494struct Split {
495    points: Vec<Vec3>,
496    curves: Vec<ToolCurve>,
497    caps: Vec<Cap>,
498    /// Flat ends that slide within their own plane all through the motion.
499    slides: Vec<SlideDisc>,
500    /// Cylinders that slide along their own generators all through it.
501    slide_sides: Vec<SlideSide>,
502    scale: f64,
503    shape: Shape,
504}
505
506/// A flat end about the tool's axis whose every point moves within the
507/// end's own plane (a turn about a parallel axis, a slide across the tool's
508/// axis): neither front nor back. What it sweeps is one face of the sweep in
509/// that plane, bounded by the rim's arcs beside back faces where the motion
510/// starts, its arcs beside front faces where it stops, and the paths of the
511/// points between them. `rim`: the rim's arcs counter-clockwise about the
512/// outward normal `u × v`, each with its direction of traversal.
513struct SlideDisc {
514    centre: Vec3,
515    u: Vec3,
516    v: Vec3,
517    rim: Vec<(usize, bool)>,
518}
519
520/// A cylinder about the tool's axis slid along that axis: every point moves
521/// along its own generator. What it sweeps is the cylinder from one rim where
522/// that rim's neighbour sits (back at the start, front at the end) to the
523/// other rim where its neighbour sits. `patches`: per stretch between two
524/// seam angles, (the angle it starts at, its sweep, the start rim's arc, the
525/// end rim's arc, the rim points at the start angle: start rim, end rim).
526struct SlideSide {
527    origin: Vec3,
528    w: Vec3,
529    patches: Vec<(f64, f64, usize, usize, [usize; 2])>,
530}
531
532/// What the membership oracle measures.
533enum Shape {
534    Planes(Vec<(Vec3, f64)>),
535    Revolved { origin: Vec3, axis: Vec3, meridian: Vec<OutlinePiece> },
536}
537
538impl Split {
539    /// Signed distance to the tool in its own frame (negative inside).
540    fn distance(&self, x: Vec3) -> f64 {
541        match &self.shape {
542            Shape::Planes(planes) => planes.iter().map(|(n, d)| n.dot(x) - d).fold(f64::NEG_INFINITY, f64::max),
543            Shape::Revolved { origin, axis, meridian } => {
544                let r = x.sub(*origin);
545                let z = r.dot(*axis);
546                let rho = r.sub(axis.scale(z)).length();
547                outline_signed_distance(meridian, [rho, z])
548            }
549        }
550    }
551
552    /// K: each curve with a front cap on one side and a back cap on the
553    /// other, with the direction in which the back cap runs along it (the back
554    /// on its left seen from outside).
555    fn grazing(&self) -> Result<Vec<(usize, bool)>, KernelRefusal> {
556        let mut uses: HashMap<usize, Vec<(bool, bool)>> = HashMap::new();
557        for cap in &self.caps {
558            for &(curve, forward, _) in &cap.coedges {
559                uses.entry(curve).or_default().push((forward, cap.front));
560            }
561        }
562        let mut grazing = Vec::new();
563        for (curve, list) in uses {
564            if self.curves[curve].degenerate {
565                continue;
566            }
567            // A sliding end's rim carries no wall: it moves within the end's plane.
568            if list.len() == 1
569                && (self.slides.iter().any(|slide| slide.rim.iter().any(|&(c, _)| c == curve))
570                    || self.slide_sides.iter().any(|side| side.patches.iter().any(|patch| patch.2 == curve || patch.3 == curve)))
571            {
572                continue;
573            }
574            match list.as_slice() {
575                [(fa, front_a), (fb, front_b)] => {
576                    if fa == fb {
577                        return Err(refuse("split_topology", "two caps run one boundary curve the same way".into()));
578                    }
579                    if front_a != front_b {
580                        grazing.push((curve, if *front_a { *fb } else { *fa }));
581                    }
582                }
583                _ => return Err(refuse("split_topology", format!("a boundary curve is used {} times", list.len()))),
584            }
585        }
586        grazing.sort_unstable();
587        Ok(grazing)
588    }
589}
590
591fn uv_line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
592    frag(make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)), "pcurve")
593}
594
595/// The plane through `origin` with in-plane axes u, v (u × v outward), as a
596/// patch covering `points`; and the map to its parameters.
597fn plane_patch(origin: Vec3, u: Vec3, v: Vec3, points: &[Vec3]) -> Result<NurbsSurface, KernelRefusal> {
598    let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
599    for p in points {
600        let q = [p.sub(origin).dot(u), p.sub(origin).dot(v)];
601        for k in 0..2 {
602            lo[k] = lo[k].min(q[k]);
603            hi[k] = hi[k].max(q[k]);
604        }
605    }
606    let at = |s: f64, t: f64| Vec4::from_point(origin.add(u.scale(s)).add(v.scale(t)), 1.0);
607    frag(
608        NurbsSurface::new(
609            1,
610            1,
611            vec![lo[0], lo[0], hi[0], hi[0]],
612            vec![lo[1], lo[1], hi[1], hi[1]],
613            vec![vec![at(lo[0], lo[1]), at(lo[0], hi[1])], vec![at(hi[0], lo[1]), at(hi[0], hi[1])]],
614        ),
615        "plane_surface",
616    )
617}
618
619/// A curve lying in the plane (origin, u, v), as a pcurve of that plane:
620/// its control points projected, weights kept (exact, the map is affine).
621fn plane_pcurve(origin: Vec3, u: Vec3, v: Vec3, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
622    let mut points = Vec::with_capacity(curve.control_points.len());
623    for p in &curve.control_points {
624        let x = frag(p.point(), "control_point")?.sub(origin);
625        points.push(Vec4::from_point(Vec3::new(x.dot(u), x.dot(v), 0.0), p.w));
626    }
627    let pcurve = frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "plane_pcurve")?;
628    if forward { Ok(pcurve) } else { frag(pcurve.reversed(), "plane_pcurve") }
629}
630
631fn split_polyhedron(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<Split, KernelRefusal> {
632    if vertices.len() < 4 || faces.len() < 4 {
633        return Err(input("polyhedron", "a polyhedron needs at least four corners and four faces".into()));
634    }
635    let centroid = vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &p| s.add(p)).scale(1.0 / vertices.len() as f64);
636    let scale = vertices.iter().map(|p| p.sub(centroid).length()).fold(0.0f64, f64::max).max(1e-300);
637    let tolerance = 1e-12 * scale.max(screw.a.sub(centroid).length());
638    let mut loops: Vec<Vec<usize>> = Vec::with_capacity(faces.len());
639    let mut planes = Vec::with_capacity(faces.len());
640    for face in faces {
641        if face.len() < 3 || face.iter().any(|&i| i >= vertices.len()) {
642            return Err(input("face", "a face needs three or more existing corners".into()));
643        }
644        let mut normal = Vec3::new(0.0, 0.0, 0.0);
645        for k in 0..face.len() {
646            let (p, q) = (vertices[face[k]], vertices[face[(k + 1) % face.len()]]);
647            normal = normal.add(p.sub(centroid).cross(q.sub(centroid)));
648        }
649        let mut normal = normal.normalized().map_err(|_| input("face", "a face has no area".into()))?;
650        let mut face = face.clone();
651        if normal.dot(vertices[face[0]].sub(centroid)) < 0.0 {
652            normal = normal.scale(-1.0);
653            face.reverse();
654        }
655        let offset = normal.dot(vertices[face[0]]);
656        for p in vertices {
657            if normal.dot(*p) - offset > 1e-9 * scale {
658                return Err(refuse("not_convex", "the polyhedron is not convex".into()));
659            }
660        }
661        for &i in &face {
662            if (normal.dot(vertices[i]) - offset).abs() > 1e-9 * scale {
663                return Err(input("face", "a face's corners are not in one plane".into()));
664            }
665        }
666        loops.push(face);
667        planes.push((normal, offset));
668    }
669    // Each face's grazing value (affine along the face).
670    let g = |face: usize, x: Vec3| -> f64 {
671        let value = screw.velocity(x).dot(planes[face].0);
672        if value.abs() <= tolerance * screw.velocity(x).length().max(1.0) { 0.0 } else { value }
673    };
674    let mut owner: HashMap<(usize, usize), usize> = HashMap::new();
675    for (index, face) in loops.iter().enumerate() {
676        for k in 0..face.len() {
677            owner.insert((face[k], face[(k + 1) % face.len()]), index);
678        }
679    }
680    for &(i, j) in owner.keys() {
681        if !owner.contains_key(&(j, i)) {
682            return Err(input("closed", "the polyhedron's faces do not close".into()));
683        }
684    }
685    // Split points on edges: where either neighbour's grazing value crosses zero.
686    let mut points: Vec<Vec3> = vertices.to_vec();
687    let mut edge_splits: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
688    let mut keys: Vec<(usize, usize)> = owner.keys().copied().filter(|&(i, j)| i < j).collect();
689    keys.sort_unstable();
690    for (i, j) in keys {
691        let mut params: Vec<f64> = Vec::new();
692        for f in [owner[&(i, j)], owner[&(j, i)]] {
693            let (gi, gj) = (g(f, vertices[i]), g(f, vertices[j]));
694            if gi * gj < 0.0 {
695                params.push(gi / (gi - gj));
696            }
697        }
698        params.sort_by(|a, b| a.total_cmp(b));
699        params.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
700        let mut list = Vec::new();
701        for s in params {
702            points.push(vertices[i].add(vertices[j].sub(vertices[i]).scale(s)));
703            list.push(points.len() - 1);
704        }
705        edge_splits.insert((i, j), list);
706    }
707    let splits_along = |i: usize, j: usize| -> Vec<usize> {
708        if i < j {
709            edge_splits[&(i, j)].clone()
710        } else {
711            edge_splits[&(j, i)].iter().rev().copied().collect()
712        }
713    };
714    // Sub-faces as point rings, counter-clockwise from outside.
715    let mut rings: Vec<(Vec<usize>, usize, bool)> = Vec::new();
716    for (index, face) in loops.iter().enumerate() {
717        let mut ring: Vec<usize> = Vec::new();
718        for k in 0..face.len() {
719            ring.push(face[k]);
720            ring.extend(splits_along(face[k], face[(k + 1) % face.len()]));
721        }
722        let values: Vec<f64> = ring.iter().map(|&p| g(index, points[p])).collect();
723        let positive = values.iter().any(|&v| v > 0.0);
724        let negative = values.iter().any(|&v| v < 0.0);
725        if !positive && !negative {
726            return Err(refuse("face_in_own_plane", format!("face {index} moves in its own plane (its sweep is flat)")));
727        }
728        if !(positive && negative) {
729            rings.push((ring, index, positive));
730            continue;
731        }
732        let zeros: Vec<usize> = (0..ring.len()).filter(|&k| values[k] == 0.0).collect();
733        if zeros.len() != 2 {
734            return Err(refuse("grazing_split", format!("face {index} meets its grazing line {} times", zeros.len())));
735        }
736        let (za, zb) = (zeros[0], zeros[1]);
737        if za + 1 == zb || (zb + 1) % ring.len() == za {
738            return Err(refuse("grazing_split", format!("face {index} is split along one of its own edges")));
739        }
740        let first: Vec<usize> = (za..=zb).map(|k| ring[k]).collect();
741        let second: Vec<usize> = (zb..ring.len()).chain(0..=za).map(|k| ring[k]).collect();
742        let first_front = values[za + 1] > 0.0;
743        rings.push((first, index, first_front));
744        rings.push((second, index, !first_front));
745    }
746    // A growing rise moves the grazing lines: every sub-face must keep its side
747    // at both ends of the motion.
748    if screw.c2 != 0.0 {
749        for (ring, face, front) in &rings {
750            for &p in ring {
751                for t in [screw.t0, screw.t1] {
752                    let value = screw.velocity_at(t, points[p]).dot(planes[*face].0);
753                    let slack = tolerance * screw.velocity_at(t, points[p]).length().max(1.0);
754                    if (*front && value < -slack) || (!*front && value > slack) {
755                        return Err(refuse("rising_sides", format!("face {face} changes side as the rise grows")));
756                    }
757                }
758            }
759        }
760    }
761    // Curves: one straight segment per point pair.
762    let mut curves: Vec<ToolCurve> = Vec::new();
763    let mut by_pair: HashMap<(usize, usize), usize> = HashMap::new();
764    let mut caps = Vec::with_capacity(rings.len());
765    for (ring, face, front) in rings {
766        let normal = planes[face].0;
767        let origin = points[ring[0]];
768        let u = frag(points[ring[1]].sub(origin).normalized(), "plane_axis")?;
769        let v = normal.cross(u);
770        let corners: Vec<Vec3> = ring.iter().map(|&p| points[p]).collect();
771        let surface = plane_patch(origin, u, v, &corners)?;
772        let mut coedges = Vec::with_capacity(ring.len());
773        for k in 0..ring.len() {
774            let (p, q) = (ring[k], ring[(k + 1) % ring.len()]);
775            let key = (p.min(q), p.max(q));
776            let index = match by_pair.get(&key) {
777                Some(&index) => index,
778                None => {
779                    curves.push(ToolCurve {
780                        curve: frag(make_line(points[key.0], points[key.1]), "line")?,
781                        start: key.0,
782                        end: key.1,
783                        degenerate: false,
784                        samples: None,
785                    });
786                    by_pair.insert(key, curves.len() - 1);
787                    curves.len() - 1
788                }
789            };
790            let forward = p == key.0;
791            coedges.push((index, forward, plane_pcurve(origin, u, v, &curves[index].curve, forward)?));
792        }
793        caps.push(Cap { surface, front, coedges, chart: Some(Chart::Plane { origin, u, v }) });
794    }
795    Ok(Split { points, curves, caps, slides: Vec::new(), slide_sides: Vec::new(), scale, shape: Shape::Planes(planes) })
796}
797
798/// The grazing value `A cos ψ + B sin ψ + C` of a face of revolution at one
799/// meridian point, from three samples.
800pub fn harmonic(g: impl Fn(f64) -> f64) -> (f64, f64, f64) {
801    let (g0, g90, g180) = (g(0.0), g(0.5 * PI), g(PI));
802    let c = 0.5 * (g0 + g180);
803    (0.5 * (g0 - g180), g90 - c, c)
804}
805
806pub fn piece_point(piece: &OutlinePiece, s: f64) -> [f64; 2] {
807    match *piece {
808        OutlinePiece::Line { from, to } => [from[0] + (to[0] - from[0]) * s, from[1] + (to[1] - from[1]) * s],
809        OutlinePiece::Arc { centre, radius, start, end } => {
810            let angle = start + (end - start) * s;
811            [centre[0] + radius * angle.cos(), centre[1] + radius * angle.sin()]
812        }
813    }
814}
815
816fn split_revolved(
817    screw: &Screw,
818    origin: Vec3,
819    axis: Vec3,
820    radial: Vec3,
821    meridian: &[OutlinePiece],
822) -> Result<Split, KernelRefusal> {
823    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
824    let u1 = radial.sub(w.scale(radial.dot(w))).normalized().map_err(|_| input("radial", "the radial direction lies along the axis".into()))?;
825    let u2 = w.cross(u1);
826    if let [OutlinePiece::Arc { centre, radius, start, end }] = meridian {
827        if ((end - start).abs() - TAU).abs() < 1e-12 && centre[0] > *radius {
828            return split_torus(screw, origin, w, u1, u2, *centre, *radius, meridian);
829        }
830    }
831    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()));
832    let scale = meridian
833        .iter()
834        .flat_map(|p| [piece_point(p, 0.0), piece_point(p, 1.0)])
835        .map(|q| q[0].abs().max(q[1].abs()))
836        .fold(0.0f64, f64::max)
837        .max(1e-300);
838    let on_axis = |q: [f64; 2]| q[0].abs() <= 1e-12 * scale;
839    // Orientation of the meridian outline (+1 counter-clockwise in (ρ, z)).
840    let mut area = 0.0;
841    for piece in meridian {
842        for k in 0..16 {
843            let (p, q) = (piece_point(piece, k as f64 / 16.0), piece_point(piece, (k + 1) as f64 / 16.0));
844            area += p[0] * q[1] - q[0] * p[1];
845        }
846    }
847    // Work counter-clockwise in (ρ, z): a revolved patch's u × v is then outward.
848    let reversed_meridian: Vec<OutlinePiece>;
849    let meridian: &[OutlinePiece] = if area > 0.0 {
850        meridian
851    } else {
852        reversed_meridian = meridian
853            .iter()
854            .rev()
855            .map(|piece| match *piece {
856                OutlinePiece::Line { from, to } => OutlinePiece::Line { from: to, to: from },
857                OutlinePiece::Arc { centre, radius, start, end } => OutlinePiece::Arc { centre, radius, start: end, end: start },
858            })
859            .collect();
860        &reversed_meridian
861    };
862    let ccw = true;
863    // Outward normal in (ρ, z) of a piece at s.
864    let normal = |piece: &OutlinePiece, s: f64| -> [f64; 2] {
865        let (p, q) = (piece_point(piece, (s - 1e-6).max(0.0)), piece_point(piece, (s + 1e-6).min(1.0)));
866        let (dx, dz) = (q[0] - p[0], q[1] - p[1]);
867        let length = dx.hypot(dz);
868        if ccw { [dz / length, -dx / length] } else { [-dz / length, dx / length] }
869    };
870    let g = |piece: &OutlinePiece, s: f64, psi: f64| -> f64 {
871        let m = piece_point(piece, s);
872        let n = normal(piece, s);
873        let x = at(m[0], m[1], psi);
874        let normal = w.scale(n[1]).add(u1.scale(n[0] * psi.cos())).add(u2.scale(n[0] * psi.sin()));
875        screw.velocity(x).dot(normal)
876    };
877    // The faces: pieces off the axis.
878    let faces: Vec<usize> = (0..meridian.len())
879        .filter(|&i| !(matches!(meridian[i], OutlinePiece::Line { .. }) && on_axis(piece_point(&meridian[i], 0.0)) && on_axis(piece_point(&meridian[i], 1.0))))
880        .collect();
881    // Each face's split angles (where K meets it, constant along it), or its
882    // great circle.
883    enum Kind {
884        /// A cylinder or cone (or a flat end) split along generators at these
885        /// angles (empty: one side).
886        Ruled(Vec<f64>),
887        /// A cylinder or cone whose two grazing curves move round it along
888        /// the meridian (`branches`), from rim to rim.
889        Moving,
890        /// A hemisphere from a pole to an equator rim, split by the great
891        /// circle square to its centre's velocity.
892        Sphere { centre: Vec3, pole_at_start: bool },
893        /// A whole ball (a half circle from pole to pole), split by that
894        /// great circle into two hemispheres.
895        Ball { centre: Vec3, radius: f64 },
896        /// A rounded corner (a zone of a torus: an arc whose centre is off the
897        /// axis), crossed by K as a graph v(ψ) of the tube angle for ψ from
898        /// `psi_a` to `psi_b`, entering and leaving at the same rim (the end
899        /// rim when `at_end`).
900        TorusZone { psi_a: f64, psi_b: f64, at_end: bool },
901        /// A flat end that slides within its own plane (`SlideDisc`).
902        Slide,
903        /// A cylinder slid along its own axis (`SlideSide`).
904        SlideSide,
905        /// A rounded corner split along meridian arcs at these angles (the
906        /// grazing curve keeps its angle about the axis: a turn about a
907        /// parallel axis, a slide across the tool's axis).
908        RuledArc(Vec<f64>),
909    }
910    // The two grazing angles of a cylinder or cone at s, the lower and the
911    // upper, unwrapped against s = 0: the front lies between them.
912    let branches = |piece: &OutlinePiece, s: f64| -> Option<(f64, f64)> {
913        let reference = {
914            let (a, b, _) = harmonic(|psi| g(piece, 0.0, psi));
915            b.atan2(a)
916        };
917        let (a, b, c) = harmonic(|psi| g(piece, s, psi));
918        let r = a.hypot(b);
919        if !(c.abs() < r * (1.0 - 1e-9)) {
920            return None;
921        }
922        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
923        let spread = (-c / r).acos();
924        Some((base - spread, base + spread))
925    };
926    let mut kinds: Vec<Kind> = Vec::with_capacity(faces.len());
927    for &i in &faces {
928        let piece = &meridian[i];
929        match *piece {
930            OutlinePiece::Line { .. } => {
931                let roots = |s: f64| -> Vec<f64> {
932                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
933                    let r = a.hypot(b);
934                    if c.abs() >= r * (1.0 - 1e-12) {
935                        return Vec::new();
936                    }
937                    let base = b.atan2(a);
938                    let spread = (-c / r).acos();
939                    let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
940                    list.sort_by(|x, y| x.total_cmp(y));
941                    list
942                };
943                // Where the grazing value vanishes all round (a rim through
944                // the motion's axis turning in its own plane) it names no
945                // angle; read the roots where it does not.
946                let alive = |s: f64| {
947                    let (a, b, c) = harmonic(|psi| g(piece, s, psi));
948                    a.hypot(b).max(c.abs()) > 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound())
949                };
950                let readings: Vec<Vec<f64>> = [0.0, 0.5, 1.0].into_iter().filter(|&t| alive(t)).map(roots).collect();
951                if readings.is_empty() {
952                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
953                    let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
954                    if flat && (on_axis(m0) || on_axis(m1)) {
955                        kinds.push(Kind::Slide);
956                        continue;
957                    }
958                    let upright = (m0[0] - m1[0]).abs() <= 1e-12 * scale;
959                    if upright && screw.omega == 0.0 && screw.turns.is_none() && screw.frame.is_none() {
960                        kinds.push(Kind::SlideSide);
961                        continue;
962                    }
963                    return Err(refuse("revolved_grazing", format!("meridian piece {i} grazes all over")));
964                }
965                let r0 = readings[0].clone();
966                let still = readings.iter().all(|r| r.len() == r0.len() && r.iter().zip(&r0).all(|(x, y)| (x - y).abs() < 1e-10));
967                if still {
968                    // A face wholly on one side that is not a disc about the
969                    // axis (a cone to its point, an annulus, a whole side):
970                    // two halves of the same side, seamed at 0 and π.
971                    let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
972                    let disc = (m0[1] - m1[1]).abs() <= 1e-12 * scale && (on_axis(m0) || on_axis(m1));
973                    kinds.push(Kind::Ruled(if r0.is_empty() && !disc { vec![0.0, PI] } else { r0 }));
974                    continue;
975                }
976                let mut previous: Option<(f64, f64)> = None;
977                for k in 0..=64 {
978                    let Some(pair) = branches(piece, k as f64 / 64.0) else {
979                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} do not run rim to rim")));
980                    };
981                    if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
982                        return Err(refuse("revolved_grazing", format!("the grazing curves on meridian piece {i} turn too fast")));
983                    }
984                    previous = Some(pair);
985                }
986                kinds.push(Kind::Moving);
987            }
988            OutlinePiece::Arc { centre, radius, start, end } => {
989                let (p0, p1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
990                let span = (end - start).abs();
991                let centre_on_axis = on_axis(centre);
992                let pole_at_start = on_axis(p0);
993                let equator = |p: [f64; 2]| (p[1] - centre[1]).abs() <= 1e-12 * scale && (p[0] - radius).abs() <= 1e-12 * scale;
994                if centre_on_axis && (span - PI).abs() < 1e-12 && pole_at_start && on_axis(p1) {
995                    kinds.push(Kind::Ball { centre: origin.add(w.scale(centre[1])), radius });
996                    continue;
997                }
998                if centre[0] > radius * (1.0 + 1e-9) && end > start && span <= PI + 1e-12 {
999                    let at_rim = |v: f64| [centre[0] + radius * v.cos(), centre[1] + radius * v.sin()];
1000                    let g_tube = |psi: f64, v: f64| -> f64 {
1001                        let m = at_rim(v);
1002                        let x = at(m[0], m[1], psi);
1003                        let normal = w.scale(v.sin()).add(u1.scale(v.cos() * psi.cos())).add(u2.scale(v.cos() * psi.sin()));
1004                        screw.velocity(x).dot(normal)
1005                    };
1006                    // K at the same angles about the axis all along the arc?
1007                    {
1008                        let roots_at = |v: f64| -> Option<Vec<f64>> {
1009                            let (a, b, c) = harmonic(|psi| g_tube(psi, v));
1010                            let r = a.hypot(b);
1011                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1012                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1013                                return None;
1014                            }
1015                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1016                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1017                            list.sort_by(|x, y| x.total_cmp(y));
1018                            Some(list)
1019                        };
1020                        let readings: Vec<Option<Vec<f64>>> = [0.25, 0.5, 0.75].into_iter().map(|t| roots_at(start + (end - start) * t)).collect();
1021                        if let [Some(r0), Some(r1), Some(r2)] = readings.as_slice() {
1022                            if r0.iter().zip(r1).chain(r0.iter().zip(r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1023                                kinds.push(Kind::RuledArc(r0.clone()));
1024                                continue;
1025                            }
1026                        }
1027                    }
1028                    if span >= PI {
1029                        return Err(refuse("revolved_arc", format!("meridian piece {i}: a half-round rim is swept only where its grazing curves keep their angle")));
1030                    }
1031                    let in_zone = |psi: f64| -> Result<Option<f64>, KernelRefusal> {
1032                        let (a, b, c) = harmonic(|v| g_tube(psi, v));
1033                        let r = a.hypot(b);
1034                        if !(c.abs() < r) {
1035                            return Ok(None);
1036                        }
1037                        let base = b.atan2(a);
1038                        let spread = (-c / r).acos();
1039                        let inside: Vec<f64> = [base - spread, base + spread]
1040                            .into_iter()
1041                            .map(|v| start + (v - start).rem_euclid(TAU))
1042                            .filter(|&v| v <= end)
1043                            .collect();
1044                        match inside.as_slice() {
1045                            [] => Ok(None),
1046                            [v] => Ok(Some(*v)),
1047                            _ => Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner twice at one angle"))),
1048                        }
1049                    };
1050                    let count = 720;
1051                    let has: Vec<bool> = (0..count).map(|k| in_zone(TAU * k as f64 / count as f64).map(|r| r.is_some())).collect::<Result<_, _>>()?;
1052                    let rises: Vec<usize> = (0..count).filter(|&k| has[k] && !has[(k + count - 1) % count]).collect();
1053                    let falls: Vec<usize> = (0..count).filter(|&k| !has[k] && has[(k + count - 1) % count]).collect();
1054                    let ([rise], [fall]) = (rises.as_slice(), falls.as_slice()) else {
1055                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve does not cross the rounded corner once")));
1056                    };
1057                    // The crossing's ends: roots of the grazing value along the rim it meets.
1058                    let estimate = |k: usize| TAU * (k as f64 - 0.5) / count as f64;
1059                    let (ea, eb) = (estimate(*rise), estimate(*fall));
1060                    let sample = |k: usize| TAU * (k % count) as f64 / count as f64;
1061                    let probe_v = in_zone(sample(*rise))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1062                    let at_end = (probe_v - end).abs() < (probe_v - start).abs();
1063                    let rim_v = if at_end { end } else { start };
1064                    let (a, b, c) = harmonic(|psi| g_tube(psi, rim_v));
1065                    let r = a.hypot(b);
1066                    let base = b.atan2(a);
1067                    let spread = (-c / r).acos();
1068                    let roots = [base - spread, base + spread];
1069                    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");
1070                    let (psi_a, psi_b) = (nearest(ea).rem_euclid(TAU), nearest(eb).rem_euclid(TAU));
1071                    let psi_b = if psi_b <= psi_a { psi_b + TAU } else { psi_b };
1072                    let leave_v = in_zone(sample(*fall + count - 1))?.ok_or_else(|| refuse("torus_zone", "the grazing curve's crossing is not found".into()))?;
1073                    if ((leave_v - end).abs() < (leave_v - start).abs()) != at_end {
1074                        return Err(refuse("torus_zone", format!("meridian piece {i}: the grazing curve crosses the rounded corner from rim to rim")));
1075                    }
1076                    kinds.push(Kind::TorusZone { psi_a, psi_b, at_end });
1077                    continue;
1078                }
1079                if !(centre_on_axis && (span - 0.5 * PI).abs() < 1e-12 && (pole_at_start && equator(p1) || on_axis(p1) && equator(p0))) {
1080                    // A cap of a sphere about the axis, from its pole to a rim
1081                    // short of (or past) the equator: swept where its grazing
1082                    // curves keep their angle about the axis (meridian arcs
1083                    // through the pole).
1084                    if centre_on_axis && end > start && span < PI && (pole_at_start != on_axis(p1)) {
1085                        let roots_at = |s: f64| -> Option<Vec<f64>> {
1086                            let (a, b, c) = harmonic(|psi| g(piece, s, psi));
1087                            let r = a.hypot(b);
1088                            let floor = 1e-12 * scale * screw.velocity(origin).length().max(screw.omega.abs() * scale).max(screw.rate_bound());
1089                            if r.max(c.abs()) <= floor || c.abs() >= r * (1.0 - 1e-12) {
1090                                return None;
1091                            }
1092                            let (base, spread) = (b.atan2(a), (-c / r).acos());
1093                            let mut list = vec![(base - spread).rem_euclid(TAU), (base + spread).rem_euclid(TAU)];
1094                            list.sort_by(|x, y| x.total_cmp(y));
1095                            Some(list)
1096                        };
1097                        if let [Some(r0), Some(r1), Some(r2)] = [0.25, 0.5, 0.75].map(roots_at) {
1098                            if r0.iter().zip(&r1).chain(r0.iter().zip(&r2)).all(|(x, y)| (x - y).abs() < 1e-10) {
1099                                kinds.push(Kind::RuledArc(r0));
1100                                continue;
1101                            }
1102                        }
1103                    }
1104                    return Err(refuse("revolved_arc", format!("meridian piece {i}: only a quarter circle from a pole to an equator is swept here")));
1105                }
1106                kinds.push(Kind::Sphere { centre: origin.add(w.scale(centre[1])), pole_at_start });
1107            }
1108        }
1109    }
1110    // Rims: junctions off the axis, with the angles they are split at.
1111    let count = meridian.len();
1112    let junction = |k: usize| piece_point(&meridian[k], 1.0); // between piece k and k + 1
1113    let face_of = |piece: usize| faces.iter().position(|&f| f == piece);
1114    let mut rim_angles: HashMap<usize, Vec<f64>> = HashMap::new();
1115    for k in 0..count {
1116        if on_axis(junction(k)) {
1117            continue;
1118        }
1119        let mut angles: Vec<f64> = Vec::new();
1120        for (piece, s_end) in [(k, 1.0), ((k + 1) % count, 0.0)] {
1121            let Some(f) = face_of(piece) else { continue };
1122            match &kinds[f] {
1123                Kind::Ruled(roots) | Kind::RuledArc(roots) => angles.extend(roots.iter().copied()),
1124                Kind::Ball { .. } | Kind::Slide => {}
1125                Kind::SlideSide => angles.extend([0.0, PI]),
1126                Kind::TorusZone { psi_a, psi_b, .. } => angles.extend([psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)]),
1127                Kind::Moving => {
1128                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1129                    angles.extend([lower.rem_euclid(TAU), upper.rem_euclid(TAU)]);
1130                }
1131                Kind::Sphere { centre, .. } => {
1132                    let d = screw.velocity(*centre).cross(w);
1133                    let base = d.dot(u2).atan2(d.dot(u1)).rem_euclid(TAU);
1134                    angles.extend([base, (base + PI).rem_euclid(TAU)]);
1135                }
1136            }
1137        }
1138        angles.sort_by(|a, b| a.total_cmp(b));
1139        let mut merged: Vec<f64> = Vec::new();
1140        for a in angles {
1141            if merged.last().is_some_and(|&b| (a - b).abs() < 1e-9) || merged.first().is_some_and(|&b| (b + TAU - a).abs() < 1e-9) {
1142                continue;
1143            }
1144            merged.push(a);
1145        }
1146        rim_angles.insert(k, merged);
1147    }
1148    // Every face's own split angles must be its rims' (one arc per patch side).
1149    for (f, &piece) in faces.iter().enumerate() {
1150        for (k, s_end) in [((piece + count - 1) % count, 0.0), (piece, 1.0)] {
1151            let own: Vec<f64> = match &kinds[f] {
1152                Kind::Ruled(roots) | Kind::RuledArc(roots) => roots.clone(),
1153                Kind::Moving => {
1154                    let (lower, upper) = branches(&meridian[piece], s_end).expect("checked");
1155                    let mut list = vec![lower.rem_euclid(TAU), upper.rem_euclid(TAU)];
1156                    list.sort_by(|a, b| a.total_cmp(b));
1157                    list
1158                }
1159                Kind::TorusZone { psi_a, psi_b, .. } => {
1160                    let mut list = vec![psi_a.rem_euclid(TAU), psi_b.rem_euclid(TAU)];
1161                    list.sort_by(|a, b| a.total_cmp(b));
1162                    list
1163                }
1164                Kind::Sphere { .. } | Kind::Ball { .. } | Kind::Slide => continue,
1165                Kind::SlideSide => vec![0.0, PI],
1166            };
1167            if let Some(angles) = rim_angles.get(&k) {
1168                if own.is_empty() {
1169                    continue;
1170                }
1171                if angles.len() != own.len() || angles.iter().zip(&own).any(|(a, b)| (a - b).abs() > 1e-9) {
1172                    return Err(refuse("revolved_rims", format!("meridian piece {piece} splits at other angles than its rim")));
1173                }
1174            }
1175        }
1176    }
1177    let mut points: Vec<Vec3> = Vec::new();
1178    let mut curves: Vec<ToolCurve> = Vec::new();
1179    let mut caps: Vec<Cap> = Vec::new();
1180    let mut slides: Vec<SlideDisc> = Vec::new();
1181    let mut slide_sides: Vec<SlideSide> = Vec::new();
1182    // Rim points and arcs: arc j of rim k runs from angle j to angle j + 1.
1183    let mut rim_points: HashMap<(usize, usize), usize> = HashMap::new();
1184    let mut rim_arcs: HashMap<(usize, usize), usize> = HashMap::new();
1185    let mut rim_keys: Vec<usize> = rim_angles.keys().copied().collect();
1186    rim_keys.sort_unstable();
1187    for &k in &rim_keys {
1188        let q = junction(k);
1189        let angles = rim_angles[&k].clone();
1190        let angles = if angles.is_empty() { vec![0.0] } else { angles };
1191        for (j, &a) in angles.iter().enumerate() {
1192            points.push(at(q[0], q[1], a));
1193            rim_points.insert((k, j), points.len() - 1);
1194        }
1195        for j in 0..angles.len() {
1196            let a = angles[j];
1197            let b = if j + 1 < angles.len() { angles[j + 1] } else { angles[0] + TAU };
1198            let base = at(q[0], q[1], a);
1199            let surface = frag(make_revolution(origin, w, &frag(make_line(base, base.add(w)), "line")?, b - a), "rim")?;
1200            curves.push(ToolCurve {
1201                curve: frag(surface.iso_curve_v(0.0), "rim_arc")?,
1202                start: rim_points[&(k, j)],
1203                end: rim_points[&(k, (j + 1) % angles.len())],
1204                degenerate: false,
1205                samples: Some((0..=LOFT_SAMPLES).map(|i| at(q[0], q[1], a + (b - a) * i as f64 / LOFT_SAMPLES as f64)).collect()),
1206            });
1207            rim_arcs.insert((k, j), curves.len() - 1);
1208        }
1209        rim_angles.insert(k, angles);
1210    }
1211    let arc_index = |k: usize, angle: f64| -> Result<usize, KernelRefusal> {
1212        rim_angles[&k]
1213            .iter()
1214            .position(|&a| ((a - angle).rem_euclid(TAU)).min((angle - a).rem_euclid(TAU)) < 1e-9)
1215            .ok_or_else(|| refuse("revolved_rims", "a patch corner is not on its rim's split".into()))
1216    };
1217    let sign_at = |piece: &OutlinePiece, psi: f64| g(piece, 0.5, psi) > 0.0;
1218    for (f, &piece_index) in faces.iter().enumerate() {
1219        let piece = &meridian[piece_index];
1220        let below = (piece_index + count - 1) % count; // rim at the piece's start
1221        let above = piece_index; // rim at its end
1222        let (m0, m1) = (piece_point(piece, 0.0), piece_point(piece, 1.0));
1223        match &kinds[f] {
1224            Kind::SlideSide => {
1225                if on_axis(m0) || on_axis(m1) {
1226                    return Err(refuse("revolved_grazing", format!("meridian piece {piece_index} grazes all over")));
1227                }
1228                let seams = [0.0, PI];
1229                let mut patches = Vec::with_capacity(2);
1230                for j in 0..2 {
1231                    let (alpha, theta) = (seams[j], PI);
1232                    let (ib, ia) = (arc_index(below, alpha)?, arc_index(above, alpha)?);
1233                    patches.push((alpha, theta, rim_arcs[&(below, ib)], rim_arcs[&(above, ia)], [rim_points[&(below, ib)], rim_points[&(above, ia)]]));
1234                }
1235                slide_sides.push(SlideSide { origin, w, patches });
1236            }
1237            Kind::RuledArc(roots) => {
1238                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1239                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1240                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1241                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1242                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1243                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1244                    let from = tube_point(psi, start);
1245                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1246                    frag(surface.iso_curve_v(0.0), "tube")
1247                };
1248                // A cap to its pole: the meridian arcs start (or end) there,
1249                // and each patch has a pole in place of a rim arc.
1250                let apex = if on_axis(m0) || on_axis(m1) {
1251                    let m = if on_axis(m0) { m0 } else { m1 };
1252                    points.push(at(0.0, m[1], 0.0));
1253                    Some(points.len() - 1)
1254                } else {
1255                    None
1256                };
1257                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1258                    match (on, apex) {
1259                        (true, Some(p)) => Ok(p),
1260                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1261                    }
1262                };
1263                let mut generators = Vec::with_capacity(roots.len());
1264                for &root in roots {
1265                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1266                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES).map(|i| tube_point(root, start + (end - start) * i as f64 / LOFT_SAMPLES as f64)).collect();
1267                    exact[0] = points[a];
1268                    exact[LOFT_SAMPLES] = points[b];
1269                    curves.push(ToolCurve { curve: generatrix(root)?, start: a, end: b, degenerate: false, samples: Some(exact) });
1270                    generators.push(curves.len() - 1);
1271                }
1272                for j in 0..roots.len() {
1273                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1274                    let surface = frag(make_revolution(origin, w, &generatrix(alpha)?, beta - alpha), "patch")?;
1275                    let (mid_psi, mid_v) = (0.5 * (alpha + beta), 0.5 * (start + end));
1276                    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()));
1277                    let front = screw.velocity(tube_point(mid_psi, mid_v)).dot(mid_normal) > 0.0;
1278                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1279                        let p = apex.expect("apex");
1280                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1281                        curves.len() - 1
1282                    };
1283                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1284                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1285                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1286                    let coedges = vec![
1287                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1288                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1289                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1290                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1291                    ];
1292                    let chart = Chart::Revolution {
1293                        origin,
1294                        w,
1295                        u1,
1296                        u2,
1297                        alpha,
1298                        theta: beta - alpha,
1299                        spans_u: spans_of(&surface.knots_u),
1300                        meridian: MeridianChart::Arc { centre, start, sweep: end - start, spans: spans_of(&surface.knots_v) },
1301                    };
1302                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1303                }
1304            }
1305            Kind::Slide => {
1306                let rim = if on_axis(m0) { above } else { below };
1307                let n = normal(piece, 0.5);
1308                let outward = w.scale(n[1].signum());
1309                let arcs = rim_angles[&rim].len();
1310                // Counter-clockwise about the outward normal: increasing ψ about +w.
1311                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1312                slides.push(SlideDisc {
1313                    centre: origin.add(w.scale(m0[1])),
1314                    u: u1,
1315                    v: outward.cross(u1),
1316                    rim: order.into_iter().map(|j| (rim_arcs[&(rim, j)], n[1] > 0.0)).collect(),
1317                });
1318            }
1319            Kind::Ruled(roots) if roots.is_empty() => {
1320                // A flat end wholly on one side: a disc about the axis.
1321                let flat = (m0[1] - m1[1]).abs() <= 1e-12 * scale;
1322                if !flat || !(on_axis(m0) || on_axis(m1)) {
1323                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a whole side or ring is not swept here")));
1324                }
1325                let rim = if on_axis(m0) { above } else { below };
1326                let front = sign_at(piece, 0.0);
1327                if (0..64).any(|k| sign_at(piece, TAU * k as f64 / 64.0) != front) {
1328                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a flat end meets its grazing line")));
1329                }
1330                let n = normal(piece, 0.5);
1331                let outward = w.scale(n[1].signum());
1332                let centre = origin.add(w.scale(m0[1]));
1333                let (u, v) = (u1, outward.cross(u1));
1334                let arcs = rim_angles[&rim].len();
1335                let mut coedges = Vec::with_capacity(arcs);
1336                let mut corners = Vec::new();
1337                // Counter-clockwise about the outward normal: increasing ψ about +w.
1338                let order: Vec<usize> = if n[1] > 0.0 { (0..arcs).collect() } else { (0..arcs).rev().collect() };
1339                for j in order {
1340                    let c = rim_arcs[&(rim, j)];
1341                    let forward = n[1] > 0.0;
1342                    coedges.push((c, forward, plane_pcurve(centre, u, v, &curves[c].curve, forward)?));
1343                    corners.push(points[curves[c].start]);
1344                }
1345                let r = junction(rim)[0];
1346                corners.extend([centre.add(u.scale(r)).add(v.scale(r)), centre.sub(u.scale(r)).sub(v.scale(r))]);
1347                caps.push(Cap { surface: plane_patch(centre, u, v, &corners)?, front, coedges, chart: Some(Chart::Plane { origin: centre, u, v }) });
1348            }
1349            Kind::Ruled(roots) => {
1350                // A cone to a point: its generators start (or end) at the
1351                // apex, and each patch has a pole there in place of a rim arc.
1352                let apex = if on_axis(m0) || on_axis(m1) {
1353                    let m = if on_axis(m0) { m0 } else { m1 };
1354                    points.push(at(0.0, m[1], 0.0));
1355                    Some(points.len() - 1)
1356                } else {
1357                    None
1358                };
1359                let rim_point = |rim: usize, on: bool, angle: f64| -> Result<usize, KernelRefusal> {
1360                    match (on, apex) {
1361                        (true, Some(p)) => Ok(p),
1362                        _ => Ok(rim_points[&(rim, arc_index(rim, angle)?)]),
1363                    }
1364                };
1365                // Generators at each root, from the start rim to the end rim.
1366                let mut generators = Vec::with_capacity(roots.len());
1367                for &root in roots {
1368                    let (a, b) = (rim_point(below, on_axis(m0), root)?, rim_point(above, on_axis(m1), root)?);
1369                    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();
1370                    curves.push(ToolCurve { curve: frag(make_line(points[a], points[b]), "generator")?, start: a, end: b, degenerate: false, samples: Some(line_samples) });
1371                    generators.push(curves.len() - 1);
1372                }
1373                for j in 0..roots.len() {
1374                    let (alpha, beta) = (roots[j], if j + 1 < roots.len() { roots[j + 1] } else { roots[0] + TAU });
1375                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1376                    let surface = frag(make_revolution(origin, w, &generatrix, beta - alpha), "patch")?;
1377                    let front = sign_at(piece, 0.5 * (alpha + beta));
1378                    let pole = |curves: &mut Vec<ToolCurve>| -> usize {
1379                        let p = apex.expect("apex");
1380                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1381                        curves.len() - 1
1382                    };
1383                    let lower = if on_axis(m0) { pole(&mut curves) } else { rim_arcs[&(below, arc_index(below, alpha)?)] };
1384                    let upper = if on_axis(m1) { pole(&mut curves) } else { rim_arcs[&(above, arc_index(above, alpha)?)] };
1385                    let (g_alpha, g_beta) = (generators[j], generators[(j + 1) % roots.len()]);
1386                    let coedges = vec![
1387                        (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1388                        (g_beta, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1389                        (upper, on_axis(m1), uv_line([1.0, 1.0], [0.0, 1.0])?),
1390                        (g_alpha, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1391                    ];
1392                    let chart = Chart::Revolution { origin, w, u1, u2, alpha, theta: beta - alpha, spans_u: spans_of(&surface.knots_u), meridian: MeridianChart::Line { m0, m1 } };
1393                    caps.push(Cap { surface, front, coedges, chart: Some(chart) });
1394                }
1395            }
1396            Kind::Moving => {
1397                if on_axis(m0) || on_axis(m1) {
1398                    return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a split cone to a point is not swept here")));
1399                }
1400                let n = 128;
1401                let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1402                let pairs: Vec<(f64, f64)> = params.iter().map(|&t| branches(piece, t).expect("checked")).collect();
1403                let pick = |pair: (f64, f64), which: usize| if which == 0 { pair.0 } else { pair.1 };
1404                // K: the lower and upper branch, each from the start rim to the end rim.
1405                let mut branch_curves = [0usize; 2];
1406                for which in 0..2 {
1407                    let (psi0, psi1) = (pick(pairs[0], which), pick(pairs[n], which));
1408                    let start = rim_points[&(below, arc_index(below, psi0)?)];
1409                    let end = rim_points[&(above, arc_index(above, psi1)?)];
1410                    let mut samples: Vec<Vec3> = params
1411                        .iter()
1412                        .zip(&pairs)
1413                        .map(|(&t, &pair)| {
1414                            let m = piece_point(piece, t);
1415                            at(m[0], m[1], pick(pair, which))
1416                        })
1417                        .collect();
1418                    samples[0] = points[start];
1419                    samples[n] = points[end];
1420                    let mut exact: Vec<Vec3> = (0..=LOFT_SAMPLES)
1421                        .map(|i| {
1422                            let t = i as f64 / LOFT_SAMPLES as f64;
1423                            let m = piece_point(piece, t);
1424                            at(m[0], m[1], pick(branches(piece, t).expect("checked"), which))
1425                        })
1426                        .collect();
1427                    exact[0] = points[start];
1428                    exact[LOFT_SAMPLES] = points[end];
1429                    curves.push(ToolCurve { curve: frag(crate::interpolate_curve(&samples, 5, &params), "branch")?, start, end, degenerate: false, samples: Some(exact) });
1430                    branch_curves[which] = curves.len() - 1;
1431                }
1432                // Front between lower and upper; back from upper to lower + 2π.
1433                for (lo_which, hi_which, hi_turn) in [(0usize, 1usize, 0.0), (1, 0, TAU)] {
1434                    let lo = |i: usize| pick(pairs[i], lo_which);
1435                    let hi = |i: usize| pick(pairs[i], hi_which) + hi_turn;
1436                    let alpha = (0..=n).map(lo).fold(f64::INFINITY, f64::min) - 1e-3;
1437                    let theta = (0..=n).map(hi).fold(f64::NEG_INFINITY, f64::max) + 1e-3 - alpha;
1438                    if theta >= TAU {
1439                        return Err(refuse("revolved_side", format!("meridian piece {piece_index}: a side patch wraps all the way round")));
1440                    }
1441                    let generatrix = frag(make_line(at(m0[0], m0[1], alpha), at(m1[0], m1[1], alpha)), "generatrix")?;
1442                    let surface = frag(make_revolution(origin, w, &generatrix, theta), "patch")?;
1443                    let spans = (surface.knots_u.len() - 6) / 2 + 1;
1444                    let u_of = |psi: f64| crate::circle_angle_to_parameter(spans, theta, psi - alpha);
1445                    let angle_near = |x: Vec3, guess: f64| -> f64 {
1446                        let r = x.sub(origin);
1447                        let a = r.dot(u2).atan2(r.dot(u1));
1448                        guess + (a - guess + PI).rem_euclid(TAU) - PI
1449                    };
1450                    let front = sign_at(piece, 0.5 * (lo(n / 2) + hi(n / 2)));
1451                    // A rim arc's pcurve on this patch, through its own parameter.
1452                    let rim_pcurve = |arc: usize, v: f64| -> Result<NurbsCurve, KernelRefusal> {
1453                        let curve = &curves[arc].curve;
1454                        let [d0, d1] = frag(curve.domain(), "domain")?;
1455                        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
1456                        let mut uv = Vec::with_capacity(ts.len());
1457                        for &t in &ts {
1458                            let x = frag(curve.evaluate(t), "rim")?;
1459                            uv.push(Vec3::new(u_of(angle_near(x, alpha + 0.5 * theta)), v, 0.0));
1460                        }
1461                        frag(crate::interpolate_curve(&uv, 5, &ts), "rim_pcurve")
1462                    };
1463                    // A grazing branch's pcurve: the image of the built edge,
1464                    // through its own parameter (angle about the axis; place
1465                    // along the meridian line).
1466                    let branch_pcurve = |which: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> {
1467                        let curve = &curves[branch_curves[which]].curve;
1468                        let [d0, d1] = frag(curve.domain(), "domain")?;
1469                        let (span_rho, span_z) = (m1[0] - m0[0], m1[1] - m0[1]);
1470                        let length2 = span_rho * span_rho + span_z * span_z;
1471                        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
1472                        let mut uv = Vec::with_capacity(ts.len());
1473                        for &t in &ts {
1474                            let x = frag(curve.evaluate(t), "branch")?;
1475                            let r = x.sub(origin);
1476                            let z = r.dot(w);
1477                            let rho = r.sub(w.scale(z)).length();
1478                            let along = ((rho - m0[0]) * span_rho + (z - m0[1]) * span_z) / length2;
1479                            uv.push(Vec3::new(u_of(angle_near(x, alpha + 0.5 * theta)), along, 0.0));
1480                        }
1481                        frag(crate::interpolate_curve(&uv, 5, &ts), "branch_pcurve")
1482                    };
1483                    let bottom = rim_arcs[&(below, arc_index(below, lo(0))?)];
1484                    let top = rim_arcs[&(above, arc_index(above, lo(n))?)];
1485                    let coedges = vec![
1486                        (bottom, true, rim_pcurve(bottom, 0.0)?),
1487                        (branch_curves[hi_which], true, branch_pcurve(hi_which, hi_turn)?),
1488                        (top, false, frag(rim_pcurve(top, 1.0)?.reversed(), "reversed")?),
1489                        (branch_curves[lo_which], false, frag(branch_pcurve(lo_which, 0.0)?.reversed(), "reversed")?),
1490                    ];
1491                    let chart_spans = spans_of(&surface.knots_u);
1492                    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 } }) });
1493                }
1494            }
1495            Kind::TorusZone { psi_a, psi_b, at_end } => {
1496                let OutlinePiece::Arc { centre, radius, start, end } = *piece else { unreachable!() };
1497                let (psi_a, psi_b, at_end) = (*psi_a, *psi_b, *at_end);
1498                let tube_centre = |psi: f64| at(centre[0], centre[1], psi);
1499                let tube_axis = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin())).cross(w);
1500                let tube_point = |psi: f64, v: f64| at(centre[0] + radius * v.cos(), centre[1] + radius * v.sin(), psi);
1501                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()));
1502                let root = |psi: f64| -> Option<f64> {
1503                    let (a, b, c) = harmonic(|v| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)));
1504                    let r = a.hypot(b);
1505                    if !(c.abs() < r) {
1506                        return None;
1507                    }
1508                    let base = b.atan2(a);
1509                    let spread = (-c / r).acos();
1510                    [base - spread, base + spread].into_iter().map(|v| start + (v - start).rem_euclid(TAU)).find(|&v| v <= end + 1e-12)
1511                };
1512                // The tube's arc (start -> end) in the meridian half-plane at ψ.
1513                let generatrix = |psi: f64| -> Result<NurbsCurve, KernelRefusal> {
1514                    let from = tube_point(psi, start);
1515                    let surface = frag(make_revolution(tube_centre(psi), tube_axis(psi), &frag(make_line(from, from.add(tube_axis(psi))), "line")?, end - start), "tube")?;
1516                    frag(surface.iso_curve_v(0.0), "tube")
1517                };
1518                let (rim_k, other_k) = if at_end { (above, below) } else { (below, above) };
1519                let ka = rim_points[&(rim_k, arc_index(rim_k, psi_a)?)];
1520                let kb = rim_points[&(rim_k, arc_index(rim_k, psi_b)?)];
1521                // K: the graph over ψ ∈ [ψa, ψb].
1522                let n = 256;
1523                let params: Vec<f64> = (0..=n).map(|j| j as f64 / n as f64).collect();
1524                // Spaced as 1 − cos: where K meets its rim it runs along the
1525                // meridian, so its tube angle goes as √(ψ − ψa); in this
1526                // parameter it is regular.
1527                let psi_of = |t: f64| psi_a + (psi_b - psi_a) * 0.5 * (1.0 - (PI * t).cos());
1528                let mut xyz = Vec::with_capacity(n + 1);
1529                for j in 0..=n {
1530                    let psi = psi_of(params[j]);
1531                    let v = if j == 0 || j == n { if at_end { end } else { start } } else {
1532                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1533                    };
1534                    xyz.push(tube_point(psi, v));
1535                }
1536                xyz[0] = points[ka];
1537                xyz[n] = points[kb];
1538                let mut exact = Vec::with_capacity(LOFT_SAMPLES + 1);
1539                for i in 0..=LOFT_SAMPLES {
1540                    let psi = psi_of(i as f64 / LOFT_SAMPLES as f64);
1541                    let v = if i == 0 || i == LOFT_SAMPLES { if at_end { end } else { start } } else {
1542                        root(psi).ok_or_else(|| refuse("torus_zone", "the grazing curve leaves the rounded corner".into()))?
1543                    };
1544                    exact.push(tube_point(psi, v));
1545                }
1546                exact[0] = points[ka];
1547                exact[LOFT_SAMPLES] = points[kb];
1548                curves.push(ToolCurve { curve: frag(crate::interpolate_curve(&xyz, 5, &params), "torus_k")?, start: ka, end: kb, degenerate: false, samples: Some(exact) });
1549                let k_curve = curves.len() - 1;
1550                // Cut meridians at ψa and ψb, from the start rim to the end rim.
1551                let mut cut = [0usize; 2];
1552                for (slot, psi) in [(0, psi_a), (1, psi_b)] {
1553                    let (lo, hi) = (rim_points[&(below, arc_index(below, psi)?)], rim_points[&(above, arc_index(above, psi)?)]);
1554                    curves.push(ToolCurve { curve: generatrix(psi)?, start: lo, end: hi, degenerate: false, samples: None });
1555                    cut[slot] = curves.len() - 1;
1556                }
1557                let label = |psi: f64, v: f64| screw.velocity(tube_point(psi, v)).dot(normal_at(psi, v)) > 0.0;
1558                // The patch over [α, β] and its exact inverse.
1559                let patch = |alpha: f64, beta: f64| -> Result<(NurbsSurface, usize, usize), KernelRefusal> {
1560                    let g = generatrix(alpha)?;
1561                    let surface = frag(make_revolution(origin, w, &g, beta - alpha), "torus_patch")?;
1562                    let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1563                    let spans_v = (g.knots.len() - 6) / 2 + 1;
1564                    Ok((surface, spans_u, spans_v))
1565                };
1566                let inverse_pcurve = |curve: &NurbsCurve, alpha: f64, beta: f64, spans_u: usize, spans_v: usize, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
1567                    let [d0, d1] = frag(curve.domain(), "domain")?;
1568                    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
1569                    let mut uv = Vec::with_capacity(ts.len());
1570                    for &t in &ts {
1571                        let x = frag(curve.evaluate(t), "point")?;
1572                        let r = x.sub(origin);
1573                        let mid = 0.5 * (alpha + beta);
1574                        let psi = mid + (r.dot(u2).atan2(r.dot(u1)) - mid + PI).rem_euclid(TAU) - PI;
1575                        let q = x.sub(tube_centre(psi));
1576                        let radial = u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1577                        let vmid = 0.5 * (start + end);
1578                        let v = vmid + (q.dot(w).atan2(q.dot(radial)) - vmid + PI).rem_euclid(TAU) - PI;
1579                        uv.push(Vec3::new(
1580                            crate::circle_angle_to_parameter(spans_u, beta - alpha, psi - alpha),
1581                            crate::circle_angle_to_parameter(spans_v, end - start, v - start),
1582                            0.0,
1583                        ));
1584                    }
1585                    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "torus_pcurve")?;
1586                    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
1587                };
1588                // The band away from K: a natural patch over [ψb, ψa + 2π].
1589                {
1590                    let (surface, _, band_spans_v) = patch(psi_b, psi_a + TAU)?;
1591                    let (bottom, top) = (rim_arcs[&(below, arc_index(below, psi_b)?)], rim_arcs[&(above, arc_index(above, psi_b)?)]);
1592                    let coedges = vec![
1593                        (bottom, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1594                        (cut[0], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1595                        (top, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1596                        (cut[1], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1597                    ];
1598                    let mid = psi_b + 0.5 * (psi_a + TAU - psi_b);
1599                    let chart_spans = spans_of(&surface.knots_u);
1600                    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 } }) });
1601                }
1602                // Over [ψa, ψb]: the lens between K and its rim, and the rest.
1603                let (surface, spans_u, spans_v) = patch(psi_a, psi_b)?;
1604                let rim_arc = rim_arcs[&(rim_k, arc_index(rim_k, psi_a)?)];
1605                let other_arc = rim_arcs[&(other_k, arc_index(other_k, psi_a)?)];
1606                let mid = 0.5 * (psi_a + psi_b);
1607                let v_k = root(mid).ok_or_else(|| refuse("torus_zone", "no grazing point mid-way".into()))?;
1608                let k_pc = |forward: bool| inverse_pcurve(&curves[k_curve].curve, psi_a, psi_b, spans_u, spans_v, forward);
1609                let lens_v = if at_end { 0.5 * (v_k + end) } else { 0.5 * (v_k + start) };
1610                let rest_v = if at_end { 0.5 * (v_k + start) } else { 0.5 * (v_k + end) };
1611                if at_end {
1612                    // Lens: K (ψa -> ψb) under the end rim, then the end rim back.
1613                    let lens = vec![(k_curve, true, k_pc(true)?), (rim_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?)];
1614                    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 } }) });
1615                    let rest = vec![
1616                        (other_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
1617                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1618                        (k_curve, false, k_pc(false)?),
1619                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1620                    ];
1621                    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 } }) });
1622                } else {
1623                    let lens = vec![(rim_arc, true, uv_line([0.0, 0.0], [1.0, 0.0])?), (k_curve, false, k_pc(false)?)];
1624                    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 } }) });
1625                    let rest = vec![
1626                        (k_curve, true, k_pc(true)?),
1627                        (cut[1], true, uv_line([1.0, 0.0], [1.0, 1.0])?),
1628                        (other_arc, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
1629                        (cut[0], false, uv_line([0.0, 1.0], [0.0, 0.0])?),
1630                    ];
1631                    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 } }) });
1632                }
1633            }
1634            Kind::Ball { centre, radius } => {
1635                let m = frag(screw.velocity(*centre).normalized(), "ball_still")?;
1636                let d = frag(w.cross(m).normalized().or_else(|_| u1.cross(m).normalized()), "ball_axis")?;
1637                let (e1, e2) = (centre.add(d.scale(*radius)), centre.sub(d.scale(*radius)));
1638                points.push(e1);
1639                points.push(e2);
1640                let (i1, i2) = (points.len() - 2, points.len() - 1);
1641                let half = frag(make_revolution(*centre, m, &frag(make_line(e1, e1.add(m)), "line")?, PI), "great")?;
1642                let k_a = frag(half.iso_curve_v(0.0), "great")?;
1643                // Exact samples at even angles from e1 round to e2 (for a
1644                // lofted wall), turned the way the curve runs.
1645                let k_a_samples: Vec<Vec3> = {
1646                    let [a0, a1] = frag(k_a.domain(), "domain")?;
1647                    let middle = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?;
1648                    let arm = e1.sub(*centre);
1649                    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 };
1650                    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();
1651                    list[0] = e1;
1652                    list[LOFT_SAMPLES] = e2;
1653                    list
1654                };
1655                curves.push(ToolCurve { curve: k_a.clone(), start: i1, end: i2, degenerate: false, samples: Some(k_a_samples.clone()) });
1656                let k_a_index = curves.len() - 1;
1657                let [a0, a1] = frag(k_a.domain(), "domain")?;
1658                let h = frag(k_a.evaluate(0.5 * (a0 + a1)), "middle")?.sub(*centre);
1659                let mut k_b_index: Option<usize> = None;
1660                for front in [true, false] {
1661                    let toward = if front { m } else { m.scale(-1.0) };
1662                    let da = if d.cross(h).dot(toward) > 0.0 { d } else { d.scale(-1.0) };
1663                    let mut generatrix = k_a.clone();
1664                    let mut surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1665                    let outward = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1666                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1667                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1668                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1669                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1670                    };
1671                    let mut forward = true;
1672                    if !outward(&surface)? {
1673                        generatrix = frag(generatrix.reversed(), "reversed")?;
1674                        surface = frag(make_revolution(*centre, da, &generatrix, PI), "hemisphere")?;
1675                        forward = false;
1676                    }
1677                    let (start, end) = if forward { (i1, i2) } else { (i2, i1) };
1678                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1679                    let k_b = match k_b_index {
1680                        Some(index) => index,
1681                        None => {
1682                            // The other half of the great circle: the first half turned half way about `da`.
1683                            let mut samples: Vec<Vec3> = k_a_samples.iter().map(|&x| centre.add(x.sub(*centre).rotate_about(da, PI))).collect();
1684                            if !forward {
1685                                samples.reverse();
1686                            }
1687                            samples[0] = points[start];
1688                            samples[LOFT_SAMPLES] = points[end];
1689                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: Some(samples) });
1690                            k_b_index = Some(curves.len() - 1);
1691                            curves.len() - 1
1692                        }
1693                    };
1694                    let k_b_forward = curves[k_b].start == start;
1695                    let k_b_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1696                    let poles = [start, end].map(|p| {
1697                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1698                        curves.len() - 1
1699                    });
1700                    let coedges = vec![
1701                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1702                        (k_b, k_b_forward, k_b_pcurve),
1703                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1704                        (k_a_index, !forward, uv_line([0.0, g1], [0.0, g0])?),
1705                    ];
1706                    caps.push(Cap { surface, front, coedges, chart: None });
1707                }
1708            }
1709            Kind::Sphere { centre, pole_at_start } => {
1710                let rim = if *pole_at_start { above } else { below };
1711                let angles = rim_angles[&rim].clone();
1712                if angles.len() != 2 {
1713                    return Err(refuse("revolved_rims", "a hemisphere's rim is not split in two".into()));
1714                }
1715                let pole_side = w.scale(if *pole_at_start { m0[1] - m1[1] } else { m1[1] - m0[1] }.signum());
1716                let m = screw.velocity(*centre);
1717                let e1 = points[rim_points[&(rim, 0)]];
1718                let d = frag(e1.sub(*centre).normalized(), "lune_axis")?;
1719                let mut great: Option<usize> = None;
1720                for j in 0..2 {
1721                    let arc = rim_arcs[&(rim, j)];
1722                    let [a0, a1] = frag(curves[arc].curve.domain(), "domain")?;
1723                    let middle = frag(curves[arc].curve.evaluate(0.5 * (a0 + a1)), "middle")?;
1724                    let hv = middle.sub(*centre);
1725                    let da = if d.cross(hv).dot(pole_side) > 0.0 { d } else { d.scale(-1.0) };
1726                    // Turn the rim arc about da until its middle reaches K's plane.
1727                    let theta = (-m.dot(hv)).atan2(m.dot(da.cross(hv))).rem_euclid(TAU);
1728                    let theta = if theta > PI { theta - PI } else { theta };
1729                    if !(theta > 1e-9 && theta < PI - 1e-9) {
1730                        return Err(refuse("revolved_lune", "the great circle meets the rim's plane edge-on".into()));
1731                    }
1732                    let mut generatrix = curves[arc].curve.clone();
1733                    let mut surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1734                    // Outward: (x − centre) at the lune's middle.
1735                    let probe = |s: &NurbsSurface| -> Result<bool, KernelRefusal> {
1736                        let p = frag(s.evaluate(0.5, 0.5), "probe")?;
1737                        let su = frag(s.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(s.evaluate(0.5 - 1e-6, 0.5), "probe")?);
1738                        let sv = frag(s.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(s.evaluate(0.5, 0.5 - 1e-6), "probe")?);
1739                        Ok(su.cross(sv).dot(p.sub(*centre)) > 0.0)
1740                    };
1741                    let mut forward = true;
1742                    if !probe(&surface)? {
1743                        generatrix = frag(generatrix.reversed(), "reversed")?;
1744                        surface = frag(make_revolution(*centre, da, &generatrix, theta), "lune")?;
1745                        forward = false;
1746                    }
1747                    let (start, end) = if forward { (curves[arc].start, curves[arc].end) } else { (curves[arc].end, curves[arc].start) };
1748                    let [g0, g1] = frag(generatrix.domain(), "domain")?;
1749                    // The great-circle half: the turned generatrix (u = 1), from
1750                    // `start` to `end`; made once, by the first lune.
1751                    let k_curve = match great {
1752                        Some(index) => index,
1753                        None => {
1754                            curves.push(ToolCurve { curve: frag(surface.iso_curve_u(1.0), "great")?, start, end, degenerate: false, samples: None });
1755                            great = Some(curves.len() - 1);
1756                            curves.len() - 1
1757                        }
1758                    };
1759                    let k_forward = curves[k_curve].start == start;
1760                    let poles = [start, end].map(|p| {
1761                        curves.push(ToolCurve { curve: make_line(points[p], points[p]).expect("point"), start: p, end: p, degenerate: true, samples: None });
1762                        curves.len() - 1
1763                    });
1764                    let k_pcurve = uv_line([1.0, g0], [1.0, g1])?;
1765                    let coedges = vec![
1766                        (poles[0], true, uv_line([0.0, g0], [1.0, g0])?),
1767                        (k_curve, k_forward, k_pcurve),
1768                        (poles[1], true, uv_line([1.0, g1], [0.0, g1])?),
1769                        (arc, !forward, uv_line([0.0, g1], [0.0, g0])?),
1770                    ];
1771                    let mid_psi = if j == 0 { 0.5 * (angles[0] + angles[1]) } else { 0.5 * (angles[1] + angles[0] + TAU) };
1772                    let front = m.dot(at(1.0, 0.0, mid_psi).sub(origin)) > 0.0;
1773                    caps.push(Cap { surface, front, coedges, chart: None });
1774                }
1775            }
1776        }
1777    }
1778    Ok(Split {
1779        points,
1780        curves,
1781        caps,
1782        slides,
1783        slide_sides,
1784        scale,
1785        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
1786    })
1787}
1788
1789/// A ring (torus: the circle of `radius` about `centre` in (ρ, z), off the
1790/// axis), split by its two grazing curves. For each angle ψ about the ring's
1791/// axis the grazing value along the tube's circle is A cos v + B sin v + C, so
1792/// each curve is a graph v(ψ) round the ring; the front band lies between
1793/// them. Each band is built in two halves (ψ in [0, π] and [π, 2π]) so no face
1794/// closes on itself.
1795#[allow(clippy::too_many_arguments)]
1796fn split_torus(
1797    screw: &Screw,
1798    origin: Vec3,
1799    w: Vec3,
1800    u1: Vec3,
1801    u2: Vec3,
1802    centre: [f64; 2],
1803    radius: f64,
1804    meridian: &[OutlinePiece],
1805) -> Result<Split, KernelRefusal> {
1806    let (rho_c, z_c) = (centre[0], centre[1]);
1807    let radial = |psi: f64| u1.scale(psi.cos()).add(u2.scale(psi.sin()));
1808    let tube_centre = |psi: f64| origin.add(w.scale(z_c)).add(radial(psi).scale(rho_c));
1809    let point = |psi: f64, v: f64| tube_centre(psi).add(radial(psi).scale(radius * v.cos())).add(w.scale(radius * v.sin()));
1810    let g = |psi: f64, v: f64| screw.velocity(point(psi, v)).dot(radial(psi).scale(v.cos()).add(w.scale(v.sin())));
1811    let reference = {
1812        let (a, b, _) = harmonic(|v| g(0.0, v));
1813        b.atan2(a)
1814    };
1815    // The lower and upper grazing angles v at ψ, unwrapped; the front between.
1816    let branches = |psi: f64| -> Option<(f64, f64)> {
1817        let (a, b, c) = harmonic(|v| g(psi, v));
1818        let r = a.hypot(b);
1819        if !(c.abs() < r * (1.0 - 1e-9)) {
1820            return None;
1821        }
1822        let base = reference + (b.atan2(a) - reference + PI).rem_euclid(TAU) - PI;
1823        let spread = (-c / r).acos();
1824        Some((base - spread, base + spread))
1825    };
1826    let n = screw.loop_samples;
1827    let halves = [(0.0, PI), (PI, TAU)];
1828    let mut samples: Vec<Vec<(f64, f64, f64)>> = Vec::new(); // per half: (ψ, lower, upper)
1829    for &(a, b) in &halves {
1830        let mut list = Vec::with_capacity(n + 1);
1831        let mut previous: Option<(f64, f64)> = None;
1832        for i in 0..=n {
1833            let psi = a + (b - a) * i as f64 / n as f64;
1834            let Some(pair) = branches(psi) else {
1835                return Err(refuse("ring_grazing", "the ring's grazing curves do not run all the way round it".into()));
1836            };
1837            if previous.is_some_and(|p| (p.0 - pair.0).abs() > 0.5 || (p.1 - pair.1).abs() > 0.5) {
1838                return Err(refuse("ring_grazing", "the ring's grazing curves turn too fast".into()));
1839            }
1840            previous = Some(pair);
1841            list.push((psi, pair.0, pair.1));
1842        }
1843        samples.push(list);
1844    }
1845    let params: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
1846    let mut points: Vec<Vec3> = Vec::new();
1847    let mut curves: Vec<ToolCurve> = Vec::new();
1848    // Points: at ψ = 0 and π, on each branch.
1849    let mut corner: HashMap<(usize, usize), usize> = HashMap::new(); // (seam 0 | 1, branch)
1850    for seam in 0..2 {
1851        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)) };
1852        for (branch, v) in [(0, lower), (1, upper)] {
1853            points.push(point(psi, v));
1854            corner.insert((seam, branch), points.len() - 1);
1855        }
1856    }
1857    let seam_of_end = |half: usize, at_end: bool| -> usize { if at_end { 1 - half } else { half } };
1858    // K: each branch over each half.
1859    let mut branch_curve: HashMap<(usize, usize), usize> = HashMap::new(); // (half, branch)
1860    for half in 0..2 {
1861        for branch in 0..2 {
1862            let mut xyz: Vec<Vec3> = samples[half].iter().map(|&(psi, lo, hi)| point(psi, if branch == 0 { lo } else { hi })).collect();
1863            let (start, end) = (corner[&(seam_of_end(half, false), branch)], corner[&(seam_of_end(half, true), branch)]);
1864            xyz[0] = points[start];
1865            xyz[n] = points[end];
1866            curves.push(ToolCurve { curve: frag(crate::interpolate_curve(&xyz, 5, &params), "ring_branch")?, start, end, degenerate: false, samples: Some(xyz.clone()) });
1867            branch_curve.insert((half, branch), curves.len() - 1);
1868        }
1869    }
1870    // Seam arcs of each band at ψ = 0 and π: band 0 (front) from lower to
1871    // upper, band 1 (back) from upper to lower + 2π.
1872    let tube_arc = |psi: f64, v0: f64, v1: f64| -> Result<NurbsCurve, KernelRefusal> {
1873        let start = point(psi, v0);
1874        let axis = radial(psi).cross(w);
1875        let surface = frag(make_revolution(tube_centre(psi), axis, &frag(make_line(start, start.add(axis)), "line")?, v1 - v0), "tube_arc")?;
1876        frag(surface.iso_curve_v(0.0), "tube_arc")
1877    };
1878    let mut seam_arc: HashMap<(usize, usize), usize> = HashMap::new(); // (seam, band)
1879    for seam in 0..2 {
1880        let psi = if seam == 0 { 0.0 } else { PI };
1881        let (lower, upper) = (samples[seam][0].1, samples[seam][0].2);
1882        let (lo_point, hi_point) = (corner[&(seam, 0)], corner[&(seam, 1)]);
1883        curves.push(ToolCurve { curve: tube_arc(psi, lower, upper)?, start: lo_point, end: hi_point, degenerate: false, samples: None });
1884        seam_arc.insert((seam, 0), curves.len() - 1);
1885        curves.push(ToolCurve { curve: tube_arc(psi, upper, lower + TAU)?, start: hi_point, end: lo_point, degenerate: false, samples: None });
1886        seam_arc.insert((seam, 1), curves.len() - 1);
1887    }
1888    let mut caps = Vec::new();
1889    for half in 0..2 {
1890        let (psi_a, psi_b) = halves[half];
1891        for band in 0..2 {
1892            // The band's lower and upper edges (v), as branches.
1893            let (lo_branch, hi_branch, hi_turn) = if band == 0 { (0usize, 1usize, 0.0) } else { (1, 0, TAU) };
1894            let pick = |s: &(f64, f64, f64), b: usize| if b == 0 { s.1 } else { s.2 };
1895            // A margin each side: an end cap may be carried a little across its
1896            // grazing curve (see `end_trim`), as far as the tube leaves room.
1897            let low = samples[half].iter().map(|s| pick(s, lo_branch)).fold(f64::INFINITY, f64::min);
1898            let high = samples[half].iter().map(|s| pick(s, hi_branch) + hi_turn).fold(f64::NEG_INFINITY, f64::max);
1899            let margin = (0.25 * (TAU - (high - low))).clamp(1e-3, 0.25);
1900            let (v_low, v_high) = (low - margin, high + margin);
1901            let theta_v = v_high - v_low;
1902            if theta_v >= TAU {
1903                return Err(refuse("ring_grazing", "a band of the ring wraps all the way round its tube".into()));
1904            }
1905            let generatrix = tube_arc(psi_a, v_low, v_high)?;
1906            let surface = frag(make_revolution(origin, w, &generatrix, psi_b - psi_a), "ring_band")?;
1907            let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
1908            let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
1909            let uv_of = |psi: f64, v: f64| {
1910                Vec3::new(
1911                    crate::circle_angle_to_parameter(spans_u, psi_b - psi_a, psi - psi_a),
1912                    crate::circle_angle_to_parameter(spans_v, theta_v, v - v_low),
1913                    0.0,
1914                )
1915            };
1916            // (ψ, v) of a point, unwrapped near the patch.
1917            let angles_of = |x: Vec3| -> (f64, f64) {
1918                let r = x.sub(origin);
1919                let psi = r.dot(u2).atan2(r.dot(u1));
1920                let psi = 0.5 * (psi_a + psi_b) + (psi - 0.5 * (psi_a + psi_b) + PI).rem_euclid(TAU) - PI;
1921                let q = x.sub(tube_centre(psi));
1922                let v = q.dot(w).atan2(q.dot(radial(psi)));
1923                let mid = 0.5 * (v_low + v_high);
1924                (psi, mid + (v - mid + PI).rem_euclid(TAU) - PI)
1925            };
1926            let inverse_pcurve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
1927                let [d0, d1] = frag(curve.domain(), "domain")?;
1928                let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
1929                let mut uv = Vec::with_capacity(ts.len());
1930                for &t in &ts {
1931                    let (psi, v) = angles_of(frag(curve.evaluate(t), "point")?);
1932                    uv.push(uv_of(psi, v));
1933                }
1934                frag(crate::interpolate_curve(&uv, 5, &ts), "ring_pcurve")
1935            };
1936            let branch_pcurve = |b: usize, _turn: f64| -> Result<NurbsCurve, KernelRefusal> { inverse_pcurve(&curves[branch_curve[&(half, b)]].curve) };
1937            let lower_edge = branch_curve[&(half, lo_branch)];
1938            let upper_edge = branch_curve[&(half, hi_branch)];
1939            let right = seam_arc[&(seam_of_end(half, true), band)];
1940            let left = seam_arc[&(seam_of_end(half, false), band)];
1941            let coedges = vec![
1942                (lower_edge, true, branch_pcurve(lo_branch, 0.0)?),
1943                (right, true, inverse_pcurve(&curves[right].curve)?),
1944                (upper_edge, false, frag(branch_pcurve(hi_branch, hi_turn)?.reversed(), "reversed")?),
1945                (left, false, frag(inverse_pcurve(&curves[left].curve)?.reversed(), "reversed")?),
1946            ];
1947            let mid = &samples[half][n / 2];
1948            let front = g(mid.0, 0.5 * (pick(mid, lo_branch) + pick(mid, hi_branch) + hi_turn)) > 0.0;
1949            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 } }) });
1950        }
1951    }
1952    Ok(Split {
1953        points,
1954        curves,
1955        caps,
1956        slides: Vec::new(),
1957        slide_sides: Vec::new(),
1958        scale: rho_c + radius,
1959        shape: Shape::Revolved { origin, axis: w, meridian: meridian.to_vec() },
1960    })
1961}
1962
1963/// Builder of a closed shell with shared vertices and edges.
1964struct Shell {
1965    vertices: Vec<VertexRecord>,
1966    edges: Vec<EdgeRecord>,
1967    faces: Vec<FaceRecord>,
1968    next: u64,
1969    /// Loops beyond each face's first (holes).
1970    holes: usize,
1971}
1972
1973impl Shell {
1974    fn new() -> Self {
1975        Self { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 1, holes: 0 }
1976    }
1977
1978    fn id(&mut self) -> u64 {
1979        self.next += 1;
1980        self.next
1981    }
1982
1983    fn vertex(&mut self, point: Vec3) -> u64 {
1984        let id = self.id();
1985        self.vertices.push(VertexRecord { id, point });
1986        id
1987    }
1988
1989    fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64, degenerate: bool) -> Result<u64, KernelRefusal> {
1990        let domain = frag(curve.domain(), "edge_domain")?;
1991        let id = self.id();
1992        self.edges.push(EdgeRecord { id, curve, t0: domain[0], t1: domain[1], start_vertex_id: start, end_vertex_id: end, degenerate, name: None });
1993        Ok(id)
1994    }
1995
1996    /// A face from its surface and its loop: (edge, traversed forward?, pcurve
1997    /// in the traversal direction).
1998    fn face(&mut self, surface: NurbsSurface, coedges: Vec<(u64, bool, NurbsCurve)>) -> u64 {
1999        let mut records = Vec::with_capacity(coedges.len());
2000        for (edge, forward, pcurve) in coedges {
2001            let id = self.id();
2002            records.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2003        }
2004        let loop_id = self.id();
2005        let id = self.id();
2006        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: vec![LoopRecord { id: loop_id, coedges: records }], name: None });
2007        id
2008    }
2009
2010    /// A face from its surface and its loops, the outer one first.
2011    fn face_loops(&mut self, surface: NurbsSurface, loops: Vec<Vec<(u64, bool, NurbsCurve)>>) -> u64 {
2012        let mut records = Vec::with_capacity(loops.len());
2013        for coedges in loops {
2014            let mut list = Vec::with_capacity(coedges.len());
2015            for (edge, forward, pcurve) in coedges {
2016                let id = self.id();
2017                list.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
2018            }
2019            let id = self.id();
2020            records.push(LoopRecord { id, coedges: list });
2021        }
2022        self.holes += records.len().saturating_sub(1);
2023        let id = self.id();
2024        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: records, name: None });
2025        id
2026    }
2027
2028    fn solid(mut self) -> BrepSolid {
2029        let shell = self.id();
2030        let id = self.id();
2031        // One shell: V − E + F = 2 − 2g (every face one loop; a pole's
2032        // degenerate edge is not counted, as the validator counts).
2033        let edges = self.edges.iter().filter(|e| !e.degenerate).count() as i64;
2034        // A face with holes counts once for each loop beyond its first less.
2035        let euler = self.vertices.len() as i64 - edges + self.faces.len() as i64 - self.holes as i64;
2036        let genus = (2 - euler) / 2;
2037        BrepSolid {
2038            mass_properties_cache: Default::default(),
2039            id,
2040            vertices: self.vertices,
2041            edges: self.edges,
2042            shells: vec![ShellRecord { id: shell, faces: self.faces }],
2043            genus,
2044            kind: Default::default(),
2045            cells: Default::default(),
2046        }
2047    }
2048}
2049
2050/// The whole sweep of `tool` along `motion` (a single screw, turn or slide),
2051/// its two end positions included.
2052pub fn sweep_solid(tool: &SolidTool, motion: &SolidMotion) -> Result<BrepSolid, KernelRefusal> {
2053    sweep_with(&Screw::from_motion(motion)?, tool)
2054}
2055
2056fn sweep_with(screw: &Screw, tool: &SolidTool) -> Result<BrepSolid, KernelRefusal> {
2057    let screw = *screw;
2058    if let SolidTool::Revolved { axis_origin, axis_direction, meridian, .. } = tool {
2059        if let Some(body) = ball_across_axis(&screw, *axis_origin, *axis_direction, meridian)? {
2060            return Ok(body);
2061        }
2062    }
2063    if let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool {
2064        if let Some(body) = flat_ring(&screw, *axis_origin, *axis_direction, *radial, meridian)? {
2065            return Ok(body);
2066        }
2067        if let Some(body) = rod_across_axis(&screw, *axis_origin, *axis_direction, meridian)? {
2068            return Ok(body);
2069        }
2070    }
2071    if let SolidTool::Polyhedron { vertices, faces } = tool {
2072        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);
2073        if whole {
2074            return whole_turn_shadow(&screw, vertices, faces);
2075        }
2076    }
2077    let split = match tool {
2078        SolidTool::Polyhedron { vertices, faces } => split_polyhedron(&screw, vertices, faces)?,
2079        SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } => {
2080            split_revolved(&screw, *axis_origin, *axis_direction, *radial, meridian)?
2081        }
2082    };
2083    let grazing = split.grazing()?;
2084    // A tool slid along its own axis has no grazing curve: its sliding sides
2085    // join its back at the start to its front at the end.
2086    if grazing.is_empty() && split.slide_sides.is_empty() {
2087        return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
2088    }
2089    let times = row_times(&screw);
2090    let last = times.len() - 1;
2091    let mut shell = Shell::new();
2092    // Vertices and edges at the row times (0 and `last` are the end positions),
2093    // made on demand.
2094    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
2095    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
2096    let mut at_time = |shell: &mut Shell, j: usize, p: usize| -> u64 {
2097        *vertex_at.entry((j, p)).or_insert_with(|| shell.vertex(screw.apply(times[j], split.points[p])))
2098    };
2099    let mut time_edge = |shell: &mut Shell, j: usize, c: usize, vertex: &mut dyn FnMut(&mut Shell, usize, usize) -> u64| -> Result<u64, KernelRefusal> {
2100        if let Some(&edge) = edge_at.get(&(j, c)) {
2101            return Ok(edge);
2102        }
2103        let curve = &split.curves[c];
2104        let (a, b) = (vertex(shell, j, curve.start), vertex(shell, j, curve.end));
2105        let edge = shell.edge(screw.move_curve(times[j], &curve.curve)?, a, b, curve.degenerate)?;
2106        edge_at.insert((j, c), edge);
2107        Ok(edge)
2108    };
2109    // Caps: the back at t0, the front at t1.
2110    for cap in &split.caps {
2111        let j = if cap.front { last } else { 0 };
2112        let surface = screw.move_surface(times[j], &cap.surface)?;
2113        let mut coedges = Vec::with_capacity(cap.coedges.len());
2114        for (c, forward, pcurve) in &cap.coedges {
2115            let edge = time_edge(&mut shell, j, *c, &mut at_time)?;
2116            coedges.push((edge, *forward, pcurve.clone()));
2117        }
2118        shell.face(surface, coedges);
2119    }
2120    // Walls, a row at a time. The back cap at t0 runs K's curve with the back
2121    // on its left, so the wall beside it runs the other way: u along the curve
2122    // that way, v from the row's start to its end, the loop (u0,0) (u1,0)
2123    // (u1,1) (u0,1).
2124    // The paths of K's corners, a row at a time: (row, point) -> edge.
2125    let mut orbit_at: HashMap<(usize, usize), u64> = HashMap::new();
2126    for row in 0..last {
2127        let (ta, tb) = (times[row], times[row + 1]);
2128        let segments = carry_segments(&screw, ta, tb);
2129        let knots_v = carry_knots(segments);
2130        let mut orbits: HashMap<usize, u64> = HashMap::new();
2131        for &(c, _) in &grazing {
2132            for r in [split.curves[c].start, split.curves[c].end] {
2133                if orbits.contains_key(&r) {
2134                    continue;
2135                }
2136                let (v0, v1) = (at_time(&mut shell, row, r), at_time(&mut shell, row + 1, r));
2137                let edge = shell.edge(carry_curve(&screw, split.points[r], ta, tb, segments)?, v0, v1, false)?;
2138                orbits.insert(r, edge);
2139                orbit_at.insert((row, r), edge);
2140            }
2141        }
2142        for &(c, back_forward) in &grazing {
2143            let tool_curve = &split.curves[c];
2144            let along = if back_forward { frag(tool_curve.curve.reversed(), "reversed")? } else { tool_curve.curve.clone() };
2145            let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
2146            let mut rows = Vec::with_capacity(along.control_points.len());
2147            for p in &along.control_points {
2148                let x = frag(p.point(), "control_point")?;
2149                rows.push(carry_points(&screw, x, ta, tb, segments).into_iter().map(|q| Vec4::from_point(q, p.w)).collect::<Vec<_>>());
2150            }
2151            let surface = frag(NurbsSurface::new(along.degree, 5, along.knots.clone(), knots_v.clone(), rows), "wall")?;
2152            let [u0, u1] = frag(along.domain(), "domain")?;
2153            let bottom = time_edge(&mut shell, row, c, &mut at_time)?;
2154            let top = time_edge(&mut shell, row + 1, c, &mut at_time)?;
2155            let coedges = vec![
2156                (bottom, !back_forward, uv_line([u0, 0.0], [u1, 0.0])?),
2157                (orbits[&to], true, uv_line([u1, 0.0], [u1, 1.0])?),
2158                (top, back_forward, uv_line([u1, 1.0], [u0, 1.0])?),
2159                (orbits[&from], false, uv_line([u0, 1.0], [u0, 0.0])?),
2160            ];
2161            shell.face(surface, coedges);
2162        }
2163    }
2164    // Sliding ends: each rim arc where its neighbour's cap sits (back at t0,
2165    // front at t1), joined by the paths of the points where that changes.
2166    // Faces the tool slides within: the one-pass probe stands further off them.
2167    let mut sliding: std::collections::HashSet<u64> = std::collections::HashSet::new();
2168    let side_of: HashMap<usize, bool> = split.caps.iter().flat_map(|cap| cap.coedges.iter().map(move |&(c, _, _)| (c, cap.front))).collect();
2169    for slide in &split.slides {
2170        let centre = screw.apply(times[0], slide.centre);
2171        let u = screw.apply(times[0], slide.centre.add(slide.u)).sub(centre);
2172        let v = screw.apply(times[0], slide.centre.add(slide.v)).sub(centre);
2173        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2174            match side_of.get(&c) {
2175                Some(true) => Ok(last),
2176                Some(false) => Ok(0),
2177                None => Err(refuse("revolved_grazing", "a sliding end has no face beside its rim".into())),
2178            }
2179        };
2180        let mut coedges = Vec::new();
2181        let mut corners: Vec<Vec3> = Vec::new();
2182        let push = |coedges: &mut Vec<(u64, bool, NurbsCurve)>, corners: &mut Vec<Vec3>, edge: u64, forward: bool, curve: &NurbsCurve| -> Result<(), KernelRefusal> {
2183            let [d0, d1] = frag(curve.domain(), "domain")?;
2184            for k in 0..=8 {
2185                corners.push(frag(curve.evaluate(d0 + (d1 - d0) * k as f64 / 8.0), "slide")?);
2186            }
2187            coedges.push((edge, forward, plane_pcurve(centre, u, v, curve, forward)?));
2188            Ok(())
2189        };
2190        for (index, &(c, forward)) in slide.rim.iter().enumerate() {
2191            let j = row_of(c)?;
2192            let edge = time_edge(&mut shell, j, c, &mut at_time)?;
2193            push(&mut coedges, &mut corners, edge, forward, &screw.move_curve(times[j], &split.curves[c].curve)?)?;
2194            // On to the next arc's time along the path of the point between them.
2195            let (next, _) = slide.rim[(index + 1) % slide.rim.len()];
2196            let next_j = row_of(next)?;
2197            if next_j == j {
2198                continue;
2199            }
2200            let point = if forward { split.curves[c].end } else { split.curves[c].start };
2201            let rows: Vec<usize> = if next_j > j { (j..next_j).collect() } else { (next_j..j).rev().collect() };
2202            for row in rows {
2203                let Some(&orbit) = orbit_at.get(&(row, point)) else {
2204                    return Err(refuse("revolved_grazing", "a sliding end's rim changes side where no grazing curve meets it".into()));
2205                };
2206                let (ta, tb) = (times[row], times[row + 1]);
2207                let curve = carry_curve(&screw, split.points[point], ta, tb, carry_segments(&screw, ta, tb))?;
2208                push(&mut coedges, &mut corners, orbit, next_j > j, &curve)?;
2209            }
2210        }
2211        sliding.insert(shell.face(plane_patch(centre, u, v, &corners)?, coedges));
2212    }
2213    // Sliding cylinders: from the start rim where its neighbour sits to the
2214    // end rim where its neighbour sits, in halves seamed along generators.
2215    for side in &split.slide_sides {
2216        let row_of = |c: usize| -> Result<usize, KernelRefusal> {
2217            match side_of.get(&c) {
2218                Some(true) => Ok(last),
2219                Some(false) => Ok(0),
2220                None => Err(refuse("revolved_grazing", "a sliding side has no face beside its rim".into())),
2221            }
2222        };
2223        let origin = screw.apply(times[0], side.origin);
2224        let w = screw.apply(times[0], side.origin.add(side.w)).sub(origin);
2225        let rows: Vec<[usize; 2]> = side.patches.iter().map(|patch| Ok([row_of(patch.2)?, row_of(patch.3)?])).collect::<Result<_, KernelRefusal>>()?;
2226        if rows.iter().any(|r| *r != rows[0]) {
2227            return Err(refuse("revolved_grazing", "a sliding side's rim changes side along it".into()));
2228        }
2229        let [jb, ja] = rows[0];
2230        // Seams: the generator at each patch's start angle, rim point to rim point.
2231        let mut seams = Vec::with_capacity(side.patches.len());
2232        for patch in &side.patches {
2233            let (a, b) = (at_time(&mut shell, jb, patch.4[0]), at_time(&mut shell, ja, patch.4[1]));
2234            let line = frag(make_line(screw.apply(times[jb], split.points[patch.4[0]]), screw.apply(times[ja], split.points[patch.4[1]])), "seam")?;
2235            seams.push((shell.edge(line.clone(), a, b, false)?, line));
2236        }
2237        for (k, patch) in side.patches.iter().enumerate() {
2238            let surface = frag(make_revolution(origin, w, &seams[k].1, patch.1), "slide_side")?;
2239            let lower = time_edge(&mut shell, jb, patch.2, &mut at_time)?;
2240            let upper = time_edge(&mut shell, ja, patch.3, &mut at_time)?;
2241            let next = (k + 1) % side.patches.len();
2242            let face = shell.face(
2243                surface,
2244                vec![
2245                    (lower, true, uv_line([0.0, 0.0], [1.0, 0.0])?),
2246                    (seams[next].0, true, uv_line([1.0, 0.0], [1.0, 1.0])?),
2247                    (upper, false, uv_line([1.0, 1.0], [0.0, 1.0])?),
2248                    (seams[k].0, false, uv_line([0.0, 1.0], [0.0, 0.0])?),
2249                ],
2250            );
2251            sliding.insert(face);
2252        }
2253    }
2254    let body = shell.solid();
2255    let issues = body.validate();
2256    if !issues.is_empty() {
2257        return Err(refuse("assembly", format!("the assembled sweep is not valid: {:?}", issues.first())));
2258    }
2259    check_single_pass(&screw, &split, &body, &sliding)?;
2260    Ok(body)
2261}
2262
2263/// A rod (a cylinder with flat ends) TURNED about a line that crosses its
2264/// axis squarely between its ends, if `meridian` is one and the motion such.
2265///
2266/// Arm by arm: the rod is its arm one way from the turn's axis and its arm
2267/// the other way, and sweeps what they sweep. At a height z (half-width
2268/// w = √(r² − z²)) an arm of length L is the rectangle 0 ≤ x ≤ L, |y| ≤ w,
2269/// which a circle about the turn's axis of radius ρ ≤ L meets in one arc
2270/// holding the arm's own direction, and beyond, out to √(L² + w²), in two
2271/// arcs ±[a, b] with a ≤ acos(L / √(L² + r²)). Turned by more than 2a, the
2272/// two arcs sweep the same angles as the arc [−b, b] they leave a gap in:
2273/// the arm with the gap filled, its points beyond its end within
2274/// √(L² + r²) of the crossing point (a cap of that ball). The filled arm
2275/// meets every circle in one arc holding its direction, so it sweeps itself
2276/// where it starts and where it stops and, between, its section by the half
2277/// plane at its direction turned. So the sweep is the union of the filled rod
2278/// (one solid of revolution about the rod's axis) at both ends of the turn
2279/// and the two arms' sections turned.
2280fn rod_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2281    if screw.frame.is_some() || screw.turns.is_some() || screw.omega == 0.0 || screw.c != 0.0 || screw.c2 != 0.0 {
2282        return Ok(None);
2283    }
2284    let Ok(w) = axis.normalized() else { return Ok(None) };
2285    // A rectangle against the axis: radius r from z0 to z1.
2286    let mut corners: Vec<[f64; 2]> = Vec::new();
2287    for piece in meridian {
2288        let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
2289        corners.push(*from);
2290        corners.push(*to);
2291    }
2292    if meridian.len() != 4 {
2293        return Ok(None);
2294    }
2295    let r = corners.iter().map(|c| c[0]).fold(0.0f64, f64::max);
2296    let (z0, z1) = corners.iter().map(|c| c[1]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), z| (lo.min(z), hi.max(z)));
2297    let scale = r.max(z0.abs()).max(z1.abs());
2298    let on = |a: f64, b: f64| (a - b).abs() <= 1e-12 * scale;
2299    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))) {
2300        return Ok(None);
2301    }
2302    // The turn's axis squarely across the rod's, between its ends.
2303    if w.dot(screw.e).abs() > 1e-12 {
2304        return Ok(None);
2305    }
2306    let offset = screw.a.sub(origin);
2307    let along = offset.dot(w);
2308    let foot = origin.add(w.scale(along));
2309    let apart = screw.a.sub(foot);
2310    if apart.sub(screw.e.scale(apart.dot(screw.e))).length() > 1e-12 * (scale + offset.length()) {
2311        return Ok(None);
2312    }
2313    if !(along > z0 + 1e-9 * scale && along < z1 - 1e-9 * scale) {
2314        return Ok(None);
2315    }
2316    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
2317    let arms = [z1 - along, along - z0];
2318    let gap = arms.iter().map(|l| (l / l.hypot(r)).acos()).fold(0.0f64, f64::max);
2319    if !(theta > 2.0 * gap * (1.0 + 1e-9) && theta < TAU * (1.0 - 1e-9)) {
2320        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()));
2321    }
2322    let arc = |centre: Vec3, from: Vec3, normal: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
2323        let surface = frag(make_revolution(centre, normal, &frag(make_line(from, from.add(normal)), "line")?, angle), "rod_across")?;
2324        frag(surface.iso_curve_v(0.0), "rod_across")
2325    };
2326    let line = |a: Vec3, b: Vec3| frag(make_line(a, b), "rod_across");
2327    // At one time: the crossing point, the rod's direction and the turn's.
2328    let filled_at = |t: f64| -> Result<BrepSolid, KernelRefusal> {
2329        let o = screw.apply(t, foot);
2330        let x = screw.apply(t, foot.add(w)).sub(o);
2331        let up = screw.e;
2332        let at = |rho: f64, s: f64| o.add(up.scale(rho)).add(x.scale(s));
2333        let n = up.cross(x);
2334        let (far_plus, far_minus) = (arms[0].hypot(r), arms[1].hypot(r));
2335        let profile = [
2336            arc(o, at(0.0, -far_minus), n, r.atan2(arms[1]))?,
2337            line(at(r, -arms[1]), at(r, arms[0]))?,
2338            arc(o, at(r, arms[0]), n, r.atan2(arms[0]))?,
2339            line(at(0.0, far_plus), at(0.0, -far_minus))?,
2340        ];
2341        frag(crate::revolve_profile_brep(&profile, o, x, TAU), "rod_across")
2342    };
2343    let o = screw.apply(screw.t0, foot);
2344    let x = screw.apply(screw.t0, foot.add(w)).sub(o);
2345    let turn_axis = screw.e.scale(screw.omega.signum());
2346    let section = |direction: Vec3, length: f64| -> Result<BrepSolid, KernelRefusal> {
2347        let at = |rho: f64, z: f64| o.add(direction.scale(rho)).add(screw.e.scale(z));
2348        let half = (r / length.hypot(r)).asin();
2349        let profile = [
2350            line(at(0.0, -r), at(length, -r))?,
2351            arc(o, at(length, -r), direction.cross(screw.e), 2.0 * half)?,
2352            line(at(length, r), at(0.0, r))?,
2353            line(at(0.0, r), at(0.0, -r))?,
2354        ];
2355        frag(crate::revolve_profile_brep(&profile, o, turn_axis, theta), "rod_across")
2356    };
2357    let parts = [filled_at(screw.t0)?, filled_at(screw.t1)?, section(x, arms[0])?, section(x.scale(-1.0), arms[1])?];
2358    crate::boolean_operation_nary(&parts, crate::BooleanOperation::Union).map(Some)
2359}
2360
2361/// A ring (or another tool with a hole about its axis walled straight
2362/// through) lying flat to its motion (a turn about an axis parallel to the
2363/// tool's, a slide square to it), if `meridian` is one and the motion such.
2364///
2365/// Every point then moves in its own plane square to the ring's axis, where
2366/// the ring's section is an annulus. The tube passes over where the hole was,
2367/// so the sweep does not pass each point once; but an annulus sweeps what its
2368/// filled disc sweeps as soon as it travels far enough that no point stays in
2369/// the hole from start to end (the hole at the start and at the end share
2370/// nothing: travel beyond the hole's greatest width, the tube's centre
2371/// circle). So the ring sweeps what the FILLED ring sweeps: a tool with a
2372/// half-round rim and flat faces, which is swept whole. A whole turn sweeps
2373/// the solid of revolution of that tool's shadow about the turn's axis.
2374fn flat_ring(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
2375    if screw.frame.is_some() || screw.turns.is_some() || screw.c2 != 0.0 {
2376        return Ok(None);
2377    }
2378    let Ok(w) = axis.normalized() else { return Ok(None) };
2379    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 };
2380    if !flat {
2381        return Ok(None);
2382    }
2383    // The holed tool: a torus (`torus`: its tube), or straight-sided pieces
2384    // whose hole is one upright wall from the tool's top to its bottom.
2385    // `big`: half the hole's greatest width. `filled_meridian`: the tool
2386    // with its hole closed, flat across at its top and bottom.
2387    let (big, level, torus, filled_meridian): (f64, f64, Option<f64>, Vec<OutlinePiece>) = match meridian {
2388        [OutlinePiece::Arc { centre, radius, start, end }] => {
2389            let (big, tube, level) = (centre[0], *radius, centre[1]);
2390            if ((end - start).abs() - TAU).abs() >= 1e-12 || big <= tube {
2391                return Ok(None);
2392            }
2393            (
2394                big,
2395                level,
2396                Some(tube),
2397                vec![
2398                    OutlinePiece::Line { from: [0.0, level - tube], to: [big, level - tube] },
2399                    OutlinePiece::Arc { centre: [big, level], radius: tube, start: -0.5 * PI, end: 0.5 * PI },
2400                    OutlinePiece::Line { from: [big, level + tube], to: [0.0, level + tube] },
2401                    OutlinePiece::Line { from: [0.0, level + tube], to: [0.0, level - tube] },
2402                ],
2403            )
2404        }
2405        pieces => {
2406            let mut ends: Vec<([f64; 2], [f64; 2])> = Vec::with_capacity(pieces.len());
2407            for piece in pieces {
2408                let OutlinePiece::Line { from, to } = piece else { return Ok(None) };
2409                ends.push((*from, *to));
2410            }
2411            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);
2412            let inner = ends.iter().flat_map(|(a, b)| [a[0], b[0]]).fold(f64::INFINITY, f64::min);
2413            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)));
2414            if ends.len() < 3 || inner <= 1e-9 * scale {
2415                return Ok(None);
2416            }
2417            let walls: Vec<usize> = (0..ends.len())
2418                .filter(|&k| {
2419                    let (a, b) = ends[k];
2420                    (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
2421                })
2422                .collect();
2423            let [wall] = walls.as_slice() else { return Ok(None) };
2424            let (from, to) = ends[*wall];
2425            // From the wall's end round the outside back to its start, then
2426            // across to the axis and along it.
2427            let mut filled = vec![OutlinePiece::Line { from: [0.0, to[1]], to }];
2428            for k in 1..pieces.len() {
2429                filled.push(pieces[(wall + k) % pieces.len()].clone());
2430            }
2431            filled.push(OutlinePiece::Line { from, to: [0.0, from[1]] });
2432            filled.push(OutlinePiece::Line { from: [0.0, from[1]], to: [0.0, to[1]] });
2433            (inner, 0.5 * (low + high), None, filled)
2434        }
2435    };
2436    let centre0 = origin.add(w.scale(level));
2437    let filled = SolidTool::Revolved { axis_origin: origin, axis_direction: w, radial, meridian: filled_meridian };
2438    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());
2439    if screw.omega == 0.0 {
2440        if screw.c.abs() * (screw.t1 - screw.t0) <= 2.0 * big * (1.0 + 1e-9) {
2441            let Some(tube) = torus else { return Err(short()) };
2442            // Short of its hole: what stays open, all the way through, is the
2443            // lens the hole shares where the ring starts and where it stops.
2444            // The hole at one place: inside the ring's inner half, between
2445            // its top and bottom planes.
2446            let hole = |t: f64| -> Result<BrepSolid, KernelRefusal> {
2447                let o = screw.apply(t, centre0);
2448                let u = frag(radial.sub(w.scale(radial.dot(w))).normalized(), "ring_flat")?;
2449                let at = |rho: f64, z: f64| o.add(u.scale(rho)).add(w.scale(z));
2450                let n = w.cross(u);
2451                let from = at(big, -tube);
2452                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")?;
2453                let profile = [
2454                    frag(make_line(at(0.0, -tube), at(big, -tube)), "ring_flat")?,
2455                    inner,
2456                    frag(make_line(at(big, tube), at(0.0, tube)), "ring_flat")?,
2457                    frag(make_line(at(0.0, tube), at(0.0, -tube)), "ring_flat")?,
2458                ];
2459                frag(crate::revolve_profile_brep(&profile, o, w, TAU), "ring_flat")
2460            };
2461            let lens = crate::boolean_operation_nary(&[hole(screw.t0)?, hole(screw.t1)?], crate::BooleanOperation::Intersect)?;
2462            let whole = sweep_with(screw, &filled)?;
2463            return crate::boolean_operation_nary(&[whole, lens], crate::BooleanOperation::Subtract).map(Some);
2464        }
2465        return sweep_with(screw, &filled).map(Some);
2466    }
2467    // A turn: the ring's centre runs a circle of radius `reach` about the axis.
2468    let start_centre = screw.apply(screw.t0, centre0);
2469    let from_axis = start_centre.sub(screw.a);
2470    let across = from_axis.sub(screw.e.scale(from_axis.dot(screw.e)));
2471    let reach = across.length();
2472    let theta = screw.omega.abs() * (screw.t1 - screw.t0);
2473    if theta >= TAU * (1.0 - 1e-12) {
2474        let Some(tube) = torus else {
2475            return Err(refuse("ring_flat", "a whole turn of a holed tool in its own plane is swept for a ring only".into()));
2476        };
2477        if reach <= (big + tube) * (1.0 + 1e-9) {
2478            return Err(refuse("ring_flat", "a ring turned a whole turn in its own plane reaches the turn's axis".into()));
2479        }
2480        let out = frag(across.normalized(), "ring_flat")?;
2481        let foot = start_centre.sub(across);
2482        let at = |rho: f64, z: f64| foot.add(out.scale(rho)).add(screw.e.scale(z));
2483        let half_round = |centre: Vec3, from: Vec3| -> Result<NurbsCurve, KernelRefusal> {
2484            let n = out.cross(screw.e);
2485            let surface = frag(make_revolution(centre, n, &frag(make_line(from, from.add(n)), "line")?, PI), "ring_flat")?;
2486            frag(surface.iso_curve_v(0.0), "ring_flat")
2487        };
2488        let profile = [
2489            frag(make_line(at(reach - big, -tube), at(reach + big, -tube)), "ring_flat")?,
2490            half_round(at(reach + big, 0.0), at(reach + big, -tube))?,
2491            frag(make_line(at(reach + big, tube), at(reach - big, tube)), "ring_flat")?,
2492            half_round(at(reach - big, 0.0), at(reach - big, tube))?,
2493        ];
2494        return frag(crate::revolve_profile_brep(&profile, foot, screw.e, TAU), "ring_flat").map(Some);
2495    }
2496    let covered = if theta >= PI { big < reach } else { reach * (0.5 * theta).sin() > big * (1.0 + 1e-9) };
2497    if !covered {
2498        return Err(short());
2499    }
2500    sweep_with(screw, &filled).map(Some)
2501}
2502
2503/// The sweep of `tool` along `motion`, where it lies in `clip` (the caller
2504/// cuts a workpiece inside that region). A TURN about the clip's own axis
2505/// whose two end positions stay outside the clip's wedge covers the wedge
2506/// wholly with the tool's shadow in (ρ, z): that shadow, turned over the wedge,
2507/// is the sweep there (a convex polyhedron's shadow is bounded by conic arcs
2508/// from its edges and straight lines from its faces, so every surface is
2509/// exact); a turn about that axis whose ends reach the wedge is refused. A
2510/// screw or turn about the region's axis whose tool reaches far past the
2511/// region's radius sweeps only the tool's part that can reach it (see
2512/// `trim_to_clip`). Any other motion gets the whole sweep ([`sweep_solid`]).
2513pub fn sweep_solid_clipped(tool: &SolidTool, motion: &SolidMotion, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
2514    let screw = Screw::from_motion(motion)?;
2515    if let (SolidTool::Polyhedron { vertices, faces }, Some(wedge)) = (tool, clip.angle) {
2516        let axis = clip.axis_direction.normalized().map_err(|_| input("clip_axis", "the clip's axis has no direction".into()))?;
2517        let same_axis = screw.c == 0.0 && screw.c2 == 0.0
2518            && screw.e.cross(axis).length() < 1e-12
2519            && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
2520        if same_axis {
2521            return turn_shadow(&screw, vertices, faces, clip, axis, wedge);
2522        }
2523    }
2524    if let SolidTool::Polyhedron { vertices, faces } = tool {
2525        if let Some((vertices, faces)) = trim_to_clip(&screw, vertices, faces, clip)? {
2526            return sweep_solid(&SolidTool::Polyhedron { vertices, faces }, motion);
2527        }
2528    }
2529    sweep_solid(tool, motion)
2530}
2531
2532/// The sweep of `tool` along a turn whose rise grows as it turns, where it lies
2533/// in `clip` (as [`sweep_solid_clipped`]). Its front and back are those at
2534/// the middle of the motion; a tool whose faces change side along it is refused.
2535pub fn sweep_solid_rising(tool: &SolidTool, motion: &RisingTurn, clip: &crate::SweepClip) -> Result<BrepSolid, KernelRefusal> {
2536    let screw = Screw::from_rising(motion)?;
2537    let SolidTool::Polyhedron { vertices, faces } = tool else {
2538        return Err(refuse("rising_tool", "a growing rise sweeps a polyhedron only".into()));
2539    };
2540    let (vertices, faces) = trim_to_clip(&screw, vertices, faces, clip)?.unwrap_or_else(|| (vertices.clone(), faces.clone()));
2541    sweep_with(&screw, &SolidTool::Polyhedron { vertices, faces })
2542}
2543
2544/// The sweep of `tool` along `motion` as parts whose union it is (a caller cuts
2545/// a workpiece by all of them). One part where the whole sweep passes once. A
2546/// convex polyhedron whose sweep folds over itself (a face facing away from a
2547/// screw's or turn's axis grazes along a line inside it, and the faces beyond
2548/// that line are swept over again) is split by the plane through the axis and
2549/// that line: each half grazes that face only along its cut edge, and is swept
2550/// whole. The halves' walls share cylinders about the axis.
2551pub fn sweep_solid_parts(tool: &SolidTool, motion: &SolidMotion) -> Result<Vec<BrepSolid>, KernelRefusal> {
2552    let folded = match sweep_solid(tool, motion) {
2553        Ok(body) => return Ok(vec![body]),
2554        Err(error) if refused_as(&error) == Some("folds") => error,
2555        Err(error) => return Err(error),
2556    };
2557    let SolidTool::Polyhedron { vertices, faces } = tool else { return Err(folded) };
2558    let screw = Screw::from_motion(motion)?;
2559    if screw.omega == 0.0 {
2560        return Err(folded);
2561    }
2562    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);
2563    let mut planes: Vec<(Vec3, f64)> = Vec::new();
2564    for face in faces {
2565        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
2566        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
2567        if n.dot(p.sub(centroid)) < 0.0 {
2568            n = n.scale(-1.0);
2569        }
2570        planes.push((n, n.dot(p)));
2571    }
2572    // A face square to the axis' plane through it (its normal square to the
2573    // axis) graze along the line through its foot from the axis; it folds if
2574    // it faces away from the axis and that line crosses it.
2575    for (n, d) in planes.clone() {
2576        if n.dot(screw.e).abs() > 1e-12 {
2577            continue;
2578        }
2579        let foot = screw.a.add(n.scale(d - n.dot(screw.a)));
2580        let radial = foot.sub(screw.a).sub(screw.e.scale(foot.sub(screw.a).dot(screw.e)));
2581        if radial.dot(n) <= 0.0 {
2582            continue; // faces the axis: its grazing line is the sweep's inner wall
2583        }
2584        let cut = match screw.e.cross(radial).normalized() {
2585            Ok(m) => m,
2586            Err(_) => continue,
2587        };
2588        let offset = cut.dot(screw.a);
2589        let mut parts = Vec::with_capacity(2);
2590        for sense in [1.0, -1.0] {
2591            let mut half = planes.clone();
2592            half.push((cut.scale(sense), offset * sense));
2593            let (corners, loops) = polyhedron_of_planes(&half)?;
2594            if corners.len() < 4 || loops.len() < 4 {
2595                parts.clear();
2596                break;
2597            }
2598            match sweep_solid(&SolidTool::Polyhedron { vertices: corners, faces: loops }, motion) {
2599                Ok(body) => parts.push(body),
2600                Err(_) => {
2601                    parts.clear();
2602                    break;
2603                }
2604            }
2605        }
2606        if parts.len() == 2 {
2607            return Ok(parts);
2608        }
2609    }
2610    Err(folded)
2611}
2612
2613/// A screw or turn about the clip's axis maps the clip's cylinder (radius
2614/// ≤ R) onto itself, so inside it the sweep of the tool is the sweep of any
2615/// part of the tool holding the tool's part inside the cylinder. A tool
2616/// reaching far past it (a bar pointing at the axis) is replaced by its part
2617/// inside the prism over the shadow's piece of a slightly larger disc, with
2618/// that disc's arc replaced by the two tangents at its ends: those faces graze
2619/// only along their own end edges, where the far ends of a long tool would
2620/// fold the sweep over itself. None when the tool needs no trim.
2621fn trim_to_clip(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip) -> Result<Option<(Vec<Vec3>, Vec<Vec<usize>>)>, KernelRefusal> {
2622    let Ok(axis) = clip.axis_direction.normalized() else { return Ok(None) };
2623    let same_axis = screw.omega != 0.0
2624        && screw.e.cross(axis).length() < 1e-12
2625        && screw.a.sub(clip.axis_origin).cross(axis).length() < 1e-9 * (1.0 + clip.radius[1]);
2626    if !same_axis || !clip.radius[1].is_finite() {
2627        return Ok(None);
2628    }
2629    let ez = axis;
2630    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))?;
2631    let ey = ez.cross(ex);
2632    let flat = |p: Vec3| {
2633        let r = p.sub(clip.axis_origin);
2634        [r.dot(ex), r.dot(ey)]
2635    };
2636    let radius = clip.radius[1] * 1.02;
2637    let shadow: Vec<[f64; 2]> = vertices.iter().map(|&p| flat(p)).collect();
2638    if shadow.iter().all(|q| q[0].hypot(q[1]) <= radius) {
2639        return Ok(None);
2640    }
2641    // The shadow's convex hull, counter-clockwise.
2642    let mut points = shadow.clone();
2643    points.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
2644    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]);
2645    let mut hull: Vec<[f64; 2]> = Vec::new();
2646    for pass in 0..2 {
2647        let start = hull.len();
2648        let ordered: Vec<[f64; 2]> = if pass == 0 { points.clone() } else { points.iter().rev().copied().collect() };
2649        for p in ordered {
2650            while hull.len() >= start + 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
2651                hull.pop();
2652            }
2653            hull.push(p);
2654        }
2655        hull.pop();
2656    }
2657    // Where the hull's boundary leaves and re-enters the disc.
2658    let m = hull.len();
2659    let inside = |q: [f64; 2]| q[0].hypot(q[1]) <= radius;
2660    // Leave a tool that does not reach the disc, or wraps the axis.
2661    let mut nearest = f64::INFINITY;
2662    let mut wraps = true;
2663    for k in 0..m {
2664        let (a, b) = (hull[k], hull[(k + 1) % m]);
2665        let d = [b[0] - a[0], b[1] - a[1]];
2666        let t = (-(a[0] * d[0] + a[1] * d[1]) / (d[0] * d[0] + d[1] * d[1])).clamp(0.0, 1.0);
2667        nearest = nearest.min((a[0] + d[0] * t).hypot(a[1] + d[1] * t));
2668        if cross(a, b, [0.0, 0.0]) < 0.0 {
2669            wraps = false;
2670        }
2671    }
2672    if wraps || nearest >= radius || (0..m).all(|k| inside(hull[k])) {
2673        return Ok(None);
2674    }
2675    let mut leave: Vec<f64> = Vec::new();
2676    let mut enter: Vec<f64> = Vec::new();
2677    for k in 0..m {
2678        let (a, b) = (hull[k], hull[(k + 1) % m]);
2679        let d = [b[0] - a[0], b[1] - a[1]];
2680        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);
2681        let disc = qb * qb - 4.0 * qa * qc;
2682        if disc <= 0.0 {
2683            continue;
2684        }
2685        for t in [(-qb - disc.sqrt()) / (2.0 * qa), (-qb + disc.sqrt()) / (2.0 * qa)] {
2686            if t > 0.0 && t < 1.0 {
2687                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
2688                let outward = 2.0 * (q[0] * d[0] + q[1] * d[1]) > 0.0;
2689                (if outward { &mut leave } else { &mut enter }).push(q[1].atan2(q[0]));
2690            }
2691        }
2692    }
2693    let ([a], [b]) = (leave.as_slice(), enter.as_slice()) else {
2694        return Err(refuse("clip_trim", "the tool's shadow leaves the clip's disc more than once".into()));
2695    };
2696    let width = (b - a).rem_euclid(TAU);
2697    if width >= 0.9 * PI {
2698        return Err(refuse("clip_trim", "the tool's shadow spans too much of the clip's circle to be trimmed".into()));
2699    }
2700    // Planes of the tool, and the two tangents (outward normals in the plane).
2701    let mut planes: Vec<(Vec3, f64)> = Vec::new();
2702    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);
2703    for face in faces {
2704        let (p, q, r) = (vertices[face[0]], vertices[face[1]], vertices[face[2]]);
2705        let mut n = frag(q.sub(p).cross(r.sub(p)).normalized(), "face_normal")?;
2706        if n.dot(p.sub(centroid)) < 0.0 {
2707            n = n.scale(-1.0);
2708        }
2709        planes.push((n, n.dot(p)));
2710    }
2711    for angle in [*a, *b] {
2712        let n = ex.scale(angle.cos()).add(ey.scale(angle.sin()));
2713        planes.push((n, n.dot(clip.axis_origin) + radius));
2714    }
2715    Ok(Some(polyhedron_of_planes(&planes)?))
2716}
2717
2718/// The convex polyhedron {n · p ≤ d for every plane}: its corners (where three
2719/// planes meet inside all) and a face per plane that bounds it.
2720pub fn polyhedron_of_planes(planes: &[(Vec3, f64)]) -> Result<(Vec<Vec3>, Vec<Vec<usize>>), KernelRefusal> {
2721    let k = planes.len();
2722    let mut corners: Vec<Vec3> = Vec::new();
2723    let scale = planes.iter().map(|p| p.1.abs()).fold(1.0f64, f64::max);
2724    for i in 0..k {
2725        for j in i + 1..k {
2726            for l in j + 1..k {
2727                let (a, b, c) = (planes[i].0, planes[j].0, planes[l].0);
2728                let det = a.dot(b.cross(c));
2729                if det.abs() < 1e-12 {
2730                    continue;
2731                }
2732                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);
2733                if planes.iter().all(|(n, d)| n.dot(p) - d <= 1e-9 * scale) && !corners.iter().any(|q| q.sub(p).length() <= 1e-9 * scale) {
2734                    corners.push(p);
2735                }
2736            }
2737        }
2738    }
2739    let mut faces = Vec::new();
2740    for (n, d) in planes {
2741        let on: Vec<usize> = (0..corners.len()).filter(|&c| (n.dot(corners[c]) - d).abs() <= 1e-9 * scale).collect();
2742        if on.len() < 3 {
2743            continue;
2744        }
2745        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);
2746        let u = frag(corners[on[0]].sub(middle).normalized(), "face_axis")?;
2747        let v = n.cross(u);
2748        let mut ordered = on.clone();
2749        ordered.sort_by(|&p, &q| {
2750            let (rp, rq) = (corners[p].sub(middle), corners[q].sub(middle));
2751            rp.dot(v).atan2(rp.dot(u)).total_cmp(&rq.dot(v).atan2(rq.dot(u)))
2752        });
2753        faces.push(ordered);
2754    }
2755    Ok((corners, faces))
2756}
2757
2758fn turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>], clip: &crate::SweepClip, axis: Vec3, wedge: [f64; 2]) -> Result<BrepSolid, KernelRefusal> {
2759    let ez = axis;
2760    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()))?;
2761    let ey = ez.cross(ex);
2762    // Turning by ω t about e = ±ez moves angles about ez by ±ω t.
2763    let rate = screw.omega * screw.e.dot(ez).signum();
2764    let local = |p: Vec3| {
2765        let r = p.sub(clip.axis_origin);
2766        [r.dot(ex), r.dot(ey), r.dot(ez)]
2767    };
2768    let corners: Vec<[f64; 3]> = vertices.iter().map(|&p| local(p)).collect();
2769    // The tool's angular extent about the axis (its corners'; the tool must
2770    // keep off the axis, so its shadow on the plane misses the origin).
2771    let mid = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
2772    let mid_angle = mid[1].atan2(mid[0]);
2773    let angles: Vec<f64> = corners.iter().map(|c| mid_angle + (c[1].atan2(c[0]) - mid_angle + PI).rem_euclid(TAU) - PI).collect();
2774    let (low, high) = (angles.iter().copied().fold(f64::INFINITY, f64::min), angles.iter().copied().fold(f64::NEG_INFINITY, f64::max));
2775    if high - low >= PI {
2776        return Err(refuse("turn_shadow", "the tool reaches round the turn's axis".into()));
2777    }
2778    let (start, end) = (rate * screw.t0, rate * screw.t1);
2779    let (first, last) = if rate > 0.0 { (start, end) } else { (end, start) };
2780    let reference = 0.5 * (wedge[0] + wedge[1]);
2781    let near = |a: f64| reference + (a - reference + PI).rem_euclid(TAU) - PI;
2782    // Before the wedge at one end, after it at the other (angles taken near the wedge).
2783    let clear = near(high + first) < wedge[0] - 1e-9 && near(low + last) > wedge[1] + 1e-9 && (last - first) < TAU;
2784    if !clear {
2785        return Err(refuse("turn_shadow", "the turned tool's ends reach the clip's wedge; its sweep there is not its turned shadow".into()));
2786    }
2787    let profile = polyhedron_shadow(&corners, faces, false)?;
2788    // The profile in the half-plane at the wedge's start angle.
2789    let (c0, s0) = (wedge[0].cos(), wedge[0].sin());
2790    let world = |rho: f64, z: f64| clip.axis_origin.add(ez.scale(z)).add(ex.scale(rho * c0)).add(ey.scale(rho * s0));
2791    let mut curves = Vec::with_capacity(profile.len());
2792    for piece in &profile {
2793        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
2794        let curve = if points.len() == 2 {
2795            frag(make_line(frag(points[0].point(), "point")?, frag(points[1].point(), "point")?), "line")?
2796        } else {
2797            frag(NurbsCurve::new(2, vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points), "conic")?
2798        };
2799        curves.push(curve);
2800    }
2801    frag(crate::revolve_profile_brep(&curves, clip.axis_origin, ez, wedge[1] - wedge[0]), "turn_shadow")
2802}
2803
2804/// A convex polyhedron turned a whole turn (no advance): the solid of
2805/// revolution of its shadow {(ρ, z)} about the turn's axis, which may pass
2806/// through it. Its corners' paths bound it only where an edge is farthest
2807/// from the axis; an edge skew to the axis turns a hyperboloid.
2808fn whole_turn_shadow(screw: &Screw, vertices: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
2809    let ez = screw.e;
2810    let ex = frag(ez.perpendicular(), "turn_shadow")?;
2811    let ex = frag(ex.sub(ez.scale(ex.dot(ez))).normalized(), "turn_shadow")?;
2812    let ey = ez.cross(ex);
2813    let corners: Vec<[f64; 3]> = vertices
2814        .iter()
2815        .map(|&p| {
2816            let r = screw.apply(screw.t0, p).sub(screw.a);
2817            [r.dot(ex), r.dot(ey), r.dot(ez)]
2818        })
2819        .collect();
2820    let profile = polyhedron_shadow(&corners, faces, true)?;
2821    // A point of the outline on the axis to round-off is on it.
2822    let reach = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(0.0f64, f64::max);
2823    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 }));
2824    let mut curves = Vec::with_capacity(profile.len());
2825    // The outline's stretch along the axis, as one edge (it comes a piece per
2826    // corner height).
2827    let on_axis = |piece: &ShadowPiece| piece.iter().all(|&(rho, _, _)| rho.abs() <= 1e-10 * reach);
2828    let mut along: Option<(f64, f64)> = None;
2829    for piece in &profile {
2830        if on_axis(piece) {
2831            let (za, zb) = (piece[0].1, piece[piece.len() - 1].1);
2832            along = Some(match along {
2833                Some((from, _)) => (from, zb),
2834                None => (za, zb),
2835            });
2836            continue;
2837        }
2838        if let Some((from, to)) = along.take() {
2839            curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
2840        }
2841        let points: Vec<Vec4> = piece.iter().map(|&(rho, z, w)| Vec4::from_point(world(rho, z), w)).collect();
2842        let (first, last) = (frag(points[0].point(), "point")?, frag(points[points.len() - 1].point(), "point")?);
2843        if first.sub(last).length() <= 1e-12 * (1.0 + first.length()) {
2844            continue;
2845        }
2846        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")? };
2847        curves.push(curve);
2848    }
2849    if let Some((from, to)) = along.take() {
2850        curves.push(frag(make_line(world(0.0, from), world(0.0, to)), "line")?);
2851    }
2852    frag(crate::revolve_profile_brep(&curves, screw.a, ez, TAU), "turn_shadow")
2853}
2854
2855/// One piece of the shadow's outline: a segment (two points) or a rational
2856/// quadratic arc (three, the middle with its weight), as (ρ, z, weight).
2857type ShadowPiece = Vec<(f64, f64, f64)>;
2858
2859/// The shadow {(ρ, z)} of a convex polyhedron (corners in the axis frame):
2860/// at each z its section is a convex polygon, the ρ it reaches an interval
2861/// from the section's nearest point to its farthest corner. The farthest is
2862/// always on an edge (ρ² = quadratic in z: a conic arc); the nearest is on a
2863/// face (ρ linear in z: a segment) or an edge.
2864///
2865/// `through`: the axis may pass through the tool (its nearest ρ is then 0 and
2866/// the outline runs along the axis there); refused otherwise.
2867fn polyhedron_shadow(corners: &[[f64; 3]], faces: &[Vec<usize>], through: bool) -> Result<Vec<ShadowPiece>, KernelRefusal> {
2868    let zs: Vec<f64> = corners.iter().map(|c| c[2]).collect();
2869    let (z_low, z_high) = (zs.iter().copied().fold(f64::INFINITY, f64::min), zs.iter().copied().fold(f64::NEG_INFINITY, f64::max));
2870    let scale = corners.iter().map(|c| c[0].hypot(c[1]).max(c[2].abs())).fold(1.0f64, f64::max);
2871    // The hull's edges (from the faces' loops) and the faces beside each.
2872    let mut edge_faces: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
2873    for (f, face) in faces.iter().enumerate() {
2874        for k in 0..face.len() {
2875            let (i, j) = (face[k], face[(k + 1) % face.len()]);
2876            edge_faces.entry((i.min(j), i.max(j))).or_default().push(f);
2877        }
2878    }
2879    let mut edges: Vec<(usize, usize)> = edge_faces.keys().copied().collect();
2880    edges.sort_unstable();
2881    // Each face's plane in the axis frame: n · p = d.
2882    let planes: Vec<([f64; 3], f64)> = faces
2883        .iter()
2884        .map(|face| {
2885            let (a, b, c) = (corners[face[0]], corners[face[1]], corners[face[2]]);
2886            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]]);
2887            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]];
2888            (n, n[0] * a[0] + n[1] * a[1] + n[2] * a[2])
2889        })
2890        .collect();
2891    #[derive(Clone, Copy, PartialEq, Debug)]
2892    enum Source {
2893        /// The crossing of edge k.
2894        Edge(usize),
2895        /// The nearest point of face f's section line.
2896        Face(usize),
2897        /// The axis itself, where it passes through the tool.
2898        Axis,
2899    }
2900    let edge_at = |k: usize, z: f64| -> [f64; 2] {
2901        let (a, b) = (corners[edges[k].0], corners[edges[k].1]);
2902        let t = (z - a[2]) / (b[2] - a[2]);
2903        [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
2904    };
2905    let crossing = |z: f64| -> Vec<usize> {
2906        (0..edges.len()).filter(|&k| (corners[edges[k].0][2] - z) * (corners[edges[k].1][2] - z) < 0.0).collect()
2907    };
2908    let farthest = |z: f64| -> (Source, f64) {
2909        let mut best = (Source::Edge(0), f64::NEG_INFINITY);
2910        for k in crossing(z) {
2911            let p = edge_at(k, z);
2912            let r = p[0].hypot(p[1]);
2913            if r > best.1 {
2914                best = (Source::Edge(k), r);
2915            }
2916        }
2917        best
2918    };
2919    // The section polygon: edge crossings ordered by angle about their mean.
2920    let nearest = |z: f64| -> Result<(Source, f64), KernelRefusal> {
2921        let list = crossing(z);
2922        let points: Vec<[f64; 2]> = list.iter().map(|&k| edge_at(k, z)).collect();
2923        let m = points.len();
2924        if m < 3 {
2925            return Err(refuse("turn_shadow", "a section of the tool is not a polygon".into()));
2926        }
2927        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]);
2928        let mut order: Vec<usize> = (0..m).collect();
2929        order.sort_by(|&a, &b| {
2930            let (pa, pb) = (points[a], points[b]);
2931            (pa[1] - centre[1]).atan2(pa[0] - centre[0]).total_cmp(&(pb[1] - centre[1]).atan2(pb[0] - centre[0]))
2932        });
2933        let mut inside = true;
2934        let mut best = (Source::Edge(0), f64::INFINITY);
2935        for k in 0..m {
2936            let (ia, ib) = (order[k], order[(k + 1) % m]);
2937            let (a, b) = (points[ia], points[ib]);
2938            let d = [b[0] - a[0], b[1] - a[1]];
2939            if d[0] * (0.0 - a[1]) - d[1] * (0.0 - a[0]) < 0.0 {
2940                inside = false;
2941            }
2942            let length2 = d[0] * d[0] + d[1] * d[1];
2943            let t = -(a[0] * d[0] + a[1] * d[1]) / length2;
2944            let (source, r) = if t > 0.0 && t < 1.0 {
2945                let (ea, eb) = (edges[list[ia]], edges[list[ib]]);
2946                let shared = edge_faces[&ea].iter().find(|f| edge_faces[&eb].contains(f)).copied();
2947                let Some(face) = shared else {
2948                    return Err(refuse("turn_shadow", "a section side does not lie on one face".into()));
2949                };
2950                let q = [a[0] + d[0] * t, a[1] + d[1] * t];
2951                (Source::Face(face), q[0].hypot(q[1]))
2952            } else {
2953                let q = if t <= 0.0 { a } else { b };
2954                (Source::Edge(list[if t <= 0.0 { ia } else { ib }]), q[0].hypot(q[1]))
2955            };
2956            if r < best.1 {
2957                best = (source, r);
2958            }
2959        }
2960        if inside {
2961            if !through {
2962                return Err(refuse("turn_shadow", "the turn's axis passes through the tool".into()));
2963            }
2964            return Ok((Source::Axis, 0.0));
2965        }
2966        Ok(best)
2967    };
2968    // ρ of a source at z, from its own geometry (smooth across the piece).
2969    let value = |source: Source, z: f64| -> f64 {
2970        match source {
2971            Source::Edge(k) => {
2972                let p = edge_at(k, z);
2973                p[0].hypot(p[1])
2974            }
2975            Source::Face(f) => {
2976                let (n, d) = planes[f];
2977                (d - n[2] * z).abs() / n[0].hypot(n[1])
2978            }
2979            Source::Axis => 0.0,
2980        }
2981    };
2982    // Breaks: corner heights, and where the farthest or nearest source changes.
2983    let mut heights: Vec<f64> = zs.clone();
2984    heights.sort_by(|a, b| a.total_cmp(b));
2985    heights.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * scale);
2986    let mut pieces_far: Vec<(f64, f64, Source)> = Vec::new();
2987    let mut pieces_near: Vec<(f64, f64, Source)> = Vec::new();
2988    for window in heights.windows(2) {
2989        let (za, zb) = (window[0], window[1]);
2990        let samples = 400;
2991        let inner = |k: usize| za + (zb - za) * (k as f64 + 0.5) / samples as f64;
2992        for near in [false, true] {
2993            let source_at = |z: f64| -> Result<Source, KernelRefusal> { Ok(if near { nearest(z)?.0 } else { farthest(z).0 }) };
2994            let mut runs: Vec<(f64, Source)> = vec![(za, source_at(inner(0))?)];
2995            for k in 1..samples {
2996                let (z0, z1) = (inner(k - 1), inner(k));
2997                let (s0, s1) = (source_at(z0)?, source_at(z1)?);
2998                // Two sources tied over the stretch (edges equally far from
2999                // the axis) are one piece of the outline.
3000                let tied = [z0, 0.5 * (z0 + z1), z1].iter().all(|&z| (value(s0, z) - value(s1, z)).abs() <= 1e-12 * scale);
3001                if s0 == s1 || tied {
3002                    continue;
3003                }
3004                // Where the source changes, by bisection (a side handing over
3005                // to its corner touches it, so their values do not cross).
3006                let (mut lo, mut hi) = (z0, z1);
3007                for _ in 0..200 {
3008                    let midz = 0.5 * (lo + hi);
3009                    if source_at(midz)? == s0 { lo = midz } else { hi = midz }
3010                }
3011                runs.push((0.5 * (lo + hi), s1));
3012            }
3013            let list = if near { &mut pieces_near } else { &mut pieces_far };
3014            for k in 0..runs.len() {
3015                let z_end = if k + 1 < runs.len() { runs[k + 1].0 } else { zb };
3016                list.push((runs[k].0, z_end, runs[k].1));
3017            }
3018        }
3019    }
3020    // Exact pieces: a pair's ρ(z) is a conic arc, a side's a segment.
3021    let piece = |source: Source, za: f64, zb: f64| -> Vec<ShadowPiece> {
3022        let (ra, rb) = (value(source, za), value(source, zb));
3023        if matches!(source, Source::Face(..) | Source::Axis) {
3024            return vec![vec![(ra, za, 1.0), (rb, zb, 1.0)]];
3025        }
3026        // ρ² = α z² + β z + γ; split so each arc turns little.
3027        let rho = |z: f64| value(source, z);
3028        // Differences kept inside the piece (an edge through the axis has a
3029        // corner in ρ at its end there).
3030        let (z_min, z_max) = (za.min(zb), za.max(zb));
3031        let slope = |z: f64| {
3032            let h = 1e-6 * (zb - za).abs().max(1e-300);
3033            let (zp, zm) = ((z + h).min(z_max), (z - h).max(z_min));
3034            (rho(zp) - rho(zm)) / (zp - zm)
3035        };
3036        let parts = 4;
3037        let mut out = Vec::new();
3038        for k in 0..parts {
3039            let (z0, z1) = (za + (zb - za) * k as f64 / parts as f64, za + (zb - za) * (k + 1) as f64 / parts as f64);
3040            let (a, b) = ((rho(z0), z0), (rho(z1), z1));
3041            // Straight (an edge meeting the axis): a segment.
3042            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);
3043            if bend <= 1e-12 * scale {
3044                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3045                continue;
3046            }
3047            let (ta, tb) = ((slope(z0), 1.0), (slope(z1), 1.0));
3048            // Tangent lines' intersection.
3049            let det = ta.0 * (-tb.1) - ta.1 * (-tb.0);
3050            if det.abs() < 1e-12 {
3051                out.push(vec![(a.0, a.1, 1.0), (b.0, b.1, 1.0)]);
3052                continue;
3053            }
3054            let rhs = (b.0 - a.0, b.1 - a.1);
3055            let s = (rhs.0 * (-tb.1) - rhs.1 * (-tb.0)) / det;
3056            let c = (a.0 + ta.0 * s, a.1 + ta.1 * s);
3057            // Shoulder: the conic's point on the line from the chord's middle to c.
3058            let m = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
3059            let on = |u: f64| {
3060                let p = (m.0 + (c.0 - m.0) * u, m.1 + (c.1 - m.1) * u);
3061                p.0 - rho(p.1)
3062            };
3063            let (mut lo, mut hi) = (0.0, 1.0);
3064            let sign_lo = on(lo);
3065            for _ in 0..200 {
3066                let mid = 0.5 * (lo + hi);
3067                if (on(mid) > 0.0) == (sign_lo > 0.0) { lo = mid } else { hi = mid }
3068            }
3069            let u = 0.5 * (lo + hi);
3070            let weight = u / (1.0 - u);
3071            out.push(vec![(a.0, a.1, 1.0), (c.0, c.1, weight), (b.0, b.1, 1.0)]);
3072        }
3073        out
3074    };
3075    // Outline: up the near side, across the top, down the far side, across the bottom.
3076    let mut outline: Vec<ShadowPiece> = Vec::new();
3077    for &(za, zb, source) in &pieces_near {
3078        outline.extend(piece(source, za, zb));
3079    }
3080    let (near_top, far_top) = (value(pieces_near.last().expect("near").2, z_high), value(pieces_far.last().expect("far").2, z_high));
3081    if far_top - near_top > 1e-12 * scale {
3082        outline.push(vec![(near_top, z_high, 1.0), (far_top, z_high, 1.0)]);
3083    }
3084    for &(za, zb, source) in pieces_far.iter().rev() {
3085        for mut arc in piece(source, za, zb).into_iter().rev() {
3086            arc.reverse();
3087            outline.push(arc);
3088        }
3089    }
3090    let (near_bottom, far_bottom) = (value(pieces_near[0].2, z_low), value(pieces_far[0].2, z_low));
3091    if far_bottom - near_bottom > 1e-12 * scale {
3092        outline.push(vec![(far_bottom, z_low, 1.0), (near_bottom, z_low, 1.0)]);
3093    }
3094    // Snap consecutive ends together.
3095    for k in 0..outline.len() {
3096        let next = (k + 1) % outline.len();
3097        let end = *outline[k].last().expect("piece");
3098        outline[next][0] = (end.0, end.1, 1.0);
3099    }
3100    Ok(outline)
3101}
3102
3103/// A ball TURNED about an axis that passes through it. Its grazing circle (in
3104/// the plane of the axis and the centre) crosses the axis at two poles N and S;
3105/// the part beyond the axis turns inside the sweep, and near the axis the ends
3106/// overlap. So the sweep has three faces: the wall, the outer arc of that
3107/// circle turned (a spindle torus's outer part, pinched at N and S); the
3108/// ball's back at the start less the ball at the end; and its front at the end
3109/// less the ball at the start. The two caps meet along the far arc, from S to
3110/// N, of the circle where the two spheres meet. None when the motion or tool
3111/// is not of that kind.
3112fn ball_across_axis(screw: &Screw, origin: Vec3, axis: Vec3, meridian: &[OutlinePiece]) -> Result<Option<BrepSolid>, KernelRefusal> {
3113    let [OutlinePiece::Arc { centre, radius, start, end }, OutlinePiece::Line { .. }] = meridian else { return Ok(None) };
3114    let (centre, r) = (*centre, *radius);
3115    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 {
3116        return Ok(None);
3117    }
3118    let w = axis.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
3119    let centre_tool = origin.add(w.scale(centre[1]));
3120    let turned = screw.omega * (screw.t1 - screw.t0);
3121    if turned.abs() >= TAU - 1e-9 {
3122        return Ok(None);
3123    }
3124    let e = screw.e.scale(screw.omega.signum()); // the sense the ball turns about
3125    let c0 = screw.apply(screw.t0, centre_tool);
3126    let c1 = screw.apply(screw.t1, centre_tool);
3127    let foot = |c: Vec3| screw.a.add(e.scale(c.sub(screw.a).dot(e)));
3128    let rho = c0.sub(foot(c0)).length();
3129    if rho >= r * (1.0 - 1e-9) || rho <= 1e-9 * r {
3130        return Ok(None);
3131    }
3132    let h0 = frag(c0.sub(foot(c0)).normalized(), "radial")?;
3133    let height = (r * r - rho * rho).sqrt();
3134    let (north, south) = (foot(c0).add(e.scale(height)), foot(c0).sub(e.scale(height)));
3135    // An arc from `from` turned about `axis` through `centre` by `angle`.
3136    let arc = |about: Vec3, k: Vec3, from: Vec3, angle: f64| -> Result<NurbsCurve, KernelRefusal> {
3137        let surface = frag(make_revolution(about, k, &frag(make_line(from, from.add(k)), "line")?, angle), "arc")?;
3138        frag(surface.iso_curve_v(0.0), "arc")
3139    };
3140    // The outer arc of the grazing circle, S -> N through c0 + r h0: in the
3141    // (h0, e) plane about c0, from angle -α to α through 0, α = atan2(height, -ρ).
3142    let alpha = height.atan2(-rho);
3143    let outer = arc(c0, h0.cross(e), south, 2.0 * alpha)?;
3144    let wall = frag(make_revolution(screw.a, e, &outer, turned.abs()), "wall")?;
3145    let outer_end = frag(wall.iso_curve_u(1.0), "wall_end")?;
3146    // The far arc where the spheres meet, S -> N beyond the axis.
3147    let mid = c0.add(c1).scale(0.5);
3148    let towards = frag(mid.sub(foot(mid)).normalized(), "bisector")?;
3149    let rho_mid = mid.sub(foot(mid)).length();
3150    let beta = height.atan2(rho_mid); // S and N seen from mid, off the far direction
3151    // From S at angle β − π (in the (towards, e) plane about mid) down through
3152    // π to N at π − β: the decreasing sense, about e × towards.
3153    let meet = arc(mid, e.cross(towards), south, 2.0 * beta)?;
3154    {
3155        // The arc must pass beyond the axis (its middle on the far side).
3156        let [d0, d1] = frag(meet.domain(), "domain")?;
3157        let middle = frag(meet.evaluate(0.5 * (d0 + d1)), "middle")?;
3158        if middle.sub(foot(middle)).dot(towards) > 0.0 {
3159            return Err(refuse("ball_across_axis", "the spheres' common circle runs the wrong way round".into()));
3160        }
3161    }
3162    // A trimmed sphere cap: a chart whose poles and seam lie where the cap is not.
3163    let cap = |c: Vec3, inward: Vec3, side: Vec3, other: Vec3| -> Result<(NurbsSurface, Box<dyn Fn(Vec3) -> Vec3>), KernelRefusal> {
3164        // South pole just off the far end of the grazing circle, on the removed
3165        // side (inside the other end's ball); the seam crosses the grazing
3166        // circle beyond the axis only.
3167        let toward_south = frag(inward.add(side.scale(-0.3)).normalized(), "pole")?;
3168        let polar = toward_south.scale(-1.0);
3169        let seam = frag(side.sub(polar.scale(side.dot(polar))).normalized(), "seam")?;
3170        for k in 0..=64 {
3171            // The seam's part on the cap's side of the grazing circle must lie
3172            // inside the other ball (where the cap is not).
3173            let a = PI * k as f64 / 64.0;
3174            let q = c.add(polar.scale(-r * a.cos())).add(seam.scale(r * a.sin()));
3175            if q.sub(c).dot(side) < 0.0 && q.sub(other).length() >= r * (1.0 - 1e-9) {
3176                return Err(refuse("ball_across_axis", "no seam place for a cap".into()));
3177            }
3178        }
3179        let south_pole = c.sub(polar.scale(r));
3180        if south_pole.sub(other).length() >= r * (1.0 - 1e-6) {
3181            return Err(refuse("ball_across_axis", "no pole place for a cap".into()));
3182        }
3183        let generatrix = arc(c, polar.scale(-1.0).cross(seam), south_pole, PI)?;
3184        let surface = frag(make_revolution(c, polar, &generatrix, TAU), "cap")?;
3185        let spans_u = (surface.knots_u.len() - 6) / 2 + 1;
3186        let spans_v = (generatrix.knots.len() - 6) / 2 + 1;
3187        let around = polar.cross(seam);
3188        let inverse = move |x: Vec3| -> Vec3 {
3189            let d = x.sub(c).scale(1.0 / r);
3190            let latitude = d.dot(polar).clamp(-1.0, 1.0).asin();
3191            let longitude = d.dot(around).atan2(d.dot(seam)).rem_euclid(TAU);
3192            Vec3::new(
3193                crate::circle_angle_to_parameter(spans_u, TAU, longitude),
3194                crate::circle_angle_to_parameter(spans_v, PI, latitude + 0.5 * PI),
3195                0.0,
3196            )
3197        };
3198        Ok((surface, Box::new(inverse)))
3199    };
3200    let moving0 = e.cross(h0);
3201    let h1 = frag(c1.sub(foot(c1)).normalized(), "radial")?;
3202    let moving1 = e.cross(h1);
3203    // The back cap at the start (its removed part near c0 − r h0 on the back);
3204    // the front cap at the end.
3205    let (back, back_inverse) = cap(c0, h0.scale(-1.0), moving0.scale(1.0), c1)?;
3206    let (front, front_inverse) = cap(c1, h1.scale(-1.0), moving1.scale(-1.0), c0)?;
3207    let pcurve = |inverse: &dyn Fn(Vec3) -> Vec3, curve: &NurbsCurve, forward: bool| -> Result<NurbsCurve, KernelRefusal> {
3208        let [d0, d1] = frag(curve.domain(), "domain")?;
3209        let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
3210        let uv: Vec<Vec3> = ts.iter().map(|&t| curve.evaluate(t).map(|x| inverse(x))).collect::<Result<_, _>>().map_err(|e| refuse("pcurve", e))?;
3211        let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "cap_pcurve")?;
3212        if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
3213    };
3214    let mut shell = Shell::new();
3215    let (vn, vs) = (shell.vertex(north), shell.vertex(south));
3216    let k0 = shell.edge(outer.clone(), vs, vn, false)?;
3217    let k1 = shell.edge(outer_end.clone(), vs, vn, false)?;
3218    let c = shell.edge(meet.clone(), vs, vn, false)?;
3219    let ds = shell.edge(frag(make_line(south, south), "point")?, vs, vs, true)?;
3220    let dn = shell.edge(frag(make_line(north, north), "point")?, vn, vn, true)?;
3221    // Wall: u turns, v runs S -> N; outward needs v the other way round the
3222    // circle's normal, so test and pick the loop's sense.
3223    let wall_outward = {
3224        let p = frag(wall.evaluate(0.5, 0.5), "probe")?;
3225        let su = frag(wall.evaluate(0.5 + 1e-6, 0.5), "probe")?.sub(frag(wall.evaluate(0.5 - 1e-6, 0.5), "probe")?);
3226        let sv = frag(wall.evaluate(0.5, 0.5 + 1e-6), "probe")?.sub(frag(wall.evaluate(0.5, 0.5 - 1e-6), "probe")?);
3227        su.cross(sv).dot(p.sub(foot(p))) > 0.0
3228    };
3229    let [g0, g1] = frag(outer.domain(), "domain")?;
3230    let wall_loop = vec![
3231        (ds, true, uv_line([0.0, g0], [1.0, g0])?),
3232        (k1, true, uv_line([1.0, g0], [1.0, g1])?),
3233        (dn, true, uv_line([1.0, g1], [0.0, g1])?),
3234        (k0, false, uv_line([0.0, g1], [0.0, g0])?),
3235    ];
3236    let reversed = |list: Vec<(u64, bool, NurbsCurve)>| -> Result<Vec<(u64, bool, NurbsCurve)>, KernelRefusal> {
3237        list.into_iter().rev().map(|(e, f, p)| Ok((e, !f, frag(p.reversed(), "reversed")?))).collect()
3238    };
3239    shell.face(wall.clone(), if wall_outward { wall_loop } else { reversed(wall_loop)? });
3240    // Caps: loop (grazing arc S -> N, then the meeting arc N -> S), sense by
3241    // the signed area of its parameters (the charts' u × v points outward).
3242    for (surface, inverse, k_edge, k_curve) in [(back, &back_inverse, k0, &outer), (front, &front_inverse, k1, &outer_end)] {
3243        let mut lp = vec![(k_edge, true, pcurve(inverse.as_ref(), k_curve, true)?), (c, false, pcurve(inverse.as_ref(), &meet, false)?)];
3244        let mut area = 0.0;
3245        for (_, _, pc) in &lp {
3246            let [d0, d1] = frag(pc.domain(), "domain")?;
3247            for j in 0..64 {
3248                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")?);
3249                area += a.x * b.y - b.x * a.y;
3250            }
3251        }
3252        if area < 0.0 {
3253            lp = reversed(lp)?;
3254        }
3255        shell.face(surface, lp);
3256    }
3257    let body = shell.solid();
3258    let issues = body.validate();
3259    if !issues.is_empty() {
3260        return Err(refuse("assembly", format!("the turned ball's sweep is not valid: {:?}", issues.first())));
3261    }
3262    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() } };
3263    check_single_pass(screw, &probe, &body, &std::collections::HashSet::new())?;
3264    Ok(Some(body))
3265}
3266
3267/// A frame riding a cubic Bézier curve (`control`, in a plane square to
3268/// `up`): its origin on the curve, its first axis along the curve's tangent,
3269/// `up` fixed. The tool is given in the frame at the curve's start and carried
3270/// by it over the whole curve.
3271#[derive(Clone, Copy, Debug)]
3272pub struct FrameCurve {
3273    pub control: [Vec3; 4],
3274    pub up: Vec3,
3275}
3276
3277/// The whole sweep of a solid of revolution carried by a frame along a
3278/// curve. In the riding frame the velocity field is the speed along the
3279/// tangent plus the turn about `up`, so the grazing loop moves on the tool with
3280/// the curve's curvature. It is split at sample times (its structure must not
3281/// change), each piece sampled exactly, and the walls lofted through those
3282/// samples (quintic both ways; the samples' count doubles until the wall is
3283/// within `LOFT_TARGET` of the exact loop at the times between). Caps are the tool's
3284/// back at the start and front at the end.
3285pub fn sweep_solid_along(tool: &SolidTool, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
3286    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
3287    let base = path.control[0];
3288    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
3289        return Err(input("plane", "the curve is not in a plane square to up".into()));
3290    }
3291    let tangent = path.control[1].sub(base);
3292    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
3293    let start_tangent = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
3294    let frame = Frame { control: path.control, up, start_tangent };
3295    let (mut speed, mut rate, mut extent) = (0.0f64, 0.0f64, 0.0f64);
3296    let mut previous = 0.0;
3297    for k in 0..=512 {
3298        let t = k as f64 / 512.0;
3299        let first = frame.first(t);
3300        if first.length() <= 1e-12 {
3301            return Err(input("tangent", "the curve stops (zero tangent)".into()));
3302        }
3303        speed = speed.max(first.length());
3304        rate = rate.max(frame.angle_rate(t).abs());
3305        extent = extent.max(frame.point(t).sub(base).length());
3306        let angle = frame.angle(t);
3307        if (angle - previous).abs() > 0.5 {
3308            return Err(refuse("frame_turns", "the frame turns half way round".into()));
3309        }
3310        previous = angle;
3311    }
3312    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,
3313        loop_samples: LOFT_SAMPLES, extent };
3314    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
3315        return Err(refuse("along_tool", "a frame along a curve carries a solid of revolution only".into()));
3316    };
3317    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
3318    // The splits name their pieces by angle about the tool's axis from its
3319    // radial direction: a grazing angle passing that reference renames them,
3320    // so try a few references.
3321    let mut last = None;
3322    for k in 0..8 {
3323        let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
3324        match lofted(&screw, *axis_origin, axis, reference, meridian) {
3325            Err(error) if refused_as(&error) == Some("loft_structure") => last = Some(error),
3326            other => return other,
3327        }
3328    }
3329    Err(last.expect("tried"))
3330}
3331
3332/// The whole sweep of a prism carried by a frame along a planar curve (its
3333/// axis along the frame's up): the prism `outline` (a convex polygon in the
3334/// start frame: first coordinate along the start tangent, second along
3335/// up × tangent) between `from` and `to` along up. The motion is planar, so the
3336/// sweep is the plane region the moving outline covers, extruded. That region
3337/// is found exactly: its boundary lies on the outline's corner paths, the paths
3338/// of each edge's grazing point (where the edge's normal is square to the
3339/// velocity), and the outline's edges at the two ends; these are split where
3340/// they meet, and a piece is kept where one side of it is covered and the other
3341/// not (folds, where a corner digs past a side, come out right).
3342pub fn sweep_prism_along(outline: &[[f64; 2]], from: f64, to: f64, path: &FrameCurve) -> Result<BrepSolid, KernelRefusal> {
3343    let up = path.up.normalized().map_err(|_| input("up", "the frame's up direction is zero".into()))?;
3344    let base = path.control[0];
3345    if path.control.iter().any(|p| p.sub(base).dot(up).abs() > 1e-9 * (1.0 + p.sub(base).length())) {
3346        return Err(input("plane", "the curve is not in a plane square to up".into()));
3347    }
3348    let tangent = path.control[1].sub(base);
3349    let tangent = if tangent.length() > 0.0 { tangent } else { path.control[2].sub(base) };
3350    let e1 = tangent.normalized().map_err(|_| input("tangent", "the curve has no start direction".into()))?;
3351    let e2 = up.cross(e1);
3352    let frame = Frame { control: path.control, up, start_tangent: e1 };
3353    // The frame in plane coordinates: origin c(s), turned by φ(s).
3354    let flat = |p: Vec3| [p.sub(base).dot(e1), p.sub(base).dot(e2)];
3355    let pose = |s: f64| (flat(frame.point(s)), frame.angle(s));
3356    let rates = |s: f64| {
3357        let first = frame.first(s);
3358        ([first.dot(e1), first.dot(e2)], frame.angle_rate(s))
3359    };
3360    prism_region_sweep(outline, from, to, base, e1, e2, up, &pose, &rates, false)
3361}
3362
3363/// The whole sweep of a prism (the convex polygon `outline` in the plane
3364/// through `base` spanned by `e1`, `e2`, between `from` and `to` along `up`)
3365/// under a planar rigid motion: at s ∈ [0, 1] a point q of the plane (in the
3366/// tool's own coordinates) is at origin(s) + R(angle(s)) q, `pose` giving
3367/// (origin, angle) and `rates` their derivatives in s. The sweep is the plane
3368/// region the moving outline covers, extruded. That region is found exactly:
3369/// its boundary lies on the outline's corner paths, the paths of each edge's
3370/// grazing point (where the edge's normal is square to the velocity), and,
3371/// unless the motion is `closed` (it ends where it starts), the outline's
3372/// edges at the two ends; these are split where they meet or cross
3373/// themselves, and a piece is kept where one side of it is covered and the
3374/// other not. The region may have holes.
3375#[allow(clippy::too_many_arguments)]
3376pub fn prism_region_sweep(
3377    outline: &[[f64; 2]],
3378    from: f64,
3379    to: f64,
3380    base: Vec3,
3381    e1: Vec3,
3382    e2: Vec3,
3383    up: Vec3,
3384    pose: &dyn Fn(f64) -> ([f64; 2], f64),
3385    rates: &dyn Fn(f64) -> ([f64; 2], f64),
3386    closed: bool,
3387) -> Result<BrepSolid, KernelRefusal> {
3388    if outline.len() < 3 || !(to > from) {
3389        return Err(input("prism", "a prism needs three corners and a positive height".into()));
3390    }
3391    // Counter-clockwise, convex.
3392    let n = outline.len();
3393    let mut corners = outline.to_vec();
3394    let area: f64 = (0..n).map(|k| corners[k][0] * corners[(k + 1) % n][1] - corners[(k + 1) % n][0] * corners[k][1]).sum();
3395    if area < 0.0 {
3396        corners.reverse();
3397    }
3398    for k in 0..n {
3399        let (a, b, c) = (corners[k], corners[(k + 1) % n], corners[(k + 2) % n]);
3400        if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) <= 0.0 {
3401            return Err(input("prism", "the outline is not convex".into()));
3402        }
3403    }
3404    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
3405    let place = |s: f64, q: [f64; 2]| -> [f64; 2] {
3406        let (o, angle) = pose(s);
3407        let (sn, cs) = angle.sin_cos();
3408        [o[0] + cs * q[0] - sn * q[1], o[1] + sn * q[0] + cs * q[1]]
3409    };
3410    let local = |s: f64, p: [f64; 2]| -> [f64; 2] {
3411        let (o, angle) = pose(s);
3412        let (sn, cs) = angle.sin_cos();
3413        let d = [p[0] - o[0], p[1] - o[1]];
3414        [cs * d[0] + sn * d[1], -sn * d[0] + cs * d[1]]
3415    };
3416    // Edges: outward normals and offsets in the start frame.
3417    let edges: Vec<([f64; 2], f64)> = (0..n)
3418        .map(|k| {
3419            let (a, b) = (corners[k], corners[(k + 1) % n]);
3420            let d = [b[0] - a[0], b[1] - a[1]];
3421            let length = d[0].hypot(d[1]);
3422            let normal = [d[1] / length, -d[0] / length];
3423            (normal, normal[0] * a[0] + normal[1] * a[1])
3424        })
3425        .collect();
3426    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);
3427    // Is p covered at some time? The least signed distance over the motion.
3428    let depth = |p: [f64; 2]| -> f64 {
3429        let samples = 2000;
3430        let f = |s: f64| inside(local(s, p));
3431        let mut best = (f64::INFINITY, 0usize);
3432        let values: Vec<f64> = (0..=samples).map(|k| f(k as f64 / samples as f64)).collect();
3433        for (k, &v) in values.iter().enumerate() {
3434            if v < best.0 {
3435                best = (v, k);
3436            }
3437        }
3438        // Refine every local minimum near the least.
3439        let mut least = best.0;
3440        for k in 0..=samples {
3441            let left = if k == 0 { f64::INFINITY } else { values[k - 1] };
3442            let right = if k == samples { f64::INFINITY } else { values[k + 1] };
3443            if values[k] <= left && values[k] <= right && values[k] < best.0 + 1e-3 * scale {
3444                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);
3445                for _ in 0..80 {
3446                    let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
3447                    if f(m1) < f(m2) { hi = m2 } else { lo = m1 }
3448                }
3449                least = least.min(f(0.5 * (lo + hi)));
3450            }
3451        }
3452        least
3453    };
3454    // Candidate boundary paths, each a map [0, 1] -> plane.
3455    #[derive(Clone, Copy)]
3456    enum Path {
3457        Corner(usize),
3458        /// Edge k's grazing point over the times [s0, s1].
3459        Graze(usize, f64, f64),
3460        /// Edge k at the start (false) or end (true).
3461        End(usize, bool),
3462    }
3463    // Where along edge k's line (0 at its start corner, 1 at its end) the
3464    // grazing point is at s, on the edge or beyond it.
3465    let graze_at = |k: usize, s: f64| -> Option<f64> {
3466        // Along edge k at x (in the tool's coordinates) the velocity's part
3467        // along the edge's normal n is w·n + φ' (ẑ × x)·n, w the origin's
3468        // velocity read in the tool's frame.
3469        let (a, b) = (corners[k], corners[(k + 1) % n]);
3470        let (nn, _) = edges[k];
3471        let (velocity, rate) = rates(s);
3472        let (sn, cs) = pose(s).1.sin_cos();
3473        let w = [cs * velocity[0] + sn * velocity[1], -sn * velocity[0] + cs * velocity[1]];
3474        let along = w[0] * nn[0] + w[1] * nn[1];
3475        let rot = |x: [f64; 2]| -x[1] * nn[0] + x[0] * nn[1]; // (ẑ × x)·n
3476        // An edge the origin moves along grazes where (ẑ × x)·n = 0 whatever
3477        // the turning rate (also where it is zero, at an inflection).
3478        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)) };
3479        if ga == gb {
3480            return None;
3481        }
3482        Some(ga / (ga - gb))
3483    };
3484    let graze_point = |k: usize, s: f64| -> Option<f64> { graze_at(k, s).filter(|&u| u > 0.0 && u < 1.0) };
3485    let mut paths: Vec<Path> = (0..n).map(Path::Corner).collect();
3486    // Where a grazing point enters or leaves its edge it is at a corner:
3487    // (that corner, the time), a place its path is split at.
3488    let mut junctions: Vec<(usize, f64)> = Vec::new();
3489    for k in 0..n {
3490        // Where along the motion edge k has a grazing point inside it, each
3491        // run's ends found where the point passes a corner.
3492        let steps = 2000;
3493        let mut run: Option<f64> = None;
3494        let mut passes = |inside: f64, outside: f64| -> f64 {
3495            let (mut a, mut b) = (inside, outside);
3496            for _ in 0..80 {
3497                let mid = 0.5 * (a + b);
3498                if graze_point(k, mid).is_some() { a = mid } else { b = mid }
3499            }
3500            let corner = if graze_at(k, a).is_some_and(|u| u < 0.5) { k } else { (k + 1) % n };
3501            junctions.push((corner, a));
3502            a
3503        };
3504        for j in 0..=steps {
3505            let s = j as f64 / steps as f64;
3506            let on = graze_point(k, s).is_some();
3507            match (on, run) {
3508                (true, None) => run = Some(if j == 0 { s } else { passes(s, s - 1.0 / steps as f64) }),
3509                (false, Some(s0)) => {
3510                    paths.push(Path::Graze(k, s0, passes(s - 1.0 / steps as f64, s)));
3511                    run = None;
3512                }
3513                _ => {}
3514            }
3515        }
3516        if let Some(s0) = run {
3517            paths.push(Path::Graze(k, s0, 1.0));
3518        }
3519        if !closed {
3520            paths.push(Path::End(k, false));
3521            paths.push(Path::End(k, true));
3522        }
3523    }
3524    let eval = |path: Path, t: f64| -> [f64; 2] {
3525        match path {
3526            Path::Corner(k) => place(t, corners[k]),
3527            Path::Graze(k, s0, s1) => {
3528                let s = s0 + (s1 - s0) * t;
3529                let u = graze_at(k, s).map_or(0.5, |u| u.clamp(0.0, 1.0));
3530                let (a, b) = (corners[k], corners[(k + 1) % n]);
3531                place(s, [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u])
3532            }
3533            Path::End(k, at_end) => {
3534                let (a, b) = (corners[k], corners[(k + 1) % n]);
3535                place(if at_end { 1.0 } else { 0.0 }, [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t])
3536            }
3537        }
3538    };
3539    // Split parameters: mutual crossings (polyline, then Newton), and each
3540    // path's ends lying on another.
3541    let m = 400;
3542    let polylines: Vec<Vec<[f64; 2]>> = paths.iter().map(|&p| (0..=m).map(|i| eval(p, i as f64 / m as f64)).collect()).collect();
3543    let mut cuts: Vec<Vec<f64>> = vec![vec![0.0, 1.0]; paths.len()];
3544    let tol = 1e-10 * scale;
3545    for a in 0..paths.len() {
3546        for b in a..paths.len() {
3547            for i in 0..m {
3548                for j in 0..m {
3549                    // A path against itself: only where it crosses over
3550                    // (stretches apart along it; a closed path's ends are
3551                    // neighbours too).
3552                    if a == b && (j < i + 3 || (closed && i < 3 && j + 3 > m)) {
3553                        continue;
3554                    }
3555                    let (p0, p1, q0, q1) = (polylines[a][i], polylines[a][i + 1], polylines[b][j], polylines[b][j + 1]);
3556                    let d1 = [p1[0] - p0[0], p1[1] - p0[1]];
3557                    let d2 = [q1[0] - q0[0], q1[1] - q0[1]];
3558                    let det = d1[0] * d2[1] - d1[1] * d2[0];
3559                    if det.abs() < 1e-300 {
3560                        continue;
3561                    }
3562                    let r = [q0[0] - p0[0], q0[1] - p0[1]];
3563                    let (x, y) = ((r[0] * d2[1] - r[1] * d2[0]) / det, (r[0] * d1[1] - r[1] * d1[0]) / det);
3564                    if !(-1e-9..=1.0 + 1e-9).contains(&x) || !(-1e-9..=1.0 + 1e-9).contains(&y) {
3565                        continue;
3566                    }
3567                    // Newton on the exact paths.
3568                    let (mut ta, mut tb) = ((i as f64 + x) / m as f64, (j as f64 + y) / m as f64);
3569                    for _ in 0..50 {
3570                        let (pa, pb) = (eval(paths[a], ta), eval(paths[b], tb));
3571                        let h = 1e-7;
3572                        let da = { let q = eval(paths[a], (ta + h).min(1.0)); let p = eval(paths[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] };
3573                        let db = { let q = eval(paths[b], (tb + h).min(1.0)); let p = eval(paths[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] };
3574                        let f = [pa[0] - pb[0], pa[1] - pb[1]];
3575                        let det = -da[0] * db[1] + da[1] * db[0];
3576                        if det.abs() < 1e-300 {
3577                            break;
3578                        }
3579                        let dta = (-f[0] * db[1] + f[1] * db[0]) / det;
3580                        let dtb = (da[0] * f[1] - da[1] * f[0]) / det;
3581                        ta = (ta - dta).clamp(0.0, 1.0);
3582                        tb = (tb - dtb).clamp(0.0, 1.0);
3583                        if dta.abs() + dtb.abs() < 1e-15 {
3584                            break;
3585                        }
3586                    }
3587                    let (pa, pb) = (eval(paths[a], ta), eval(paths[b], tb));
3588                    if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < tol && !(a == b && (ta - tb).abs() < 1.0 / m as f64) {
3589                        cuts[a].push(ta);
3590                        cuts[b].push(tb);
3591                    }
3592                }
3593            }
3594        }
3595    }
3596    // A corner's path is its own time: split it where a grazing point passes it.
3597    for &(corner, s) in &junctions {
3598        cuts[corner].push(s);
3599    }
3600    for c in &mut cuts {
3601        c.sort_by(|x, y| x.total_cmp(y));
3602        c.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
3603    }
3604    // Pieces on the boundary: covered on exactly one side.
3605    struct Piece {
3606        path: usize,
3607        t0: f64,
3608        t1: f64,
3609    }
3610    let eps = 1e-7 * scale;
3611    let mut pieces: Vec<Piece> = Vec::new();
3612    for (index, c) in cuts.iter().enumerate() {
3613        for w in c.windows(2) {
3614            let (t0, t1) = (w[0], w[1]);
3615            if t1 - t0 < 1e-9 {
3616                continue;
3617            }
3618            let (pa, pb) = (eval(paths[index], t0), eval(paths[index], t1));
3619            if (pa[0] - pb[0]).hypot(pa[1] - pb[1]) < 1e-9 * scale {
3620                continue;
3621            }
3622            let tm = 0.5 * (t0 + t1);
3623            let (p, q) = (eval(paths[index], tm), eval(paths[index], (tm + 1e-6).min(1.0)));
3624            let d = [q[0] - p[0], q[1] - p[1]];
3625            let length = d[0].hypot(d[1]);
3626            if length == 0.0 {
3627                continue;
3628            }
3629            let left = [p[0] - d[1] / length * eps, p[1] + d[0] / length * eps];
3630            let right = [p[0] + d[1] / length * eps, p[1] - d[0] / length * eps];
3631            let (l, r) = (depth(left) < -1e-12 * scale, depth(right) < -1e-12 * scale);
3632            match (l, r) {
3633                (true, false) => pieces.push(Piece { path: index, t0, t1 }),
3634                (false, true) => pieces.push(Piece { path: index, t0: t1, t1: t0 }),
3635                _ => {}
3636            }
3637        }
3638    }
3639    // Chain into loops, the region on their left (the outer one runs
3640    // counter-clockwise, a hole's clockwise).
3641    if pieces.is_empty() {
3642        return Err(refuse("prism_along", "no boundary found".into()));
3643    }
3644    let mut used = vec![false; pieces.len()];
3645    let mut loops: Vec<Vec<usize>> = Vec::new();
3646    while let Some(first) = (0..pieces.len()).find(|&k| !used[k]) {
3647        let mut order = vec![first];
3648        used[first] = true;
3649        loop {
3650            let last = &pieces[*order.last().expect("order")];
3651            let end = eval(paths[last.path], last.t1);
3652            let start = eval(paths[pieces[order[0]].path], pieces[order[0]].t0);
3653            if (end[0] - start[0]).hypot(end[1] - start[1]) < 1e-8 * scale {
3654                break;
3655            }
3656            let next = (0..pieces.len()).filter(|&k| !used[k]).min_by(|&x, &y| {
3657                let (px, py) = (eval(paths[pieces[x].path], pieces[x].t0), eval(paths[pieces[y].path], pieces[y].t0));
3658                (px[0] - end[0]).hypot(px[1] - end[1]).total_cmp(&(py[0] - end[0]).hypot(py[1] - end[1]))
3659            });
3660            let Some(next) = next else {
3661                return Err(refuse("prism_along", "the boundary does not close".into()));
3662            };
3663            let p = eval(paths[pieces[next].path], pieces[next].t0);
3664            if (p[0] - end[0]).hypot(p[1] - end[1]) > 1e-8 * scale {
3665                return Err(refuse("prism_along", format!("the boundary does not close (gap {:e})", (p[0] - end[0]).hypot(p[1] - end[1]))));
3666            }
3667            used[next] = true;
3668            order.push(next);
3669        }
3670        loops.push(order);
3671    }
3672    // The outer loop first: the one of greatest area.
3673    let area_of = |order: &Vec<usize>| -> f64 {
3674        let mut points: Vec<[f64; 2]> = Vec::new();
3675        for &k in order {
3676            let piece = &pieces[k];
3677            for i in 0..32 {
3678                points.push(eval(paths[piece.path], piece.t0 + (piece.t1 - piece.t0) * i as f64 / 32.0));
3679            }
3680        }
3681        (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
3682    };
3683    let areas: Vec<f64> = loops.iter().map(area_of).collect();
3684    let outer = (0..loops.len()).max_by(|&x, &y| areas[x].abs().total_cmp(&areas[y].abs())).expect("loops");
3685    if areas[outer] <= 0.0 || (0..loops.len()).any(|k| k != outer && areas[k] >= 0.0) {
3686        return Err(refuse("prism_along", "the swept region is not one region with holes".into()));
3687    }
3688    loops.swap(0, outer);
3689    // Plane curves of the loops, then the extrusion.
3690    let world = |q: [f64; 2], h: f64| base.add(e1.scale(q[0])).add(e2.scale(q[1])).add(up.scale(h));
3691    let mut shell = Shell::new();
3692    let mut top_loops = Vec::with_capacity(loops.len());
3693    let mut bottom_loops = Vec::with_capacity(loops.len());
3694    let mut extent: Vec<[f64; 2]> = Vec::new();
3695    for order in &loops {
3696        let mut loop_points: Vec<[f64; 2]> = order.iter().map(|&k| eval(paths[pieces[k].path], pieces[k].t0)).collect();
3697        loop_points.push(loop_points[0]);
3698        let count = order.len();
3699        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();
3700        let mut bottom_e = Vec::with_capacity(count);
3701        let mut top_e = Vec::with_capacity(count);
3702        let mut curves2d = Vec::with_capacity(count);
3703        for (slot, &k) in order.iter().enumerate() {
3704            let piece = &pieces[k];
3705            let straight = matches!(paths[piece.path], Path::End(..));
3706            let next = (slot + 1) % count;
3707            for i in 0..=16 {
3708                extent.push(eval(paths[piece.path], piece.t0 + (piece.t1 - piece.t0) * i as f64 / 16.0));
3709            }
3710            let curve_at = |h: f64| -> Result<NurbsCurve, KernelRefusal> {
3711                if straight {
3712                    return frag(make_line(world(loop_points[slot], h), world(loop_points[next], h)), "line");
3713                }
3714                let samples = 192;
3715                let ts: Vec<f64> = (0..=samples).map(|i| i as f64 / samples as f64).collect();
3716                let mut points: Vec<Vec3> = ts.iter().map(|&t| world(eval(paths[piece.path], piece.t0 + (piece.t1 - piece.t0) * t), h)).collect();
3717                points[0] = world(loop_points[slot], h);
3718                points[samples] = world(loop_points[next], h);
3719                frag(crate::interpolate_curve(&points, 5, &ts), "plane_path")
3720            };
3721            let (cb, ct) = (curve_at(from)?, curve_at(to)?);
3722            bottom_e.push(shell.edge(cb.clone(), bottom_v[slot], bottom_v[next], false)?);
3723            top_e.push(shell.edge(ct.clone(), top_v[slot], top_v[next], false)?);
3724            curves2d.push((cb, ct));
3725        }
3726        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<_, _>>()?;
3727        // Top (outward up) and bottom (outward down) loops.
3728        let mut coedges = Vec::with_capacity(count);
3729        for k in 0..count {
3730            coedges.push((top_e[k], true, plane_pcurve(world([0.0, 0.0], to), e1, e2, &curves2d[k].1, true)?));
3731        }
3732        top_loops.push(coedges);
3733        let mut coedges = Vec::with_capacity(count);
3734        for k in (0..count).rev() {
3735            coedges.push((bottom_e[k], false, plane_pcurve(world([0.0, 0.0], from), e2, e1, &curves2d[k].0, false)?));
3736        }
3737        bottom_loops.push(coedges);
3738        // Sides: the bottom curve extruded (u along it, v up), outward on its right.
3739        for k in 0..count {
3740            let next = (k + 1) % count;
3741            let (cb, _) = &curves2d[k];
3742            let rows: Vec<Vec<Vec4>> = cb
3743                .control_points
3744                .iter()
3745                .map(|p| {
3746                    let x = p.point().expect("point");
3747                    vec![Vec4::from_point(x, p.w), Vec4::from_point(x.add(up.scale(to - from)), p.w)]
3748                })
3749                .collect();
3750            let surface = frag(NurbsSurface::new(cb.degree, 1, cb.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows), "side")?;
3751            let [u0, u1] = frag(cb.domain(), "domain")?;
3752            let coedges = vec![
3753                (bottom_e[k], true, uv_line([u0, 0.0], [u1, 0.0])?),
3754                (verticals[next], true, uv_line([u1, 0.0], [u1, 1.0])?),
3755                (top_e[k], false, uv_line([u1, 1.0], [u0, 1.0])?),
3756                (verticals[k], false, uv_line([u0, 1.0], [u0, 0.0])?),
3757            ];
3758            shell.face(surface, coedges);
3759        }
3760    }
3761    let top_points: Vec<Vec3> = extent.iter().map(|&q| world(q, to)).collect();
3762    shell.face_loops(plane_patch(world([0.0, 0.0], to), e1, e2, &top_points)?, top_loops);
3763    let bottom_points: Vec<Vec3> = extent.iter().map(|&q| world(q, from)).collect();
3764    shell.face_loops(plane_patch(world([0.0, 0.0], from), e2, e1, &bottom_points)?, bottom_loops);
3765    let body = shell.solid();
3766    let issues = body.validate();
3767    if !issues.is_empty() {
3768        return Err(refuse("assembly", format!("the swept prism is not valid: {:?}", issues.first())));
3769    }
3770    Ok(body)
3771}
3772
3773/// A prism whose section is a convex polygon, carried by turns about axes
3774/// all along its own (a planar motion: a planet on its carrier) that ends
3775/// where it starts: its whole sweep (`prism_region_sweep`), or None when the
3776/// tool or motion is not of that kind. `steps`: each turn's axis point,
3777/// direction and rate, applied in order at every t ∈ [t0, t1].
3778#[allow(clippy::too_many_arguments)]
3779pub fn closed_planar_prism(
3780    origin: Vec3,
3781    normal: Vec3,
3782    x_axis: Vec3,
3783    outline: &[OutlinePiece],
3784    from: f64,
3785    to: f64,
3786    steps: &[(Vec3, Vec3, f64, f64)],
3787    t0: f64,
3788    t1: f64,
3789) -> Result<Option<BrepSolid>, KernelRefusal> {
3790    let Ok(up) = normal.normalized() else { return Ok(None) };
3791    let Ok(e1) = x_axis.sub(up.scale(x_axis.dot(up))).normalized() else { return Ok(None) };
3792    let e2 = up.cross(e1);
3793    // A polygon of straight sides, in order.
3794    let mut corners: Vec<[f64; 2]> = Vec::with_capacity(outline.len());
3795    for (k, piece) in outline.iter().enumerate() {
3796        let OutlinePiece::Line { from: a, to: b } = piece else { return Ok(None) };
3797        let OutlinePiece::Line { from: next, .. } = &outline[(k + 1) % outline.len()] else { return Ok(None) };
3798        if (b[0] - next[0]).hypot(b[1] - next[1]) > 1e-9 * (1.0 + b[0].hypot(b[1])) {
3799            return Ok(None);
3800        }
3801        corners.push(*a);
3802    }
3803    if corners.len() < 3 || steps.is_empty() || !(t1 > t0) {
3804        return Ok(None);
3805    }
3806    // Convex (either way round), or it is another engine's.
3807    let turn_of = |k: usize| {
3808        let (a, b, c) = (corners[k], corners[(k + 1) % corners.len()], corners[(k + 2) % corners.len()]);
3809        (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
3810    };
3811    let first_turn = turn_of(0);
3812    if first_turn == 0.0 || (1..corners.len()).any(|k| turn_of(k) * first_turn <= 0.0) {
3813        return Ok(None);
3814    }
3815    // Turns only, about axes along the prism's own: (centre in the plane, rate about +up).
3816    let mut turns: Vec<([f64; 2], f64)> = Vec::with_capacity(steps.len());
3817    for &(point, direction, turn, advance) in steps {
3818        let Ok(axis) = direction.normalized() else { return Ok(None) };
3819        if advance != 0.0 || axis.cross(up).length() > 1e-12 {
3820            return Ok(None);
3821        }
3822        let r = point.sub(origin);
3823        turns.push(([r.dot(e1), r.dot(e2)], turn * axis.dot(up).signum()));
3824    }
3825    let moved = |t: f64, q: [f64; 2]| -> [f64; 2] {
3826        let mut x = q;
3827        for &(c, rate) in &turns {
3828            let (sn, cs) = (rate * t).sin_cos();
3829            let d = [x[0] - c[0], x[1] - c[1]];
3830            x = [c[0] + cs * d[0] - sn * d[1], c[1] + sn * d[0] + cs * d[1]];
3831        }
3832        x
3833    };
3834    let total: f64 = turns.iter().map(|t| t.1).sum();
3835    // The turns compose to one rigid motion of the plane: a point q (where
3836    // it stands before any motion) is at moved(t, 0) + R(total t) q.
3837    let pose = |s: f64| -> ([f64; 2], f64) {
3838        let t = t0 + (t1 - t0) * s;
3839        (moved(t, [0.0, 0.0]), total * t)
3840    };
3841    // The turns are defined at every t, so the origin's velocity is a
3842    // centred difference at the motion's ends too.
3843    let rates = |s: f64| -> ([f64; 2], f64) {
3844        let h = 1e-6;
3845        let (pa, pb) = (pose(s - h).0, pose(s + h).0);
3846        ([(pb[0] - pa[0]) / (2.0 * h), (pb[1] - pa[1]) / (2.0 * h)], total * (t1 - t0))
3847    };
3848    // Ends where it starts: the same turn (mod 2π) and place.
3849    let scale = corners.iter().map(|c| c[0].hypot(c[1])).fold(1.0f64, f64::max);
3850    let closes = corners.iter().all(|&c| {
3851        let (a, b) = (moved(t0, c), moved(t1, c));
3852        (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-9 * scale
3853    });
3854    if !closes {
3855        return Ok(None);
3856    }
3857    prism_region_sweep(&corners, from, to, origin, e1, e2, up, &pose, &rates, true).map(Some)
3858}
3859
3860/// Two turns driven by one parameter t: first by `rates[0]·t` about the
3861/// first axis (point, direction), then by `rates[1]·t` about the second; both
3862/// axes fixed in the world; t from `from` to `to`.
3863#[derive(Clone, Copy, Debug)]
3864pub struct TwoTurns {
3865    pub axes: [(Vec3, Vec3); 2],
3866    pub rates: [f64; 2],
3867    pub from: f64,
3868    pub to: f64,
3869}
3870
3871/// The whole sweep of a solid of revolution tumbled by two turns about skew
3872/// axes. The grazing loop moves on the tool (the instantaneous screw changes
3873/// with t), so the walls are lofted through exact samples. Where the tumble
3874/// passes over a point twice (the one-pass probe), the time is bisected into
3875/// spans each passing once, and the spans' sweeps are joined (consecutive
3876/// spans meet along a grazing loop; distant ones overlap).
3877pub fn sweep_solid_tumbled(tool: &SolidTool, motion: &TwoTurns) -> Result<BrepSolid, KernelRefusal> {
3878    if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
3879        return Err(input("range", "the motion's range must run forward".into()));
3880    }
3881    let mut points = [Vec3::new(0.0, 0.0, 0.0); 2];
3882    let mut directions = [Vec3::new(0.0, 0.0, 1.0); 2];
3883    for k in 0..2 {
3884        points[k] = motion.axes[k].0;
3885        directions[k] = motion.axes[k].1.normalized().map_err(|_| input("axis", "a turn's axis has no direction".into()))?;
3886    }
3887    let turns = Turns { points, directions, rates: motion.rates };
3888    let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else {
3889        return Err(refuse("tumble_tool", "a tumble sweeps a solid of revolution only".into()));
3890    };
3891    let axis = axis_direction.normalized().map_err(|_| input("axis", "the tool's axis has no direction".into()))?;
3892    let base = Screw {
3893        a: points[0],
3894        e: directions[0],
3895        omega: motion.rates[0].abs() + motion.rates[1].abs(),
3896        c: 0.0,
3897        c2: 0.0,
3898        t0: motion.from,
3899        t1: motion.to,
3900        frame: None,
3901        turns: Some(turns),
3902        frozen: None,
3903        loop_samples: LOFT_SAMPLES,
3904        extent: points[1].sub(points[0]).length(),
3905    };
3906    let span = |t0: f64, t1: f64| -> Result<BrepSolid, KernelRefusal> {
3907        let mut screw = base;
3908        screw.t0 = t0;
3909        screw.t1 = t1;
3910        let mut last = None;
3911        // The loop's sampling doubles while the walls' rows miss between
3912        // samples (a thin ring's loop bends sharply before it folds).
3913        'samples: while screw.loop_samples <= 16 * LOFT_SAMPLES {
3914            for k in 0..8 {
3915                let reference = radial.rotate_about(axis, PI * k as f64 / 4.0);
3916                match lofted(&screw, *axis_origin, axis, reference, meridian) {
3917                    // A bulge that crosses a seam high up reads on the next
3918                    // wall as a part held away from its end: other seams too.
3919                    Err(error) if matches!(refused_as(&error), Some("loft_structure") | Some("end_trim_corner") | Some("end_trim_deep")) => last = Some(error),
3920                    Err(error) if refused_as(&error) == Some("loft_rows") => {
3921                        last = Some(error);
3922                        screw.loop_samples *= 2;
3923                        continue 'samples;
3924                    }
3925                    other => return other,
3926                }
3927            }
3928            break;
3929        }
3930        Err(last.expect("tried"))
3931    };
3932    // Bisect where the sweep folds over itself.
3933    let mut pending = vec![(motion.from, motion.to, 0usize)];
3934    let mut spans: Vec<(f64, BrepSolid)> = Vec::new();
3935    while let Some((t0, t1, depth)) = pending.pop() {
3936        match span(t0, t1) {
3937            Ok(body) => spans.push((t0, body)),
3938            Err(error) if refused_as(&error) == Some("folds") && depth < 6 => {
3939                let middle = 0.5 * (t0 + t1);
3940                pending.push((middle, t1, depth + 1));
3941                pending.push((t0, middle, depth + 1));
3942            }
3943            Err(error) => return Err(error),
3944        }
3945    }
3946    spans.sort_by(|a, b| a.0.total_cmp(&b.0));
3947    let mut bodies: Vec<BrepSolid> = spans.into_iter().map(|(_, body)| body).collect();
3948    if bodies.len() == 1 {
3949        return Ok(bodies.pop().expect("one"));
3950    }
3951    crate::boolean_operation_nary(&bodies, crate::BooleanOperation::Union)
3952}
3953
3954/// A cap's pcurve for a lofted edge through the cap's exact chart (the edge
3955/// read back into the tool's frame at the cap's time).
3956fn charted_pcurve(chart: &Chart, screw: &Screw, t: f64, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
3957    let [d0, d1] = frag(curve.domain(), "domain")?;
3958    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
3959    let mut uv = Vec::with_capacity(ts.len());
3960    let mut poles = Vec::with_capacity(ts.len());
3961    for &tt in &ts {
3962        let x = screw.invert(t, frag(curve.evaluate(tt), "point")?);
3963        let [u, v] = chart.invert(x);
3964        uv.push(Vec3::new(u, v, 0.0));
3965        poles.push(chart.at_pole(x));
3966    }
3967    continue_pole_angles(&mut uv, &ts, &poles)?;
3968    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "charted_pcurve")?;
3969    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
3970}
3971
3972/// An edge through its surface's pole (a ball carried square to its own
3973/// axis: every grazing circle runs pole to pole) has no angle there, and the
3974/// inverse returns any. Each sample at a pole (`poles`) takes the first
3975/// parameter its neighbours run to, continued in a line.
3976fn continue_pole_angles(uv: &mut [Vec3], ts: &[f64], poles: &[bool]) -> Result<(), KernelRefusal> {
3977    for j in 0..uv.len() {
3978        if !poles[j] {
3979            continue;
3980        }
3981        let near = if j + 2 < uv.len() && !poles[j + 1] && !poles[j + 2] {
3982            [j + 1, j + 2]
3983        } else if j >= 2 && !poles[j - 1] && !poles[j - 2] {
3984            [j - 1, j - 2]
3985        } else {
3986            return Err(refuse("cap_pole", "a lofted edge stays on its cap's pole".into()));
3987        };
3988        let (a, b) = (uv[near[0]].x, uv[near[1]].x);
3989        uv[j].x = a + (a - b) * (ts[j] - ts[near[0]]) / (ts[near[0]] - ts[near[1]]);
3990    }
3991    Ok(())
3992}
3993
3994/// A cap's pcurve for a lofted edge: its dense image on the cap's surface.
3995fn projected_pcurve(surface: &NurbsSurface, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
3996    let [d0, d1] = frag(curve.domain(), "domain")?;
3997    let ts: Vec<f64> = (0..=PCURVE_SAMPLES).map(|j| d0 + (d1 - d0) * j as f64 / PCURVE_SAMPLES as f64).collect();
3998    let mut uv = Vec::with_capacity(ts.len());
3999    let mut poles = Vec::with_capacity(ts.len());
4000    let [u0, u1] = frag(surface.domain_u(), "domain")?;
4001    let step = 1e-3 * (u1 - u0);
4002    for &t in &ts {
4003        let x = frag(curve.evaluate(t), "point")?;
4004        let foot = frag(crate::project_point_to_surface(surface, x), "project")?;
4005        if foot.distance > 1e-6 * (1.0 + x.length()) {
4006            return Err(refuse("loft_cap", format!("a lofted edge leaves its cap by {} at {x:?}", foot.distance)));
4007        }
4008        uv.push(Vec3::new(foot.u, foot.v, 0.0));
4009        // A pole of the surface: its points do not move with the first
4010        // parameter there.
4011        let aside = if foot.u + step <= u1 { foot.u + step } else { foot.u - step };
4012        let moved = frag(surface.evaluate(aside, foot.v), "point")?.sub(frag(surface.evaluate(foot.u, foot.v), "point")?).length();
4013        poles.push(moved <= 1e-9 * (1.0 + x.length()));
4014    }
4015    continue_pole_angles(&mut uv, &ts, &poles)?;
4016    let fitted = frag(crate::interpolate_curve(&uv, 5, &ts), "projected_pcurve")?;
4017    if forward { Ok(fitted) } else { frag(fitted.reversed(), "reversed") }
4018}
4019
4020type Signature = (Vec<(usize, usize, bool)>, Vec<(bool, Vec<(usize, bool)>)>, Vec<(usize, bool)>);
4021
4022fn signature(split: &Split) -> Result<Signature, KernelRefusal> {
4023    Ok((
4024        split.curves.iter().map(|c| (c.start, c.end, c.degenerate)).collect(),
4025        split.caps.iter().map(|cap| (cap.front, cap.coedges.iter().map(|&(c, f, _)| (c, f)).collect())).collect(),
4026        split.grazing()?,
4027    ))
4028}
4029
4030fn lofted(screw: &Screw, origin: Vec3, axis: Vec3, radial: Vec3, meridian: &[OutlinePiece]) -> Result<BrepSolid, KernelRefusal> {
4031    let split_at = |t: f64| -> Result<Split, KernelRefusal> {
4032        let mut frozen = *screw;
4033        frozen.frozen = Some(t);
4034        split_revolved(&frozen, origin, axis, radial, meridian)
4035    };
4036    let mut lambdas: Vec<f64> = (0..=LOFT_SAMPLES).map(|i| i as f64 / LOFT_SAMPLES as f64).collect();
4037    // World samples of grazing curve c at time t, in the wall's direction.
4038    let samples_of = |split: &Split, c: usize, back_forward: bool, t: f64| -> Result<Vec<Vec3>, KernelRefusal> {
4039        let Some(list) = &split.curves[c].samples else {
4040            return Err(refuse("loft_samples", "a grazing curve has no exact samples to loft".into()));
4041        };
4042        let mut world: Vec<Vec3> = list.iter().map(|&x| screw.apply(t, x)).collect();
4043        if back_forward {
4044            world.reverse();
4045        }
4046        Ok(world)
4047    };
4048    // Time breaks start even and are refined only in the spans whose middle
4049    // misses, by the quintic's h^6 error: a smooth stretch of the motion keeps
4050    // its long spans (doubling everywhere tripled the wall for one bend).
4051    let mut fractions: Vec<f64> = (0..=15).map(|j| j as f64 / 15.0).collect();
4052    loop {
4053        let count = fractions.len() - 1;
4054        // The walls' second parameter runs 0 -> 1 over the motion.
4055        let times: Vec<f64> = fractions.iter().map(|&f| if f == 1.0 { screw.t1 } else { screw.t0 + (screw.t1 - screw.t0) * f }).collect();
4056        let splits: Vec<Split> = times.iter().map(|&t| split_at(t)).collect::<Result<_, _>>()?;
4057        if splits.iter().any(|split| !split.slides.is_empty() || !split.slide_sides.is_empty()) {
4058            return Err(refuse("loft_structure", "a flat end that slides within its own plane is not lofted".into()));
4059        }
4060        let shape = signature(&splits[0])?;
4061        for split in &splits[1..] {
4062            if signature(split)? != shape {
4063                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
4064            }
4065        }
4066        let grazing = shape.2.clone();
4067        if grazing.is_empty() {
4068            return Err(refuse("no_grazing", "the tool has no grazing loop under this motion".into()));
4069        }
4070        let scale = splits[0].scale + screw.extent;
4071        let target = LOFT_TARGET * scale;
4072        // Walls: per grazing curve, rows along it at each time, then across time.
4073        let mut walls = Vec::with_capacity(grazing.len());
4074        // Every wall's exact samples at every time.
4075        let mut sampled: Vec<Vec<Vec<Vec3>>> = Vec::with_capacity(grazing.len());
4076        for &(c, back_forward) in &grazing {
4077            let mut at_times = Vec::with_capacity(times.len());
4078            for (j, split) in splits.iter().enumerate() {
4079                let points = samples_of(split, c, back_forward, times[j])?;
4080                if points.len() != lambdas.len() {
4081                    if points.len() < 13 || points.len() % 2 == 0 {
4082                        return Err(refuse("loft_samples", "a grazing curve's exact samples cannot be lofted".into()));
4083                    }
4084                    lambdas = (0..points.len()).map(|i| i as f64 / (points.len() - 1) as f64).collect();
4085                }
4086                at_times.push(points);
4087            }
4088            sampled.push(at_times);
4089        }
4090        // A row through every `stride`-th sample: its worst miss at the
4091        // samples it leaves out, over every wall and time.
4092        let thinned = |stride: usize| -> Result<f64, KernelRefusal> {
4093            let coarse_lambdas: Vec<f64> = lambdas.iter().step_by(stride).copied().collect();
4094            let mut worst = 0.0f64;
4095            for at_times in &sampled {
4096                for points in at_times {
4097                    let coarse_points: Vec<Vec3> = points.iter().step_by(stride).copied().collect();
4098                    let coarse = frag(crate::interpolate_curve(&coarse_points, 5, &coarse_lambdas), "loft_row")?;
4099                    for (i, x) in points.iter().enumerate().filter(|(i, _)| i % stride != 0) {
4100                        worst = worst.max(frag(coarse.evaluate(lambdas[i]), "loft_row")?.sub(*x).length());
4101                    }
4102                }
4103            }
4104            Ok(worst)
4105        };
4106        // Each wall's rows pass through as few of its samples as hold every
4107        // exact sample within a quarter of the target, at every time (a loop
4108        // smooth but for one sharp bend needs its samples only there, and the
4109        // wall's size is what the solid's users pay for): from every 16th,
4110        // a stretch that misses at a sample it leaves out gets its middle one.
4111        let spans = lambdas.len() - 1;
4112        let mut kept: Vec<Vec<usize>> = Vec::with_capacity(sampled.len());
4113        for at_times in &sampled {
4114            let coarsest = if spans % 16 == 0 && spans >= 96 { 16 } else { 1 };
4115            let mut subset: Vec<usize> = (0..=spans).step_by(coarsest).collect();
4116            loop {
4117                let subset_lambdas: Vec<f64> = subset.iter().map(|&i| lambdas[i]).collect();
4118                let mut misses = vec![0.0f64; subset.len() - 1];
4119                for points in at_times {
4120                    let row_points: Vec<Vec3> = subset.iter().map(|&i| points[i]).collect();
4121                    let row = frag(crate::interpolate_curve(&row_points, 5, &subset_lambdas), "loft_row")?;
4122                    for k in 0..subset.len() - 1 {
4123                        for i in subset[k] + 1..subset[k + 1] {
4124                            misses[k] = misses[k].max(frag(row.evaluate(lambdas[i]), "loft_row")?.sub(points[i]).length());
4125                        }
4126                    }
4127                }
4128                let mut refined = Vec::with_capacity(2 * subset.len());
4129                for k in 0..subset.len() - 1 {
4130                    refined.push(subset[k]);
4131                    if misses[k] > 0.25 * target {
4132                        refined.push((subset[k] + subset[k + 1]) / 2);
4133                    }
4134                }
4135                refined.push(spans);
4136                if refined.len() == subset.len() {
4137                    break;
4138                }
4139                subset = refined;
4140            }
4141            kept.push(subset);
4142        }
4143        // Where a wall keeps neighbouring samples there is none left out
4144        // between them to measure at: a row passes through its samples, and
4145        // between them it is as good as the loop is smooth at that spacing.
4146        // Its miss there is estimated from the rows through every other
4147        // sample, scaled by the quintic's 2^-6.
4148        let dense = kept.iter().any(|subset| subset.windows(2).any(|pair| pair[1] == pair[0] + 1));
4149        let between = if dense { thinned(2)? / 64.0 } else { 0.0 };
4150        for (index, &(c, back_forward)) in grazing.iter().enumerate() {
4151            let row_lambdas: Vec<f64> = kept[index].iter().map(|&i| lambdas[i]).collect();
4152            let mut rows: Vec<NurbsCurve> = Vec::with_capacity(times.len());
4153            for points in &sampled[index] {
4154                let row_points: Vec<Vec3> = kept[index].iter().map(|&i| points[i]).collect();
4155                rows.push(frag(crate::interpolate_curve(&row_points, 5, &row_lambdas), "loft_row")?);
4156            }
4157            let knots_u = rows[0].knots.clone();
4158            let mut net: Vec<Vec<Vec4>> = Vec::with_capacity(rows[0].control_points.len());
4159            let mut knots_v = Vec::new();
4160            for k in 0..rows[0].control_points.len() {
4161                let column: Vec<Vec3> = rows.iter().map(|row| row.control_points[k].point()).collect::<Result<_, _>>().map_err(|e| refuse("loft", e))?;
4162                let across = frag(crate::interpolate_curve(&column, 5, &fractions), "loft_column")?;
4163                knots_v = across.knots.clone();
4164                net.push(across.control_points.clone());
4165            }
4166            let surface = frag(NurbsSurface::new(5, 5, knots_u, knots_v, net), "loft_wall")?;
4167            walls.push((c, back_forward, surface, rows.first().cloned().expect("rows"), rows.last().cloned().expect("rows")));
4168        }
4169        if between > target {
4170            return Err(refuse("loft_rows", format!("the lofted wall's rows stay about {between:e} off the grazing loop between its samples")));
4171        }
4172        // Against the exact loop in the middle of each span, every sample.
4173        let mut misses = vec![0.0f64; count];
4174        for j in 0..count {
4175            let t = 0.5 * (times[j] + times[j + 1]);
4176            let fraction = 0.5 * (fractions[j] + fractions[j + 1]);
4177            let split = split_at(t)?;
4178            if signature(&split)? != shape {
4179                return Err(refuse("loft_structure", "the grazing loop changes its structure along the curve".into()));
4180            }
4181            for (c, back_forward, surface, _, _) in &walls {
4182                let exact = samples_of(&split, *c, *back_forward, t)?;
4183                for (i, x) in exact.iter().enumerate() {
4184                    misses[j] = misses[j].max(frag(surface.evaluate(lambdas[i], fraction), "loft_check")?.sub(*x).length());
4185                }
4186            }
4187        }
4188        let worst = misses.iter().copied().fold(0.0f64, f64::max);
4189        if worst > target {
4190            if count > 2000 {
4191                return Err(refuse("loft_accuracy", format!("the lofted wall stays {worst:e} off the grazing loop")));
4192            }
4193            // A span missing by more than half the target is cut into
4194            // ceil((e / (target / 4))^(1/6)) pieces; the rest stay.
4195            let mut refined = Vec::with_capacity(2 * fractions.len());
4196            for j in 0..count {
4197                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 };
4198                for k in 0..pieces {
4199                    refined.push(fractions[j] + (fractions[j + 1] - fractions[j]) * k as f64 / pieces as f64);
4200                }
4201            }
4202            refined.push(1.0);
4203            fractions = refined;
4204            continue;
4205        }
4206        // Each K corner's path through the sample times.
4207        let mut paths: HashMap<usize, Vec<Vec3>> = HashMap::new();
4208        for &(c, _) in &grazing {
4209            for r in [splits[0].curves[c].start, splits[0].curves[c].end] {
4210                paths.entry(r).or_insert_with(|| splits.iter().zip(&times).map(|(split, &t)| screw.apply(t, split.points[r])).collect());
4211            }
4212        }
4213        return assemble_lofted(screw, &splits[0], &splits[count], &walls, &fractions, &paths, target);
4214    }
4215}
4216
4217/// Refuse a lofted wall with an edge of regression: across one the wall's
4218/// normal turns over, and the band beside it lies inside nearby poses (the
4219/// sweep folds within a few degrees of the motion, which no probe walk is
4220/// dense enough to be sure of seeing). Normals are compared between
4221/// neighbours on every time row and between rows, outside what the end trims
4222/// take away (`removed`, chart rings) and a few columns off its edge (a fold
4223/// line meets the end at the cut's own ends). `fit`: how near the wall keeps
4224/// to its exact loop (a length).
4225fn wall_regular(surface: &NurbsSurface, fractions: &[f64], removed: &[&[[f64; 2]]], fit: f64) -> Result<(), KernelRefusal> {
4226    const COLUMNS: usize = 4 * LOFT_SAMPLES;
4227    let mut rows: Vec<f64> = Vec::with_capacity(2 * fractions.len());
4228    for j in 0..fractions.len() {
4229        rows.push(fractions[j]);
4230        if j + 1 < fractions.len() {
4231            rows.push(0.5 * (fractions[j] + fractions[j + 1]));
4232        }
4233    }
4234    let normal = |u: f64, v: f64| -> Result<Option<Vec3>, KernelRefusal> {
4235        let h = 1e-6;
4236        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));
4237        let du = frag(surface.evaluate(ub, v), "regular")?.sub(frag(surface.evaluate(ua, v), "regular")?).scale(1.0 / (ub - ua));
4238        let dv = frag(surface.evaluate(u, vb), "regular")?.sub(frag(surface.evaluate(u, va), "regular")?).scale(1.0 / (vb - va));
4239        // Where the wall's two directions all but line up, or it is no
4240        // wider than its own fit's ripple (a corner it pinches to), it has
4241        // no normal to speak of: the fit's noise would turn it.
4242        let cross = du.cross(dv);
4243        if cross.length() <= 1e-6 * du.length() * dv.length() || du.length().min(dv.length()) <= 1e3 * fit {
4244            return Ok(None);
4245        }
4246        Ok(cross.normalized().ok())
4247    };
4248    let mut previous: Option<Vec<Option<Vec3>>> = None;
4249    for &v in &rows {
4250        // What a trim takes away is not part of the body.
4251        let row: Vec<Option<Vec3>> = (0..=COLUMNS)
4252            .map(|i| {
4253                let u = i as f64 / COLUMNS as f64;
4254                if removed.iter().any(|ring| inside_ring(ring, [u, v]) || near_ring(ring, [u, v], 4.0 / COLUMNS as f64)) { Ok(None) } else { normal(u, v) }
4255            })
4256            .collect::<Result<_, _>>()?;
4257        for i in 0..COLUMNS {
4258            if let (Some(a), Some(b)) = (row[i], row[i + 1]) {
4259                if a.dot(b) < -0.5 {
4260                    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)));
4261                }
4262            }
4263            if let Some(Some(Some(a))) = previous.as_ref().map(|p| p.get(i).copied()) {
4264                if let Some(b) = row[i] {
4265                    if a.dot(b) < -0.5 {
4266                        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)));
4267                    }
4268                }
4269            }
4270        }
4271        previous = Some(row);
4272    }
4273    Ok(())
4274}
4275
4276/// A stretch of a wall's row at v, from u = a to u = b, as an edge's curve.
4277fn row_piece(wall: &NurbsSurface, v: f64, a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
4278    let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
4279    let along: Vec<Vec3> = ts.iter().map(|&s| frag(wall.evaluate((a + (b - a) * s).clamp(0.0, 1.0), v), "wall")).collect::<Result<_, _>>()?;
4280    frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
4281}
4282
4283/// A wall's end row in pieces around its trims and breaks (one more than the
4284/// spans), at v.
4285fn row_pieces(wall: &NurbsSurface, v: f64, spans: &[TrimSpan]) -> Result<Vec<NurbsCurve>, KernelRefusal> {
4286    let mut pieces = Vec::with_capacity(spans.len() + 1);
4287    let mut from = 0.0;
4288    for span in spans {
4289        pieces.push(row_piece(wall, v, from, span.lambdas[0])?);
4290        from = span.lambdas[1];
4291    }
4292    pieces.push(row_piece(wall, v, from, 1.0)?);
4293    Ok(pieces)
4294}
4295
4296/// The wall over u ∈ [a, b] only, in the same parameters.
4297fn restrict_u(surface: &NurbsSurface, a: f64, b: f64) -> Result<NurbsSurface, KernelRefusal> {
4298    let [u0, u1] = frag(surface.domain_u(), "domain")?;
4299    if a <= u0 + 1e-12 && b >= u1 - 1e-12 {
4300        return Ok(surface.clone());
4301    }
4302    let columns = surface.control_points[0].len();
4303    let mut knots = Vec::new();
4304    let mut net: Vec<Vec<Vec4>> = Vec::new();
4305    for j in 0..columns {
4306        let line: Vec<Vec4> = surface.control_points.iter().map(|row| row[j]).collect();
4307        let mut curve = frag(NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), line), "restrict")?;
4308        if b < u1 - 1e-12 {
4309            curve = frag(curve.split(b), "restrict")?.0;
4310        }
4311        if a > u0 + 1e-12 {
4312            curve = frag(curve.split(a), "restrict")?.1;
4313        }
4314        if j == 0 {
4315            knots = curve.knots.clone();
4316            net = vec![Vec::with_capacity(columns); curve.control_points.len()];
4317        }
4318        for (i, point) in curve.control_points.iter().enumerate() {
4319            net[i].push(*point);
4320        }
4321    }
4322    frag(NurbsSurface::new(surface.degree_u, surface.degree_v, knots, surface.knots_v.clone(), net), "restrict")
4323}
4324
4325/// One place a wall is cut back where an end pose bulges past it: the wall
4326/// parameter range [λa, λb] along the grazing loop where the trim leaves and
4327/// rejoins it, the cut (from the point at λa to the point at λb, on both the
4328/// wall and the pose), the wall's side of the trim from λa to λb (`chain`),
4329/// the double curve and its swallowtail point if the trim follows one, and
4330/// the part of the wall's chart it takes away (`removed`, (u, v) points
4331/// around it).
4332struct TrimSpan {
4333    lambdas: [f64; 2],
4334    points: [Vec3; 2],
4335    /// None: no cut at all, only a break in the end's row at λa = λb (where
4336    /// a line splitting the wall lands on it).
4337    cut: Option<NurbsCurve>,
4338    chain: Vec<(TrimPiece, bool, NurbsCurve)>,
4339    slot: Option<(NurbsCurve, Vec3)>,
4340    /// The swallowtail's point in the wall's chart (u, v), where the trim
4341    /// follows a double curve.
4342    tip: Option<[f64; 2]>,
4343    removed: Vec<[f64; 2]>,
4344}
4345
4346/// Every place an end pose bulges past one wall, in order along the loop, and
4347/// the loop's pieces around them (one more than the spans).
4348struct EndTrim {
4349    spans: Vec<TrimSpan>,
4350    pieces: Vec<NurbsCurve>,
4351}
4352
4353/// Which edge a piece of a trimmed wall's end runs on: the cut it shares with
4354/// the cap, or the wall's own double curve (both of the slot's sides).
4355#[derive(Clone, Copy, PartialEq, Eq, Debug)]
4356enum TrimPiece {
4357    Cut,
4358    Slot,
4359}
4360
4361/// The cut of a lofted wall (u along the grazing loop, v the motion's time
4362/// fraction) by the pose at its end (`end` 0: v = 0, 1: v = 1), if the pose
4363/// bulges past it, else None.
4364///
4365/// The wall meets the pose along K and leaves it to second order (K grazes),
4366/// so with ε the time fraction from the end, f = d / ε² (d the pose's signed
4367/// distance) is smooth up to the end. The part of the wall inside the pose is
4368/// where f < 0; its boundary is traced as the curve f = 0 from the end and back
4369/// to it. It need not be a graph over u: a tongue of it may run on past where
4370/// it left the end.
4371///
4372/// `fit`: how near the wall keeps to the exact loop (a length).
4373fn end_trim(screw: &Screw, split: &Split, t: f64, wall: &NurbsSurface, end: usize, fit: f64) -> Result<Option<EndTrim>, KernelRefusal> {
4374    let v_of = |e: f64| if end == 1 { 1.0 - e } else { e };
4375    let at = |u: f64, e: f64| -> Result<Vec3, KernelRefusal> { frag(wall.evaluate(u.clamp(0.0, 1.0), v_of(e)), "wall") };
4376    let f = |u: f64, e: f64| -> Result<f64, KernelRefusal> { Ok(split.distance(screw.invert(t, at(u, e)?)) / (e * e)) };
4377    // Below `floor` the walls' fit swamps d / ε².
4378    let floor = 1e-3;
4379    // How far into the motion (as a fraction of it) a trim may reach (a fold
4380    // band can run most of a span); past that the end pose meets a distant
4381    // part of the sweep (`end_trim_deep`).
4382    let window = 0.6;
4383    let noise = 2.0 * fit / (floor * floor);
4384    // Where the wall dips into the pose just off the end.
4385    let n = 2000;
4386    let edge: Vec<f64> = (0..=n).map(|i| f(i as f64 / n as f64, floor)).collect::<Result<_, _>>()?;
4387    // Inside: the stretches where f is negative, those that dip below the
4388    // fit's noise somewhere (a stretch that never does is the fit's own).
4389    let mut inside: Vec<bool> = edge.iter().map(|&x| x < 0.0).collect();
4390    let mut i = 0;
4391    while i <= n {
4392        if !inside[i] {
4393            i += 1;
4394            continue;
4395        }
4396        let mut j = i;
4397        while j < n && inside[j + 1] {
4398            j += 1;
4399        }
4400        if edge[i..=j].iter().all(|&x| x >= -noise) {
4401            for flag in &mut inside[i..=j] {
4402                *flag = false;
4403            }
4404        }
4405        i = j + 1;
4406    }
4407    if !inside.iter().any(|&x| x) {
4408        // Nothing near the end; a pocket deeper in is caught below.
4409        return pierced(&f, floor, window, noise, &[]);
4410    }
4411    if inside[0] || inside[n] || inside[1] || inside[n - 1] {
4412        return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
4413    }
4414    // Crossings of the floor line, by bisection between samples of either sign.
4415    let mut crossings: Vec<f64> = Vec::new();
4416    for i in 0..n {
4417        if inside[i] != inside[i + 1] {
4418            let (mut a, mut b) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
4419            let a_inside = inside[i];
4420            for _ in 0..60 {
4421                let mid = 0.5 * (a + b);
4422                if (f(mid, floor)? < 0.0) == a_inside { a = mid } else { b = mid }
4423            }
4424            crossings.push(0.5 * (a + b));
4425        }
4426    }
4427    if crossings.len() % 2 != 0 || crossings.is_empty() {
4428        return Err(refuse("end_trim", "an end pose's bulges past a wall do not pair up".into()));
4429    }
4430    // Trace f = 0 from the first crossing of each pair into the wall until it
4431    // returns to the floor; it must come back at the pair's other crossing.
4432    let gradient = |u: f64, e: f64| -> Result<[f64; 2], KernelRefusal> {
4433        let h = 1e-6;
4434        Ok([(f(u + h, e)? - f(u - h, e)?) / (2.0 * h), (f(u, e + h)? - f(u, e - h)?) / (2.0 * h)])
4435    };
4436    let settle = |mut p: [f64; 2]| -> Result<[f64; 2], KernelRefusal> {
4437        for _ in 0..30 {
4438            let value = f(p[0], p[1])?;
4439            let g = gradient(p[0], p[1])?;
4440            let norm = g[0] * g[0] + g[1] * g[1];
4441            if norm == 0.0 {
4442                return Err(refuse("end_trim", "the cut of an end pose has a flat point".into()));
4443            }
4444            p = [p[0] - value * g[0] / norm, p[1] - value * g[1] / norm];
4445            if value.abs() * p[1] * p[1] < 1e-14 * split.scale {
4446                break;
4447            }
4448        }
4449        Ok(p)
4450    };
4451    let step = 1e-3;
4452    let mut cuts: Vec<Vec<[f64; 2]>> = Vec::new();
4453    // Each cut starts at the lowest crossing not yet used and ends at the
4454    // unused one it comes back to.
4455    let mut unused: Vec<f64> = crossings.clone();
4456    while !unused.is_empty() {
4457        let start = unused.remove(0);
4458        let mut points: Vec<[f64; 2]> = vec![[start, floor]];
4459        let mut heading = [0.0, 1.0];
4460        loop {
4461            let last = *points.last().expect("points");
4462            let g = gradient(last[0], last[1])?;
4463            let length = g[0].hypot(g[1]);
4464            let mut tangent = [-g[1] / length, g[0] / length];
4465            if tangent[0] * heading[0] + tangent[1] * heading[1] < 0.0 {
4466                tangent = [-tangent[0], -tangent[1]];
4467            }
4468            let next = settle([last[0] + step * tangent[0], last[1] + step * tangent[1]])?;
4469            if next[1] < floor {
4470                break;
4471            }
4472            if next[0] <= 1e-3 || next[0] >= 1.0 - 1e-3 {
4473                return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
4474            }
4475            if next[1] > window {
4476                return Err(refuse("end_trim_deep", "an end pose holds a deep part of a wall".into()));
4477            }
4478            if points.len() > 20_000 {
4479                return Err(refuse("end_trim", "the cut of an end pose does not close".into()));
4480            }
4481            heading = [next[0] - last[0], next[1] - last[1]];
4482            points.push(next);
4483        }
4484        let back = *points.last().expect("points");
4485        let Some(at_end) = unused.iter().position(|&c| (back[0] - c).abs() <= 2.0 * step) else {
4486            return Err(refuse("end_trim", "the cut of an end pose does not come back where it should".into()));
4487        };
4488        let back_at = unused.remove(at_end);
4489        // A dip that never rises off the floor and comes straight back is
4490        // the fit's noise at the end, not a bulge.
4491        if points.len() == 1 && (back_at - start).abs() <= step {
4492            continue;
4493        }
4494        points.push([back_at, floor]);
4495        // Down to the end itself along the cut's direction at the floor (taken
4496        // from the first point clearly above it).
4497        let to_end = |p: [f64; 2], rest: &[[f64; 2]], reversed: bool| -> Result<[f64; 2], KernelRefusal> {
4498            // Along the cut's own tangent there (across the gradient of f), so
4499            // the run to the end continues it smoothly.
4500            let g = gradient(p[0], p[1])?;
4501            if g[0].abs() > 1e-3 * g[1].abs() {
4502                return Ok([p[0] + g[1] / g[0] * p[1], 0.0]);
4503            }
4504            let clear = |q: &&[f64; 2]| q[1] - p[1] > 0.25 * step;
4505            let found = if reversed { rest.iter().rev().find(clear) } else { rest.iter().find(clear) };
4506            Ok(match found {
4507                Some(q) => [p[0] - (q[0] - p[0]) / (q[1] - p[1]) * p[1], 0.0],
4508                None => [p[0], 0.0],
4509            })
4510        };
4511        let count = points.len();
4512        let (first, last) = (to_end(points[0], &points[1..], false)?, to_end(points[count - 1], &points[..count - 1], true)?);
4513        if [first[0], last[0]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
4514            return Err(refuse("end_trim_corner", "an end pose bulges past a wall across a corner of its grazing loop".into()));
4515        }
4516        points.insert(0, first);
4517        points.push(last);
4518        if points[0][0] > points[points.len() - 1][0] {
4519            points.reverse();
4520        }
4521        cuts.push(points);
4522    }
4523    let rings: Vec<&[[f64; 2]]> = cuts.iter().map(|c| c.as_slice()).collect();
4524    pierced(&f, floor, window, noise, &rings)?;
4525    let chart = |p: [f64; 2]| [p[0], v_of(p[1])];
4526    // A curve on the wall through chart points and its pcurve, both on the
4527    // given parameters (normalized to [0, 1]); chart-length parameters by
4528    // default (the wall's own speed collapses near an edge of regression, so
4529    // 3D chord lengths would bunch them).
4530    let chart_lengths = |chart_points: &[[f64; 2]]| -> Vec<f64> {
4531        let mut params = vec![0.0];
4532        for k in 1..chart_points.len() {
4533            let gap = (chart_points[k][0] - chart_points[k - 1][0]).hypot(chart_points[k][1] - chart_points[k - 1][1]);
4534            params.push(params[k - 1] + gap.max(1e-15));
4535        }
4536        params
4537    };
4538    // Returns the curve, its pcurve, and how far the pcurve's image strays
4539    // from the curve between the points.
4540    let curve_through = |chart_points: &[[f64; 2]], params: &[f64], what: &'static str| -> Result<(NurbsCurve, NurbsCurve, f64), KernelRefusal> {
4541        let total = *params.last().expect("params");
4542        let params: Vec<f64> = params.iter().map(|x| x / total).collect();
4543        let world: Vec<Vec3> = chart_points.iter().map(|p| at(p[0], p[1])).collect::<Result<_, _>>()?;
4544        let uv: Vec<Vec3> = chart_points.iter().map(|p| Vec3::new(p[0], v_of(p[1]), 0.0)).collect();
4545        let (curve, pcurve) = (frag(crate::interpolate_curve(&world, 5, &params), what)?, frag(crate::interpolate_curve(&uv, 5, &params), what)?);
4546        // Between the points too: the pcurve's image stays on the curve.
4547        let mut worst = 0.0f64;
4548        for k in 0..params.len() - 1 {
4549            let s = 0.5 * (params[k] + params[k + 1]);
4550            let q = frag(pcurve.evaluate(s), "pcurve")?;
4551            let e = if end == 1 { 1.0 - q.y } else { q.y };
4552            worst = worst.max(at(q.x, e)?.sub(frag(curve.evaluate(s), "curve")?).length());
4553        }
4554        Ok((curve, pcurve, worst))
4555    };
4556    // A trim curve is refined until its pcurve's image is within `fine` of
4557    // it, and taken as near as it gets if within `loose` (a double curve has
4558    // a cusp at its swallowtail's point, where no finer trace helps; a
4559    // tighter bar costs a thin tool many rounds and buys no reader anything).
4560    let (fine, loose) = (1e-7 * split.scale, 1e-7 * split.scale);
4561    let missed = |what: &str| refuse("end_trim", format!("the {what}'s pcurve leaves it between its points however finely it is traced"));
4562    // The cut, refined where its fit misses: a settled point between each
4563    // pair of traced ones (on the stretches run straight to the end, their
4564    // middles).
4565    let cut_through = |mut chart_points: Vec<[f64; 2]>| -> Result<(NurbsCurve, NurbsCurve), KernelRefusal> {
4566        let mut best: Option<(NurbsCurve, NurbsCurve, f64)> = None;
4567        for _ in 0..7 {
4568            let fitted = curve_through(&chart_points, &chart_lengths(&chart_points), "cut")?;
4569            let done = fitted.2 <= fine;
4570            if best.as_ref().map_or(true, |b| fitted.2 < b.2) {
4571                best = Some(fitted);
4572            }
4573            if done {
4574                break;
4575            }
4576            let mut finer = Vec::with_capacity(2 * chart_points.len());
4577            for k in 0..chart_points.len() - 1 {
4578                finer.push(chart_points[k]);
4579                let (p, q) = (chart_points[k], chart_points[k + 1]);
4580                let middle = [0.5 * (p[0] + q[0]), 0.5 * (p[1] + q[1])];
4581                // Below the floor the cut runs straight to the end: split it there as a line.
4582                finer.push(if p[1] >= floor && q[1] >= floor { settle(middle)? } else { middle });
4583            }
4584            finer.push(chart_points[chart_points.len() - 1]);
4585            chart_points = finer;
4586        }
4587        match best {
4588            Some((curve, pcurve, worst)) if worst <= loose => Ok((curve, pcurve)),
4589            _ => Err(missed("cut")),
4590        }
4591    };
4592    let piece = |a: f64, b: f64| -> Result<NurbsCurve, KernelRefusal> {
4593        let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
4594        let along: Vec<Vec3> = ts.iter().map(|&s| at(a + (b - a) * s, 0.0)).collect::<Result<_, _>>()?;
4595        frag(crate::interpolate_curve(&along, 5, &ts), "loop_piece")
4596    };
4597    // Where the wall turns over near the end (a swallowtail), the cut passes
4598    // through a point of the end's own loop K a second time, on the wall's far
4599    // sheet: there the wall's double curve starts, and the trim follows it to
4600    // the swallowtail's point and back instead of the cut's first stretch.
4601    let span_of = |points: &Vec<[f64; 2]>| -> Result<TrimSpan, KernelRefusal> {
4602        if let Some((k, ua, b)) = double_start(&at, points, floor)? {
4603            // The double curve, traced more finely while its fit misses.
4604            let mut traced: Option<(Vec<[f64; 2]>, Vec<[f64; 2]>, NurbsCurve, NurbsCurve, NurbsCurve, f64)> = None;
4605            for round in 0..5 {
4606                let (a_side, b_side) = double_curve(&at, [ua, 0.0], b, window, 2e-3 / f64::from(1u32 << round))?;
4607                // Both sides on the continuation's own arc length, so the double
4608                // curve and its two pcurves share one parameter.
4609                let mut sigma = vec![0.0];
4610                for k in 1..a_side.len() {
4611                    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]));
4612                    sigma.push(sigma[k - 1] + step.max(1e-15));
4613                }
4614                let ((slot, pa, miss_a), (_, pb, miss_b)) = (curve_through(&a_side, &sigma, "double_curve")?, curve_through(&b_side, &sigma, "double_curve")?);
4615                let worst = miss_a.max(miss_b);
4616                if traced.as_ref().map_or(true, |t| worst < t.5) {
4617                    traced = Some((a_side, b_side, slot, pa, pb, worst));
4618                }
4619                if worst <= fine {
4620                    break;
4621                }
4622            }
4623            let Some((a_side, b_side, slot, pa, pb, _)) = traced.filter(|t| t.5 <= loose) else { return Err(missed("double curve")) };
4624            // The cut keeps the stretch from the far sheet's point to its end away
4625            // from where the double curve leaves K.
4626            let low = ua < points[0][0];
4627            if !low && ua <= points[points.len() - 1][0] {
4628                return Err(refuse("end_trim", "the double curve of a wall leaves its end inside the cut".into()));
4629            }
4630            let mut kept: Vec<[f64; 2]> = if low { points[k..].to_vec() } else { points[..=k].to_vec() };
4631            if low { kept[0] = b } else { *kept.last_mut().expect("kept") = b }
4632            let (cut, cut_pcurve) = cut_through(kept.clone())?;
4633            let tip = at(a_side[a_side.len() - 1][0], a_side[a_side.len() - 1][1])?;
4634            // The wall's side of the trim from the low end to the high one.
4635            let chain = if low {
4636                vec![(TrimPiece::Slot, true, pa), (TrimPiece::Slot, false, frag(pb.reversed(), "reversed")?), (TrimPiece::Cut, true, cut_pcurve)]
4637            } else {
4638                vec![(TrimPiece::Cut, true, cut_pcurve), (TrimPiece::Slot, true, pb), (TrimPiece::Slot, false, frag(pa.reversed(), "reversed")?)]
4639            };
4640            let lambdas = if low { [ua, points[points.len() - 1][0]] } else { [points[0][0], ua] };
4641            let mut removed: Vec<[f64; 2]> = Vec::new();
4642            if low {
4643                removed.extend(a_side.iter().map(|&p| chart(p)));
4644                removed.extend(b_side.iter().rev().map(|&p| chart(p)));
4645                removed.extend(kept.iter().map(|&p| chart(p)));
4646            } else {
4647                removed.extend(kept.iter().map(|&p| chart(p)));
4648                removed.extend(b_side.iter().map(|&p| chart(p)));
4649                removed.extend(a_side.iter().rev().map(|&p| chart(p)));
4650            }
4651            // Everything the end pose holds must be in what goes.
4652            let dropped: Vec<[f64; 2]> = if low { points[..k].to_vec() } else { points[k + 1..].to_vec() };
4653            for p in dropped.iter().filter(|p| p[1] > 2.0 * floor && (p[0] - b[0]).hypot(p[1] - b[1]) > 5e-3) {
4654                if !inside_ring(&removed, chart(*p)) {
4655                    return Err(refuse("end_trim", "the cut of an end pose leaves the part of the wall its double curve takes away".into()));
4656                }
4657            }
4658            let points3 = [at(lambdas[0], 0.0)?, at(lambdas[1], 0.0)?];
4659            // The double curve's sides part about its end: one keeps to
4660            // each side of the swallowtail's point along the loop, so a
4661            // line through that point splits the wall between them.
4662            let tip_chart = chart(a_side[a_side.len() - 1]);
4663            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)));
4664            let ((a_lo, a_hi), (b_lo, b_hi)) = (side(&a_side), side(&b_side));
4665            let parted = (a_lo >= -1e-9 && b_hi <= 1e-9) || (a_hi <= 1e-9 && b_lo >= -1e-9);
4666            if !parted {
4667                return Err(refuse("end_trim", "the two sides of a wall's double curve do not keep to either side of its end".into()));
4668            }
4669            return Ok(TrimSpan { lambdas, points: points3, cut: Some(cut), chain, slot: Some((slot, tip)), tip: Some(tip_chart), removed });
4670        }
4671        let (cut, wall_pcurve) = cut_through(points.clone())?;
4672        let (la, lb) = (points[0][0], points[points.len() - 1][0]);
4673        let removed: Vec<[f64; 2]> = points.iter().map(|&p| chart(p)).collect();
4674        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 })
4675    };
4676    if cuts.is_empty() {
4677        return pierced(&f, floor, window, noise, &[]);
4678    }
4679    let mut spans = Vec::with_capacity(cuts.len());
4680    for points in &cuts {
4681        spans.push(span_of(points)?);
4682    }
4683    spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
4684    // A trim wholly inside what another takes away adds nothing (a bulge of
4685    // the end pose inside a swallowtail's slot).
4686    let edge_row = v_of(0.0);
4687    let within = |inner: &TrimSpan, outer: &TrimSpan| -> bool {
4688        inner.lambdas[0] >= outer.lambdas[0]
4689            && inner.lambdas[1] <= outer.lambdas[1]
4690            && 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))
4691    };
4692    let mut k = 0;
4693    while k < spans.len() {
4694        if (0..spans.len()).any(|j| j != k && within(&spans[k], &spans[j])) {
4695            spans.remove(k);
4696        } else {
4697            k += 1;
4698        }
4699    }
4700    for pair in spans.windows(2) {
4701        if pair[0].lambdas[1] >= pair[1].lambdas[0] {
4702            return Err(refuse("end_trim", "an end pose's trims of a wall overlap".into()));
4703        }
4704    }
4705    let mut pieces = Vec::with_capacity(spans.len() + 1);
4706    let mut from = 0.0;
4707    for span in &spans {
4708        pieces.push(piece(from, span.lambdas[0])?);
4709        from = span.lambdas[1];
4710    }
4711    pieces.push(piece(from, 1.0)?);
4712    Ok(Some(EndTrim { spans, pieces }))
4713}
4714
4715
4716
4717/// Is q within `reach` of the closed polygon `ring`'s sides?
4718fn near_ring(ring: &[[f64; 2]], q: [f64; 2], reach: f64) -> bool {
4719    (0..ring.len()).any(|k| {
4720        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
4721        let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
4722        let length = dx * dx + dy * dy;
4723        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 };
4724        (q[0] - a[0] - s * dx).hypot(q[1] - a[1] - s * dy) < reach
4725    })
4726}
4727
4728/// Is q inside the closed polygon `ring` (its last point joins its first)?
4729fn inside_ring(ring: &[[f64; 2]], q: [f64; 2]) -> bool {
4730    let mut crossings = 0;
4731    for k in 0..ring.len() {
4732        let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
4733        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]) {
4734            crossings += 1;
4735        }
4736    }
4737    crossings % 2 == 1
4738}
4739
4740/// The point of an end pose's cut (chart points (u, ε), ε the time fraction
4741/// from the end) that lies on the end's own loop K a second time, away from
4742/// the cut's ends: (its index along the cut, the loop parameter u of the point
4743/// of K it meets, and the refined (u, ε) on the cut), if there is one.
4744fn double_start(at: &dyn Fn(f64, f64) -> Result<Vec3, KernelRefusal>, points: &[[f64; 2]], floor: f64) -> Result<Option<(usize, f64, [f64; 2])>, KernelRefusal> {
4745    let n = 4000;
4746    let row: Vec<Vec3> = (0..=n).map(|i| at(i as f64 / n as f64, 0.0)).collect::<Result<_, _>>()?;
4747    let scale = row.iter().fold(0.0f64, |m, p| m.max(p.sub(row[0]).length())).max(1e-300);
4748    let mut best: Option<(f64, usize, usize)> = None;
4749    for (k, p) in points.iter().enumerate() {
4750        if p[1] < 4.0 * floor {
4751            continue;
4752        }
4753        let x = at(p[0], p[1])?;
4754        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 });
4755        // The cut nears K at its own ends in proportion to ε; the second
4756        // meeting is where that ratio drops to nothing.
4757        if best.map_or(true, |b| d / p[1] < b.0 / points[b.1][1]) {
4758            best = Some((d, k, i));
4759        }
4760    }
4761    let Some((distance, k, i)) = best else { return Ok(None) };
4762    // Coarse: the cut's points are a few thousandths of the chart apart.
4763    if distance > 5e-3 * scale {
4764        return Ok(None);
4765    }
4766    // Newton on at(b) = at(u, 0) for (b_u, b_ε, u).
4767    let mut x = [points[k][0], points[k][1], i as f64 / n as f64];
4768    let h = 1e-7;
4769    for _ in 0..40 {
4770        let g = at(x[0], x[1])?.sub(at(x[2], 0.0)?);
4771        if g.length() < 1e-13 * scale {
4772            // Not the trivial meeting of the end row with itself.
4773            if x[1] < 2.0 * floor || !(0.0..=1.0).contains(&x[0]) || !(0.0..=1.0).contains(&x[2]) {
4774                return Ok(None);
4775            }
4776            return Ok(Some((k, x[2], [x[0], x[1]])));
4777        }
4778        let c0 = at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h);
4779        let c1 = at(x[0], x[1] + h)?.sub(at(x[0], x[1] - h)?).scale(0.5 / h);
4780        let c2 = at(x[2] + h, 0.0)?.sub(at(x[2] - h, 0.0)?).scale(-0.5 / h);
4781        let det = c0.dot(c1.cross(c2));
4782        if det.abs() < 1e-300 {
4783            break;
4784        }
4785        // Cramer's rule for [c0 c1 c2] d = -g.
4786        let r = g.scale(-1.0);
4787        let d = [r.dot(c1.cross(c2)) / det, c0.dot(r.cross(c2)) / det, c0.dot(c1.cross(r)) / det];
4788        x = [x[0] + d[0], x[1] + d[1], x[2] + d[2]];
4789    }
4790    if distance < 1e-6 * scale {
4791        return Err(refuse("end_trim", "an end pose's cut meets its own loop, but not exactly enough to follow".into()));
4792    }
4793    Ok(None)
4794}
4795
4796/// The double curve of a wall from where it leaves the end (a, on the end's
4797/// loop) and its partner b on the far sheet, traced by continuation of
4798/// at(a) = at(b) in (u, ε) for both, to the swallowtail point where the two
4799/// sides meet. Returns both sides' chart points, ending at the same point.
4800fn 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> {
4801    let h = 1e-7;
4802    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);
4803    let jacobian = |x: [f64; 4]| -> Result<[Vec3; 4], KernelRefusal> {
4804        Ok([
4805            at(x[0] + h, x[1])?.sub(at(x[0] - h, x[1])?).scale(0.5 / h),
4806            at(x[0], x[1] + h)?.sub(at(x[0], (x[1] - h).max(0.0))?).scale(1.0 / (h + x[1].min(h))),
4807            at(x[2] + h, x[3])?.sub(at(x[2] - h, x[3])?).scale(-0.5 / h),
4808            at(x[2], x[3] + h)?.sub(at(x[2], (x[3] - h).max(0.0))?).scale(-1.0 / (h + x[3].min(h))),
4809        ])
4810    };
4811    let residual = |x: [f64; 4]| -> Result<Vec3, KernelRefusal> { Ok(at(x[0], x[1])?.sub(at(x[2], x[3])?)) };
4812    // The null direction of the 3x4 Jacobian: its signed 3x3 minors.
4813    let null = |j: &[Vec3; 4]| -> [f64; 4] {
4814        let minor = |p: usize, q: usize, r: usize| j[p].dot(j[q].cross(j[r]));
4815        let n = [minor(1, 2, 3), -minor(0, 2, 3), minor(0, 1, 3), -minor(0, 1, 2)];
4816        let length = n.iter().map(|x| x * x).sum::<f64>().sqrt().max(1e-300);
4817        [n[0] / length, n[1] / length, n[2] / length, n[3] / length]
4818    };
4819    // Minimum-norm Newton back onto at(a) = at(b).
4820    let correct = |mut x: [f64; 4]| -> Result<Option<[f64; 4]>, KernelRefusal> {
4821        for _ in 0..30 {
4822            let g = residual(x)?;
4823            if g.length() < 1e-13 * scale {
4824                return Ok(Some(x));
4825            }
4826            let j = jacobian(x)?;
4827            // J Jᵀ y = -g, step = Jᵀ y.
4828            let mut m = [[0.0; 3]; 3];
4829            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]];
4830            for p in 0..3 {
4831                for q in 0..3 {
4832                    m[p][q] = (0..4).map(|c| rows[p][c] * rows[q][c]).sum();
4833                }
4834            }
4835            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]);
4836            if det.abs() < 1e-300 {
4837                return Ok(None);
4838            }
4839            let r = [-g.x, -g.y, -g.z];
4840            let solve = |col: usize| -> f64 {
4841                let mut a = m;
4842                for p in 0..3 {
4843                    a[p][col] = r[p];
4844                }
4845                (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
4846            };
4847            let y = [solve(0), solve(1), solve(2)];
4848            for c in 0..4 {
4849                x[c] += (0..3).map(|p| rows[p][c] * y[p]).sum::<f64>();
4850            }
4851        }
4852        Ok(None)
4853    };
4854    let mut x = [a[0], a[1], b[0], b[1]];
4855    let mut a_side = vec![a];
4856    let mut b_side = vec![b];
4857    let mut heading: Option<[f64; 4]> = None;
4858    loop {
4859        let separation = (x[0] - x[2]).hypot(x[1] - x[3]);
4860        if separation < 3.0 * step && a_side.len() > 2 {
4861            let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
4862            a_side.push(tip);
4863            b_side.push(tip);
4864            return Ok((a_side, b_side));
4865        }
4866        let mut t = null(&jacobian(x)?);
4867        let reference = heading.unwrap_or([0.0, 1.0, 0.0, 0.0]);
4868        if (0..4).map(|c| t[c] * reference[c]).sum::<f64>() < 0.0 {
4869            t = [-t[0], -t[1], -t[2], -t[3]];
4870        }
4871        let mut next = None;
4872        let mut length = step;
4873        for _ in 0..6 {
4874            let guess = [x[0] + length * t[0], x[1] + length * t[1], x[2] + length * t[2], x[3] + length * t[3]];
4875            if let Some(y) = correct(guess)? {
4876                next = Some(y);
4877                break;
4878            }
4879            length *= 0.5;
4880        }
4881        let Some(y) = next else {
4882            // Near the swallowtail's point the two sheets turn tangent and
4883            // Newton gives out; close there if the sides are that near.
4884            if separation < 2e-2 && a_side.len() > 2 {
4885                let tip = [0.5 * (x[0] + x[2]), 0.5 * (x[1] + x[3])];
4886                a_side.push(tip);
4887                b_side.push(tip);
4888                return Ok((a_side, b_side));
4889            }
4890            return Err(refuse("end_trim", format!("the double curve of a wall cannot be followed (sides {separation:e} apart)")));
4891        };
4892        if [y[0], y[2]].iter().any(|&u| u <= 1e-3 || u >= 1.0 - 1e-3) {
4893            return Err(refuse("end_trim_corner", "the double curve of a wall reaches a corner of its grazing loop".into()));
4894        }
4895        if y[1] > window || y[3] > window || y[1] < 0.0 || y[3] < 0.0 {
4896            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())));
4897        }
4898        if a_side.len() > 20_000 {
4899            return Err(refuse("end_trim", "the double curve of a wall does not close".into()));
4900        }
4901        heading = Some([y[0] - x[0], y[1] - x[1], y[2] - x[2], y[3] - x[3]]);
4902        x = y;
4903        a_side.push([x[0], x[1]]);
4904        b_side.push([x[2], x[3]]);
4905    }
4906}
4907
4908/// Refuse a wall the end pose holds a part of that no cut encloses: a pocket
4909/// of the wall inside the pose away from the end.
4910fn pierced(
4911    f: &dyn Fn(f64, f64) -> Result<f64, KernelRefusal>,
4912    floor: f64,
4913    window: f64,
4914    noise: f64,
4915    cuts: &[&[[f64; 2]]],
4916) -> Result<Option<EndTrim>, KernelRefusal> {
4917    let enclosed = |q: [f64; 2]| -> bool { cuts.iter().any(|ring| inside_ring(ring, q)) };
4918    for i in 1..200 {
4919        for j in 1..=40 {
4920            let (u, e) = (i as f64 / 200.0, floor + (window - floor) * (j as f64 / 40.0).powi(2));
4921            // d itself against the fit's noise: f grows as 1 / ε² near the end.
4922            if f(u, e)? * e * e < -noise * floor * floor && !enclosed([u, e]) {
4923                return Err(refuse("end_trim_deep", "an end pose holds a part of a wall away from its end".into()));
4924            }
4925        }
4926    }
4927    Ok(None)
4928}
4929
4930#[allow(clippy::too_many_arguments)]
4931fn assemble_lofted(
4932    screw: &Screw,
4933    first: &Split,
4934    last: &Split,
4935    walls: &[(usize, bool, NurbsSurface, NurbsCurve, NurbsCurve)],
4936    times: &[f64],
4937    paths: &HashMap<usize, Vec<Vec3>>,
4938    fit: f64,
4939) -> Result<BrepSolid, KernelRefusal> {
4940    let mut shell = Shell::new();
4941    let ends = [(first, screw.t0), (last, screw.t1)];
4942    // Where an end pose bulges past a wall near its grazing loop (a saddle side
4943    // curving past the wall it touches), cut the wall back to where it
4944    // re-enters the pose and carry the end cap across the loop to there.
4945    let mut trims: HashMap<(usize, usize), EndTrim> = HashMap::new();
4946    // Walls split into strips along lines through their swallowtails' points.
4947    let mut split_walls: std::collections::HashSet<usize> = std::collections::HashSet::new();
4948    for (index, (_, _, surface, _, _)) in walls.iter().enumerate() {
4949        for end in 0..2 {
4950            if let Some(trim) = end_trim(screw, ends[end].0, ends[end].1, surface, end, fit)? {
4951                trims.insert((index, end), trim);
4952            }
4953        }
4954        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();
4955        wall_regular(surface, times, &removed, fit)?;
4956        // A trim along a double curve has that curve as one edge on both its
4957        // sides: on one face its two uses could not be told apart from its
4958        // 3D curve alone (the wall passes through it twice). The wall is split
4959        // along the parameter line from each swallowtail's point to the far
4960        // end's row, which that row is broken at.
4961        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() };
4962        let (tips0, tips1) = (tips_at(0), tips_at(1));
4963        if !tips0.is_empty() && !tips1.is_empty() {
4964            return Err(refuse("wall_split", "a wall turns over near both its ends".into()));
4965        }
4966        let (far, tips) = if tips0.is_empty() { (0usize, tips1) } else { (1usize, tips0) };
4967        // A straight split line serves only where the trimmed row keeps to
4968        // its own side of it: all that comes before the swallowtail's point
4969        // along the row at or below its u, all after at or above. (A cut
4970        // that bulges across it would be crossed by the line; such a wall
4971        // stays one face.)
4972        let straight = |trim: &EndTrim| -> Result<bool, KernelRefusal> {
4973            for (k, span) in trim.spans.iter().enumerate() {
4974                let Some(tip) = span.tip else { continue };
4975                let first_slot = span.chain.iter().position(|piece| piece.0 == TrimPiece::Slot).unwrap_or(0);
4976                for (j, other) in trim.spans.iter().enumerate() {
4977                    for (n, (_, _, pcurve)) in other.chain.iter().enumerate() {
4978                        let before = j < k || (j == k && n <= first_slot);
4979                        let [d0, d1] = frag(pcurve.domain(), "domain")?;
4980                        for i in 0..=32 {
4981                            let u = frag(pcurve.evaluate(d0 + (d1 - d0) * i as f64 / 32.0), "pcurve")?.x;
4982                            if (before && u > tip[0] + 1e-9) || (!before && u < tip[0] - 1e-9) {
4983                                return Ok(false);
4984                            }
4985                        }
4986                    }
4987                }
4988            }
4989            Ok(true)
4990        };
4991        let split_here = !tips.is_empty() && trims.get(&(index, 1 - far)).map(straight).transpose()?.unwrap_or(false);
4992        if split_here {
4993            split_walls.insert(index);
4994            let v_far = far as f64;
4995            let mut spans = trims.remove(&(index, far)).map(|trim| trim.spans).unwrap_or_default();
4996            for tip in &tips {
4997                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 {
4998                    return Err(refuse("wall_split", "a wall's split line lands in a trim of its far end".into()));
4999                }
5000                let point = frag(surface.evaluate(tip[0], v_far), "wall")?;
5001                spans.push(TrimSpan { lambdas: [tip[0], tip[0]], points: [point, point], cut: None, chain: Vec::new(), slot: None, tip: None, removed: Vec::new() });
5002            }
5003            spans.sort_by(|a, b| a.lambdas[0].total_cmp(&b.lambdas[0]));
5004            let pieces = row_pieces(surface, v_far, &spans)?;
5005            trims.insert((index, far), EndTrim { spans, pieces });
5006        }
5007    }
5008    let mut vertex_at: HashMap<(usize, usize), u64> = HashMap::new();
5009    let mut vertex = |shell: &mut Shell, end: usize, p: usize| -> u64 {
5010        *vertex_at.entry((end, p)).or_insert_with(|| shell.vertex(screw.apply(ends[end].1, ends[end].0.points[p])))
5011    };
5012    let grazing: HashMap<usize, usize> = walls.iter().enumerate().map(|(index, w)| (w.0, index)).collect();
5013    // Edges at each end: K curves from the walls' end rows (in the tool
5014    // curve's direction), the rest the end split's own curves moved.
5015    let mut edge_at: HashMap<(usize, usize), u64> = HashMap::new();
5016    let mut edge_curve: HashMap<(usize, usize), NurbsCurve> = HashMap::new();
5017    // Per trimmed wall end: the loop's piece edges, and each span's cut and
5018    // double-curve edges (u64::MAX where a span has none).
5019    let mut trim_edges: HashMap<(usize, usize), (Vec<u64>, Vec<[u64; 2]>)> = HashMap::new();
5020    // Per trimmed wall end and span: the vertex at its low end, and at the
5021    // swallowtail's point where it has one.
5022    let mut trim_vertices: HashMap<(usize, usize), Vec<(u64, Option<u64>)>> = HashMap::new();
5023    for end in 0..2 {
5024        let (split, t) = ends[end];
5025        for (c, tool_curve) in split.curves.iter().enumerate() {
5026            let used = split.caps.iter().any(|cap| cap.front == (end == 1) && cap.coedges.iter().any(|e| e.0 == c));
5027            if !used {
5028                continue;
5029            }
5030            if let Some(&index) = grazing.get(&c) {
5031                if let Some(trim) = trims.get(&(index, end)) {
5032                    // Pieces in the wall's direction: K up to the cut, the cut, K after it.
5033                    let back_forward = walls[index].1;
5034                    let (from, to) = if back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
5035                    let (vf, vt) = (vertex(&mut shell, end, from), vertex(&mut shell, end, to));
5036                    let mut piece_edges = Vec::with_capacity(trim.pieces.len());
5037                    let mut span_edges = Vec::with_capacity(trim.spans.len());
5038                    let mut start = vf;
5039                    let mut span_vertices = Vec::with_capacity(trim.spans.len());
5040                    for (span, piece) in trim.spans.iter().zip(&trim.pieces) {
5041                        let va = shell.vertex(span.points[0]);
5042                        piece_edges.push(shell.edge(piece.clone(), start, va, false)?);
5043                        let Some(cut_curve) = &span.cut else {
5044                            // A break only: the row goes on from the same vertex.
5045                            span_edges.push([u64::MAX, u64::MAX]);
5046                            span_vertices.push((va, None));
5047                            start = va;
5048                            continue;
5049                        };
5050                        let vb = shell.vertex(span.points[1]);
5051                        let cut = shell.edge(cut_curve.clone(), va, vb, false)?;
5052                        // The double curve runs from where it leaves K (at
5053                        // the low end of the span if its chain starts with
5054                        // it) to the swallowtail's point.
5055                        let (slot, tip_vertex) = match &span.slot {
5056                            Some((curve, tip)) => {
5057                                let from = if span.chain[0].0 == TrimPiece::Slot { va } else { vb };
5058                                let tip = shell.vertex(*tip);
5059                                (shell.edge(curve.clone(), from, tip, false)?, Some(tip))
5060                            }
5061                            None => (u64::MAX, None),
5062                        };
5063                        span_edges.push([cut, slot]);
5064                        span_vertices.push((va, tip_vertex));
5065                        start = vb;
5066                    }
5067                    trim_vertices.insert((index, end), span_vertices);
5068                    piece_edges.push(shell.edge(trim.pieces[trim.pieces.len() - 1].clone(), start, vt, false)?);
5069                    trim_edges.insert((index, end), (piece_edges, span_edges));
5070                    continue;
5071                }
5072            }
5073            let curve = match grazing.get(&c) {
5074                Some(&index) => {
5075                    let (_, back_forward, _, row0, row1) = &walls[index];
5076                    let row = if end == 0 { row0 } else { row1 };
5077                    if *back_forward { frag(row.reversed(), "reversed")? } else { row.clone() }
5078                }
5079                None => screw.move_curve(t, &tool_curve.curve)?,
5080            };
5081            let (a, b) = (vertex(&mut shell, end, tool_curve.start), vertex(&mut shell, end, tool_curve.end));
5082            let edge = shell.edge(curve.clone(), a, b, tool_curve.degenerate)?;
5083            edge_at.insert((end, c), edge);
5084            edge_curve.insert((end, c), curve);
5085        }
5086    }
5087    for end in 0..2 {
5088        let (split, t) = ends[end];
5089        for cap in split.caps.iter().filter(|cap| cap.front == (end == 1)) {
5090            let surface = screw.move_surface(t, &cap.surface)?;
5091            let mut coedges = Vec::with_capacity(cap.coedges.len());
5092            for (c, forward, pcurve) in &cap.coedges {
5093                if let Some(&index) = grazing.get(c) {
5094                    if let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) {
5095                        let Some(chart) = cap.chart.as_ref() else {
5096                            return Err(refuse("end_trim", "an end pose bulges past a wall beside a cap without a chart".into()));
5097                        };
5098                        // The cap runs the tool's curve forward or back; the
5099                        // pieces run the wall's way: loop piece, cut, loop
5100                        // piece, ... loop piece.
5101                        let along = *forward != walls[index].1;
5102                        let mut pieces: Vec<(u64, &NurbsCurve)> = Vec::with_capacity(2 * trim.pieces.len());
5103                        for (k, piece) in trim.pieces.iter().enumerate() {
5104                            pieces.push((piece_edges[k], piece));
5105                            if let Some(cut) = trim.spans.get(k).and_then(|span| span.cut.as_ref()) {
5106                                pieces.push((span_edges[k][0], cut));
5107                            }
5108                        }
5109                        if !along {
5110                            pieces.reverse();
5111                        }
5112                        for (edge, curve) in pieces {
5113                            coedges.push((edge, along, charted_pcurve(chart, screw, t, curve, along)?));
5114                        }
5115                        continue;
5116                    }
5117                }
5118                let pcurve = if grazing.contains_key(c) && cap.chart.is_some() {
5119                    charted_pcurve(cap.chart.as_ref().expect("chart"), screw, t, &edge_curve[&(end, *c)], *forward)?
5120                } else if grazing.contains_key(c) {
5121                    match projected_pcurve(&surface, &edge_curve[&(end, *c)], *forward) {
5122                        Ok(p) => p,
5123                        Err(error) => {
5124                            // Which: the exact samples themselves, or the row between them?
5125                            let samples = split.curves[*c].samples.as_ref().map(|list| {
5126                                list.iter()
5127                                    .map(|&x| crate::project_point_to_surface(&surface, screw.apply(t, x)).map(|f| f.distance).unwrap_or(f64::NAN))
5128                                    .fold(0.0f64, f64::max)
5129                            });
5130                            let line = split.curves[*c].curve.degree;
5131                            return Err(KernelRefusal::unsupported(
5132                                KernelStage::Classify,
5133                                "loft_cap",
5134                                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),
5135                            ));
5136                        }
5137                    }
5138                } else {
5139                    pcurve.clone()
5140                };
5141                coedges.push((edge_at[&(end, *c)], *forward, pcurve));
5142            }
5143            shell.face(surface, coedges);
5144        }
5145    }
5146    // Orbits of K's corners: interpolated through the sample times as the
5147    // walls' end columns are.
5148    let mut orbits: HashMap<usize, u64> = HashMap::new();
5149    let mut keys: Vec<usize> = paths.keys().copied().collect();
5150    keys.sort_unstable();
5151    for r in keys {
5152        let curve = frag(crate::interpolate_curve(&paths[&r], 5, times), "orbit")?;
5153        let (a, b) = (vertex(&mut shell, 0, r), vertex(&mut shell, 1, r));
5154        orbits.insert(r, shell.edge(curve, a, b, false)?);
5155    }
5156    // One piece of a wall's end row in the direction of u: (edge, traversed
5157    // forward?, pcurve that way), and where a split line meets the row right
5158    // after it: (u, v, vertex).
5159    type RowPiece = (u64, bool, NurbsCurve, Option<(f64, f64, u64)>);
5160    for (index, (c, back_forward, surface, _, _)) in walls.iter().enumerate() {
5161        let tool_curve = &first.curves[*c];
5162        let (from, to) = if *back_forward { (tool_curve.end, tool_curve.start) } else { (tool_curve.start, tool_curve.end) };
5163        let row = |end: usize| -> Result<Vec<RowPiece>, KernelRefusal> {
5164            let v = end as f64;
5165            let (Some(trim), Some((piece_edges, span_edges))) = (trims.get(&(index, end)), trim_edges.get(&(index, end))) else {
5166                return Ok(vec![(edge_at[&(end, *c)], !*back_forward, uv_line([0.0, v], [1.0, v])?, None)]);
5167            };
5168            let vertices = &trim_vertices[&(index, end)];
5169            let mut list: Vec<RowPiece> = Vec::new();
5170            let mut at = 0.0;
5171            for (k, span) in trim.spans.iter().enumerate() {
5172                let broken = if span.cut.is_none() { Some((span.lambdas[0], v, vertices[k].0)) } else { None };
5173                list.push((piece_edges[k], true, uv_line([at, v], [span.lambdas[0], v])?, broken));
5174                for (n, (piece, forward, pcurve)) in span.chain.iter().enumerate() {
5175                    let edge = if *piece == TrimPiece::Cut { span_edges[k][0] } else { span_edges[k][1] };
5176                    // The swallowtail's point lies between the double curve's two uses.
5177                    let between = *piece == TrimPiece::Slot && span.chain.get(n + 1).is_some_and(|next| next.0 == TrimPiece::Slot);
5178                    let tip = match (span.tip, vertices[k].1) {
5179                        (Some(tip), Some(vertex)) if between && split_walls.contains(&index) => Some((tip[0], tip[1], vertex)),
5180                        _ => None,
5181                    };
5182                    list.push((edge, *forward, pcurve.clone(), tip));
5183                }
5184                at = span.lambdas[1];
5185            }
5186            list.push((piece_edges[trim.spans.len()], true, uv_line([at, v], [1.0, v])?, None));
5187            Ok(list)
5188        };
5189        let (bottom, top) = (row(0)?, row(1)?);
5190        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());
5191        if low.len() != high.len() || low.iter().zip(&high).any(|(a, b)| (a.0 - b.0).abs() > 1e-9) {
5192            return Err(refuse("wall_split", "a wall's split lines do not run from one end's row to the other's".into()));
5193        }
5194        // The split lines, each from its lower point to its upper.
5195        let mut lines: Vec<(u64, f64, f64, f64)> = Vec::with_capacity(low.len());
5196        for (below, above) in low.iter().zip(&high) {
5197            let ts: Vec<f64> = (0..=128).map(|j| j as f64 / 128.0).collect();
5198            let along: Vec<Vec3> = ts.iter().map(|&s| frag(surface.evaluate(below.0, below.1 + (above.1 - below.1) * s), "wall")).collect::<Result<_, _>>()?;
5199            let edge = shell.edge(frag(crate::interpolate_curve(&along, 5, &ts), "split_line")?, below.2, above.2, false)?;
5200            lines.push((edge, below.0, below.1, above.1));
5201        }
5202        // Each row in the stretches between the split lines.
5203        let stretches = |list: Vec<RowPiece>| -> Vec<Vec<(u64, bool, NurbsCurve)>> {
5204            let mut out = vec![Vec::new()];
5205            for (edge, forward, pcurve, cut) in list {
5206                out.last_mut().expect("stretch").push((edge, forward, pcurve));
5207                if cut.is_some() {
5208                    out.push(Vec::new());
5209                }
5210            }
5211            out
5212        };
5213        let (bottoms, tops) = (stretches(bottom), stretches(top));
5214        // A strip between two split lines (or the wall's sides): along the
5215        // start row, up its far side, back along the end row, down its near
5216        // side; on the wall over its own stretch of u only.
5217        for j in 0..=lines.len() {
5218            let mut coedges = bottoms[j].clone();
5219            match lines.get(j) {
5220                Some(&(edge, u, v0, v1)) => coedges.push((edge, true, uv_line([u, v0], [u, v1])?)),
5221                None => coedges.push((orbits[&to], true, uv_line([1.0, 0.0], [1.0, 1.0])?)),
5222            }
5223            for (edge, forward, pcurve) in tops[j].iter().rev() {
5224                coedges.push((*edge, !*forward, frag(pcurve.reversed(), "reversed")?));
5225            }
5226            match j.checked_sub(1).map(|k| lines[k]) {
5227                Some((edge, u, v0, v1)) => coedges.push((edge, false, uv_line([u, v1], [u, v0])?)),
5228                None => coedges.push((orbits[&from], false, uv_line([0.0, 1.0], [0.0, 0.0])?)),
5229            }
5230            let (ua, ub) = (if j == 0 { 0.0 } else { lines[j - 1].1 }, lines.get(j).map_or(1.0, |line| line.1));
5231            shell.face(restrict_u(surface, ua, ub)?, coedges);
5232        }
5233    }
5234    let body = shell.solid();
5235    let issues = body.validate();
5236    if !issues.is_empty() {
5237        // Name the faces whose coedges stray: their pcurves' ends on the surface
5238        // against their edges' ends.
5239        let mut notes = Vec::new();
5240        for face in body.shells.iter().flat_map(|s| &s.faces) {
5241            for coedge in &face.loops[0].coedges {
5242                let edge = body.edges.iter().find(|e| e.id == coedge.edge_id).expect("edge");
5243                let [p0, p1] = frag(coedge.pcurve.domain(), "domain")?;
5244                let a = frag(coedge.pcurve.evaluate(p0), "uv")?;
5245                let on = frag(face.surface.evaluate_extended(a.x, a.y), "on")?;
5246                let at = frag(edge.curve.evaluate(if coedge.forward { edge.t0 } else { edge.t1 }), "at")?;
5247                if on.sub(at).length() > 1e-6 {
5248                    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));
5249                }
5250                let _ = p1;
5251            }
5252        }
5253        return Err(refuse("assembly", format!("the lofted sweep is not valid: {:?}; {}", issues.first(), notes.iter().take(4).cloned().collect::<Vec<_>>().join("; "))));
5254    }
5255    check_single_pass(screw, first, &body, &std::collections::HashSet::new())?;
5256    Ok(body)
5257}
5258
5259/// Is the world point y inside the moving tool at some time of the motion?
5260/// Steps t by the distance over a bound on the speed of any tool point near y.
5261fn covered(screw: &Screw, split: &Split, y: Vec3, margin: f64) -> Result<bool, KernelRefusal> {
5262    let reach = y.sub(screw.a).length() + split.scale + screw.extent;
5263    let speed = (screw.omega.abs() * reach + screw.rate_bound()).max(1e-300);
5264    let floor = (screw.t1 - screw.t0) * 1e-7;
5265    let mut t = screw.t0;
5266    let mut steps = 0usize;
5267    loop {
5268        let d = split.distance(screw.invert(t, y));
5269        if d < -margin {
5270            return Ok(true);
5271        }
5272        if t >= screw.t1 {
5273            return Ok(false);
5274        }
5275        if steps > 2_000_000 {
5276            return Err(refuse("probe_budget", "the one-pass check could not walk the motion past a point near the sweep".into()));
5277        }
5278        t = (t + ((d.abs() + margin) / speed).max(floor)).min(screw.t1);
5279        steps += 1;
5280    }
5281}
5282
5283/// Refuse a sweep that covers points just outside its own faces.
5284///
5285/// `sliding`: faces the tool slides within all through the motion. A probe
5286/// just off one stays that near the tool the whole way, and the walk's step
5287/// is that distance: it stands a thousand times further off them (whatever
5288/// of the tool rides higher than that over such a face is still found).
5289fn check_single_pass(screw: &Screw, split: &Split, body: &BrepSolid, sliding: &std::collections::HashSet<u64>) -> Result<(), KernelRefusal> {
5290    let margin = 1e-9 * split.scale;
5291    for face in body.shells.iter().flat_map(|s| &s.faces) {
5292        let step = if sliding.contains(&face.id) { 1e-3 * split.scale } else { 1e-6 * split.scale };
5293        let surface = &face.surface;
5294        // Probe inside the face: towards each corner of its loop from the
5295        // average of its corners (caps are convex in their parameters), and on
5296        // a grid for the four-sided walls.
5297        let mut corners: Vec<[f64; 2]> = Vec::new();
5298        for coedge in &face.loops[0].coedges {
5299            let domain = frag(coedge.pcurve.domain(), "domain")?;
5300            for k in 0..4 {
5301                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 4.0), "pcurve")?;
5302                corners.push([p.x, p.y]);
5303            }
5304        }
5305        let middle = corners.iter().fold([0.0, 0.0], |s, c| [s[0] + c[0], s[1] + c[1]]);
5306        let middle = [middle[0] / corners.len() as f64, middle[1] / corners.len() as f64];
5307        let mut probes: Vec<[f64; 2]> = vec![middle];
5308        for c in &corners {
5309            for w in [0.25, 0.5, 0.75, 0.9, 0.99] {
5310                probes.push([middle[0] + (c[0] - middle[0]) * w, middle[1] + (c[1] - middle[1]) * w]);
5311            }
5312        }
5313        if surface.degree_v == 5 {
5314            let [u0, u1] = frag(surface.domain_u(), "domain")?;
5315            for i in 1..8 {
5316                for j in 1..64 {
5317                    probes.push([u0 + (u1 - u0) * i as f64 / 8.0, j as f64 / 64.0]);
5318                }
5319            }
5320        }
5321        let ([u0, u1], [v0, v1]) = (frag(surface.domain_u(), "domain")?, frag(surface.domain_v(), "domain")?);
5322        // Keep the probes inside the face's own loop (a face under a grazing
5323        // curve that dips is not convex in its parameters).
5324        let mut ring: Vec<[f64; 2]> = Vec::new();
5325        for coedge in &face.loops[0].coedges {
5326            let domain = frag(coedge.pcurve.domain(), "domain")?;
5327            for k in 0..32 {
5328                let p = frag(coedge.pcurve.evaluate(domain[0] + (domain[1] - domain[0]) * k as f64 / 32.0), "pcurve")?;
5329                ring.push([p.x, p.y]);
5330            }
5331        }
5332        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])]));
5333        for i in 1..12 {
5334            for j in 1..12 {
5335                probes.push([lo[0] + (hi[0] - lo[0]) * i as f64 / 12.0, lo[1] + (hi[1] - lo[1]) * j as f64 / 12.0]);
5336            }
5337        }
5338        let inside = |q: [f64; 2]| -> bool {
5339            let mut crossings = 0;
5340            for k in 0..ring.len() {
5341                let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
5342                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]) {
5343                    crossings += 1;
5344                }
5345            }
5346            crossings % 2 == 1
5347        };
5348        for [u, v] in probes.into_iter().filter(|&q| inside(q)) {
5349            let p = frag(surface.evaluate(u, v), "probe")?;
5350            let (hu, hv) = (1e-6 * (u1 - u0), 1e-6 * (v1 - v0));
5351            // Derivatives, not raw differences: their cross product is
5352            // measured against an absolute zero.
5353            let (ua, ub, va, vb) = ((u - hu).max(u0), (u + hu).min(u1), (v - hv).max(v0), (v + hv).min(v1));
5354            let du = frag(surface.evaluate(ub, v), "probe")?.sub(frag(surface.evaluate(ua, v), "probe")?).scale(1.0 / (ub - ua));
5355            let dv = frag(surface.evaluate(u, vb), "probe")?.sub(frag(surface.evaluate(u, va), "probe")?).scale(1.0 / (vb - va));
5356            let Ok(n) = du.cross(dv).normalized() else { continue };
5357            let n = if face.same_sense { n } else { n.scale(-1.0) };
5358            if covered(screw, split, p.add(n.scale(step)), margin)? {
5359                return Err(refuse("folds", format!("the sweep passes over a point twice (just outside its own face at {p:?}); not one pass")));
5360            }
5361        }
5362    }
5363    Ok(())
5364}