Skip to main content

brep_construction/construction/
solid_sweep.rs

1//! The sweep of a SOLID: everything a tool passes through as it moves, inside a
2//! region the caller names (the workpiece it is cut from).
3//!
4//! ## What is built, and why it reduces to a plane
5//!
6//! The boundary of a swept solid is an envelope: at each instant the tool's
7//! surface touches the sweep along its characteristic curve (where the motion's
8//! velocity is tangent to the surface), and the sweep's wall is the union of
9//! those curves. In general that wall has no simpler description. In the three
10//! classes built here it is invariant under a motion, so the region is a planar
11//! region carried by that motion:
12//!
13//! | class | tool | invariance | planar region | solid |
14//! |---|---|---|---|---|
15//! | SCREW | a solid of revolution | the screw | the section square to the screw axis | a loft through screwed copies |
16//! | TURN | a solid of revolution | the turn | the meridian section | a revolve |
17//! | PLANAR | a prism | the prism's direction | the union of the moving outline | an extrude |
18//!
19//! For a SCREW (axial advance `c` per radian) the reduced coordinates of a point
20//! are `(ℓ, o) = (ρ, α − z/c)`, both unchanged by the screw; for a TURN they are
21//! `(ρ, z)`; for a PLANAR motion `(ρ, α)` in the workpiece's frame. In each the
22//! region is described per LEVEL `ℓ` as a set of intervals of `o`.
23//!
24//! ## The region engine
25//!
26//! At a level the interval ends are local extrema of `o` over the images of the
27//! tool's boundary: on a face patch `S(u, v)` (a meridian piece revolved; an
28//! outline piece carried through time) Newton solves `ℓ(S) = ℓ₀`,
29//! `det(∇o, ∇ℓ) = 0` from seeds on a grid; on a sharp edge (a meridian corner
30//! revolved; an outline vertex carried through time; the outline at either end of
31//! the motion) the ends are the roots of `ℓ = ℓ₀`. These are CANDIDATES; a
32//! membership oracle (does the point's preimage under the motion meet the tool,
33//! for some time in the range, by the tool's signed distance) classifies the
34//! gaps between them, so the intervals are exact at every level. This is what
35//! survives where the characteristic degenerates: a grinding wheel set along its
36//! helix has a whole circle of characteristic points, which tracing the
37//! characteristic by parameter cannot follow, but the level extremes can.
38//!
39//! The levels are scanned for EVENTS — an interval born at a tip, two lobes
40//! merging, an interval end changing the boundary piece it lies on — solved by
41//! bisection. Between events each interval end is a smooth function of the
42//! level, sampled at levels clustered at both ends (`ℓ − ℓa ∝ σ²`, so a square
43//! root tip is smooth in `σ`) and interpolated as its own cubic edge. Along
44//! each event level the boundary runs along the level itself (an arc, or a
45//! straight line for the turn) where the intervals above and below differ.
46//!
47//! ## The contract
48//!
49//! Each returned body equals the sweep inside the clip region: levels in
50//! `clip.radius`, axial positions in `clip.axial`, angles in `clip.angle`. The
51//! caller cuts a workpiece that lies inside that region. A screw or turn whose
52//! first or last position reaches the clip region is refused, because there the
53//! sweep is not invariant; a planar sweep includes its end positions exactly.
54//!
55//! FOLDS. Two lobes of a space can merge where one face's envelope turns back
56//! (the plus-cut wheel's arm tip, ρ = 20). Where the face's fold Newton reaches
57//! the point it is a critical point like a tip; where it cannot (that envelope's
58//! level varies by 1e-4 along it, too flat for nested differences), the merge is
59//! located from the gap's own √ law: gap² fitted as a quadratic in the level at
60//! three levels just below, its root the merge level (4e-11 from ρ = 20).
61//!
62//! ## Not built yet (refused, never approximated)
63//!
64//! - A source whose level is constant along it (a vertex turning about the
65//!   clip's own axis) reads as roots everywhere; keep the clip's axis off such
66//!   a turn's axis.
67//! - Motions outside the three classes (two turns about skew axes: the
68//!   tumbling torus).
69use crate::{
70    extrude_profile_brep, interpolate_curve, loft_profile_brep, make_arc, make_line,
71    revolve_profile_brep, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, OrRefuse, Vec3,
72};
73use std::f64::consts::{PI, TAU};
74
75/// One piece of a planar outline, in the outline's own 2D coordinates.
76#[derive(Clone, Copy, Debug, PartialEq)]
77pub enum OutlinePiece {
78    /// The segment from `from` to `to`.
79    Line { from: [f64; 2], to: [f64; 2] },
80    /// The arc about `centre` of `radius`, from angle `start` to angle `end`
81    /// (radians; `end < start` runs clockwise). A full circle is `0 → 2π`.
82    Arc { centre: [f64; 2], radius: f64, start: f64, end: f64 },
83}
84
85impl OutlinePiece {
86    fn point(&self, s: f64) -> [f64; 2] {
87        match *self {
88            OutlinePiece::Line { from, to } => {
89                [from[0] + (to[0] - from[0]) * s, from[1] + (to[1] - from[1]) * s]
90            }
91            OutlinePiece::Arc { centre, radius, start, end } => {
92                let angle = start + (end - start) * s;
93                [centre[0] + radius * angle.cos(), centre[1] + radius * angle.sin()]
94            }
95        }
96    }
97
98    fn is_full_circle(&self) -> bool {
99        matches!(*self, OutlinePiece::Arc { start, end, .. } if ((end - start).abs() - TAU).abs() < 1e-12)
100    }
101
102    /// Unsigned distance from `p` to the piece.
103    fn distance(&self, p: [f64; 2]) -> f64 {
104        match *self {
105            OutlinePiece::Line { from, to } => {
106                let d = [to[0] - from[0], to[1] - from[1]];
107                let length2 = d[0] * d[0] + d[1] * d[1];
108                let t = if length2 > 0.0 {
109                    (((p[0] - from[0]) * d[0] + (p[1] - from[1]) * d[1]) / length2).clamp(0.0, 1.0)
110                } else {
111                    0.0
112                };
113                let q = [from[0] + d[0] * t - p[0], from[1] + d[1] * t - p[1]];
114                q[0].hypot(q[1])
115            }
116            OutlinePiece::Arc { centre, radius, start, end } => {
117                let v = [p[0] - centre[0], p[1] - centre[1]];
118                let angle = v[1].atan2(v[0]);
119                if self.is_full_circle() || angle_within(angle, start, end) {
120                    (v[0].hypot(v[1]) - radius).abs()
121                } else {
122                    let a = self.point(0.0);
123                    let b = self.point(1.0);
124                    (a[0] - p[0]).hypot(a[1] - p[1]).min((b[0] - p[0]).hypot(b[1] - p[1]))
125                }
126            }
127        }
128    }
129
130    /// Crossings of the ray from `p` towards +x with the piece (for the parity
131    /// inside test). Half-open in y so a vertex is counted once.
132    fn ray_crossings(&self, p: [f64; 2]) -> usize {
133        match *self {
134            OutlinePiece::Line { from, to } => {
135                let (a, b) = (from, to);
136                if (a[1] > p[1]) != (b[1] > p[1]) {
137                    let x = a[0] + (p[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
138                    usize::from(x > p[0])
139                } else {
140                    0
141                }
142            }
143            OutlinePiece::Arc { centre, radius, start, end } => {
144                let dy = p[1] - centre[1];
145                if dy.abs() >= radius {
146                    return 0;
147                }
148                let dx = (radius * radius - dy * dy).sqrt();
149                let mut count = 0;
150                for x in [centre[0] - dx, centre[0] + dx] {
151                    if x <= p[0] {
152                        continue;
153                    }
154                    let angle = dy.atan2(x - centre[0]);
155                    if self.is_full_circle() || angle_within(angle, start, end) {
156                        // Half-open at the arc's own ends, like the segment rule:
157                        // count an end only where the arc leaves upwards.
158                        count += 1;
159                    }
160                }
161                count
162            }
163        }
164    }
165}
166
167/// Is `angle` on the arc that runs from `start` to `end` (either sense)?
168fn angle_within(angle: f64, start: f64, end: f64) -> bool {
169    let (low, high) = if end >= start { (start, end) } else { (end, start) };
170    let shifted = low + (angle - low).rem_euclid(TAU);
171    shifted <= high
172}
173
174fn scale_of(outline: &[OutlinePiece]) -> f64 {
175    outline
176        .iter()
177        .flat_map(|piece| [piece.point(0.0), piece.point(1.0)])
178        .map(|p| p[0].abs().max(p[1].abs()))
179        .fold(1.0f64, f64::max)
180}
181
182/// Signed distance to a closed outline (negative inside).
183pub fn outline_signed_distance(outline: &[OutlinePiece], p: [f64; 2]) -> f64 {
184    let distance = outline
185        .iter()
186        .map(|piece| piece.distance(p))
187        .fold(f64::INFINITY, f64::min);
188    let crossings: usize = outline.iter().map(|piece| piece.ray_crossings(p)).sum();
189    if crossings % 2 == 1 {
190        -distance
191    } else {
192        distance
193    }
194}
195
196fn validate_outline(outline: &[OutlinePiece], what: &str) -> Result<(), KernelRefusal> {
197    if outline.is_empty() {
198        return Err(KernelRefusal::input(
199            KernelStage::Collect,
200            "outline_empty",
201            format!("sweepSolidWithin: the {what} outline is empty"),
202        ));
203    }
204    let scale = outline
205        .iter()
206        .flat_map(|piece| [piece.point(0.0), piece.point(1.0)])
207        .map(|p| p[0].abs().max(p[1].abs()))
208        .fold(1.0f64, f64::max);
209    for (index, piece) in outline.iter().enumerate() {
210        let next = &outline[(index + 1) % outline.len()];
211        let a = piece.point(1.0);
212        let b = next.point(0.0);
213        if (a[0] - b[0]).hypot(a[1] - b[1]) > 1e-9 * scale {
214            return Err(KernelRefusal::input(
215                KernelStage::Collect,
216                "outline_open",
217                format!("sweepSolidWithin: the {what} outline is not closed after piece {index}"),
218            ));
219        }
220    }
221    Ok(())
222}
223
224/// The moving tool.
225#[derive(Clone, Debug)]
226pub enum SweptTool {
227    /// A solid of revolution: the region `meridian` bounds in the half-plane
228    /// spanned by `radial` (first coordinate, the distance from the axis, ≥ 0)
229    /// and `axis_direction` (second coordinate), turned about the axis through
230    /// `axis_origin`.
231    Revolved {
232        axis_origin: Vec3,
233        axis_direction: Vec3,
234        radial: Vec3,
235        meridian: Vec<OutlinePiece>,
236    },
237    /// A prism: the region `outline` bounds in the plane through `origin`
238    /// spanned by `x_axis` and `normal × x_axis`, extended along `normal` from
239    /// `from` to `to`.
240    Prism {
241        origin: Vec3,
242        normal: Vec3,
243        x_axis: Vec3,
244        outline: Vec<OutlinePiece>,
245        from: f64,
246        to: f64,
247    },
248    /// A bar: the region `section` bounds (curves end to end round a closed
249    /// loop, lying in the plane through `origin` square to `normal`), extended
250    /// along `normal` from height `from` to `to`. Its sides lean inward by
251    /// `draft` radians: at height `h` the section is the given one moved
252    /// inward by `h·tan(draft)` (outward where that is negative). Swept by a
253    /// screw about the clip's axis, whichever way the bar points.
254    Bar {
255        origin: Vec3,
256        normal: Vec3,
257        section: Vec<NurbsCurve>,
258        from: f64,
259        to: f64,
260        draft: f64,
261    },
262}
263
264/// One elementary motion, linear in the motion parameter `t`: a turn of
265/// `turn·t` radians, right-handed about the axis through `axis_origin` along
266/// `axis_direction`, together with an advance of `advance·t` along it. A turn
267/// alone is `advance = 0`, a slide alone is `turn = 0`.
268#[derive(Clone, Copy, Debug)]
269pub struct ScrewStep {
270    pub axis_origin: Vec3,
271    pub axis_direction: Vec3,
272    pub turn: f64,
273    pub advance: f64,
274}
275
276/// A rigid motion: the steps applied in order (the first to the tool first),
277/// for `t` from `from` to `to`.
278#[derive(Clone, Debug)]
279pub struct SolidMotion {
280    pub steps: Vec<ScrewStep>,
281    pub from: f64,
282    pub to: f64,
283}
284
285/// The region the result must agree with the sweep in, about an axis: levels
286/// (distance from the axis) in `radius`, axial positions in `axial` (measured
287/// from `axis_origin`), and polar angles in `angle` (from `reference`,
288/// right-handed about the axis), when given.
289#[derive(Clone, Copy, Debug)]
290pub struct SweepClip {
291    pub axis_origin: Vec3,
292    pub axis_direction: Vec3,
293    pub reference: Vec3,
294    pub radius: [f64; 2],
295    pub axial: [f64; 2],
296    pub angle: Option<[f64; 2]>,
297}
298
299/// The prefix of every refusal of this operation.
300pub const SOLID_SWEEP_REFUSAL: &str = "sweepSolidWithin";
301
302/// Words of the refusal for a level the sweep covers at every angle.
303const WHOLE_LEVEL: &str = "the sweep covers every angle at level";
304
305/// Turns of a thread each row of faces carries (measured: shorter rows cost more
306/// meshing, longer ones more edge reading).
307const TURNS_PER_ROW: f64 = 2.0;
308
309/// `BREP_SWEEP_THREAD_ROWS` (default on; `=0` one body-long face per wall and the
310/// boolean for the clip): a thread is built a few turns at a time, since readings
311/// over a face cost the square of its length.
312fn thread_rows_on() -> bool {
313    crate::switch!("BREP_SWEEP_THREAD_ROWS", true)
314}
315
316/// `BREP_SWEEP_WHOLE_LEVEL` (default on; `=0` restores the refusal): a screw's
317/// sweep whose turns meet at a crest, built as the clip less what stays.
318fn whole_level_on() -> bool {
319    crate::switch!("BREP_SWEEP_WHOLE_LEVEL", true)
320}
321
322/// `BREP_SWEEP_SCREW_CARRY` (default off; `=1` on): every screw sweep's walls
323/// are carried along the screw to high order, as a bar's and a crest's already
324/// are, instead of lofted as a cubic through 64 sections a turn (which stands
325/// r·h⁴/384 off the screw: 1e-6 at a groove's floor).
326fn screw_carry_on() -> bool {
327    crate::switch!("BREP_SWEEP_SCREW_CARRY", false)
328}
329
330/// `BREP_SWEEP_APEX_TIP` (default off; `=1` on): a point of a solid of
331/// revolution on its own axis (a cone's apex) is a critical point of the faces
332/// that meet there. It revolves into nothing, so no edge carries it, and a
333/// groove whose tip it cuts was ended where bisection first saw the level's
334/// contour (3.5e-7 short of a cone point's tip) instead of at the point itself.
335fn apex_tip_on() -> bool {
336    crate::switch!("BREP_SWEEP_APEX_TIP", false)
337}
338
339fn refuse(what: &'static str, message: String) -> KernelRefusal {
340    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{SOLID_SWEEP_REFUSAL}: {message}"))
341}
342
343fn rotate(x: Vec3, origin: Vec3, axis: Vec3, angle: f64) -> Vec3 {
344    origin.add(x.sub(origin).rotate_about(axis, angle))
345}
346
347impl ScrewStep {
348    fn apply(&self, t: f64, x: Vec3, axis: Vec3) -> Vec3 {
349        rotate(x, self.axis_origin, axis, self.turn * t).add(axis.scale(self.advance * t))
350    }
351    fn invert(&self, t: f64, x: Vec3, axis: Vec3) -> Vec3 {
352        rotate(x.sub(axis.scale(self.advance * t)), self.axis_origin, axis, -self.turn * t)
353    }
354}
355
356/// Orthonormal frame of the clip: (ex, ey, ez).
357#[derive(Clone, Copy, Debug)]
358struct Frame {
359    origin: Vec3,
360    ex: Vec3,
361    ey: Vec3,
362    ez: Vec3,
363}
364
365impl Frame {
366    fn local(&self, x: Vec3) -> [f64; 3] {
367        let d = x.sub(self.origin);
368        [d.dot(self.ex), d.dot(self.ey), d.dot(self.ez)]
369    }
370    fn world(&self, p: [f64; 3]) -> Vec3 {
371        self.origin
372            .add(self.ex.scale(p[0]))
373            .add(self.ey.scale(p[1]))
374            .add(self.ez.scale(p[2]))
375    }
376}
377
378#[derive(Clone, Copy, Debug, PartialEq)]
379enum Class {
380    /// Axial advance per radian of the screw, in the clip frame (nonzero).
381    Screw(f64),
382    Turn,
383    Planar,
384}
385
386/// A tool-boundary source: a face patch over a 2D parameter box, or an edge
387/// over a 1D parameter interval. `periodic` marks a parameter that wraps.
388#[derive(Clone, Copy, Debug)]
389enum Source {
390    /// Revolved meridian piece `piece`, parameters (s ∈ [0,1], φ ∈ [0,2π)).
391    RevolvedFace { piece: usize },
392    /// Revolved meridian corner at the start of piece `piece`, parameter φ.
393    RevolvedCorner { piece: usize },
394    /// Prism outline piece `piece` carried through time: (s ∈ [0,1], t).
395    PrismFace { piece: usize },
396    /// Prism outline vertex at the start of piece `piece`, parameter t.
397    PrismVertex { piece: usize },
398    /// Prism outline piece `piece` at the motion's first (`end = false`) or last
399    /// position, parameter s.
400    PrismEnd { piece: usize, end: bool },
401    /// Under a screw, at the tool's own place (the screw's reduction is invariant
402    /// along it): side face of outline piece `piece`, (s ∈ [0,1], height).
403    ScrewPrismSide { piece: usize },
404    /// Under a screw: the upright edge at the start of piece `piece`, parameter height.
405    ScrewPrismEdge { piece: usize },
406    /// Under a screw: outline piece `piece` at the prism's low (`end = false`) or
407    /// high end, parameter s. An end cap itself maps one-to-one into the reduced
408    /// plane (polar coordinates at a fixed height), so only its rim can bound.
409    ScrewPrismRim { piece: usize, end: bool },
410    /// A bar's side on section curve `piece`, at its own place: (s ∈ [0,1], height).
411    BarSide { piece: usize },
412    /// A bar's upright edge at the start of section curve `piece`, parameter height.
413    BarEdge { piece: usize },
414    /// A bar's section curve `piece` at its low (`end = false`) or high end, parameter s.
415    BarRim { piece: usize, end: bool },
416}
417
418struct Engine<'a> {
419    tool: &'a SweptTool,
420    motion: &'a SolidMotion,
421    axes: Vec<Vec3>,
422    frame: Frame,
423    class: Class,
424    clip: &'a SweepClip,
425    /// The tool as a bar, where it is swept as one.
426    bar: Option<crate::solid_sweep_bar::Bar>,
427    /// The clip was narrowed to a crest level: below it some material is left.
428    crest_gap: bool,
429    sources: Vec<Source>,
430    /// Per face source: its parameter grid (nu × nv) of reduced coordinates.
431    grids: Vec<Option<Grid>>,
432    /// Per source: its critical points of the level, as (level, o).
433    critical: Vec<Vec<(f64, f64)>>,
434    /// Per face source: the parameters of its critical points (tips), which
435    /// seed the extremum Newton where the level's contour is smaller than a cell.
436    critical_params: Vec<Vec<(f64, f64)>>,
437    /// Angular `o` (wraps at 2π) or not.
438    angular: bool,
439    /// Prism height (along its normal) the planar sources are evaluated at.
440    prism_height: f64,
441    scale: f64,
442    /// `intervals_at` by level bits: the sampling revisits levels (a refined
443    /// band keeps every level of the coarser one).
444    cache: std::cell::RefCell<std::collections::HashMap<u64, Vec<Interval>>>,
445    /// The motion ends where it began as a set (the plus wheel: one turn of the
446    /// wheel, one and a half of the tool), so there are no end positions; piece
447    /// `k` at the end continues as piece `wrap[k]` at the start.
448    wrap: Option<Vec<usize>>,
449    /// Debug counters: (levels evaluated, oracle calls, oracle steps, seconds in
450    /// candidates, seconds in the oracle).
451    counters: std::cell::Cell<(usize, usize, usize, f64, f64)>,
452}
453
454struct Grid {
455    nu: usize,
456    nv: usize,
457    u: [f64; 2],
458    v: [f64; 2],
459    v_periodic: bool,
460    values: Vec<(f64, f64)>,
461}
462
463/// One interval of the region at a level, with the sources of its ends.
464#[derive(Clone, Copy, Debug)]
465struct Interval {
466    lo: f64,
467    hi: f64,
468    lo_source: usize,
469    hi_source: usize,
470}
471
472fn wrap_pi(angle: f64) -> f64 {
473    let wrapped = (angle + PI).rem_euclid(TAU) - PI;
474    wrapped
475}
476
477impl<'a> Engine<'a> {
478    fn motion_apply(&self, t: f64, x: Vec3) -> Vec3 {
479        self.motion
480            .steps
481            .iter()
482            .zip(&self.axes)
483            .fold(x, |x, (step, axis)| step.apply(t, x, *axis))
484    }
485
486    fn motion_invert(&self, t: f64, x: Vec3) -> Vec3 {
487        self.motion
488            .steps
489            .iter()
490            .zip(&self.axes)
491            .rev()
492            .fold(x, |x, (step, axis)| step.invert(t, x, *axis))
493    }
494
495    /// Reduced coordinates of a clip-frame point.
496    fn reduce(&self, p: [f64; 3]) -> (f64, f64) {
497        let level = p[0].hypot(p[1]);
498        match self.class {
499            Class::Screw(c) => (level, p[1].atan2(p[0]) - p[2] / c),
500            Class::Turn => (level, p[2]),
501            Class::Planar => (level, p[1].atan2(p[0])),
502        }
503    }
504
505    fn tool_signed_distance(&self, x: Vec3) -> f64 {
506        if let Some(bar) = &self.bar {
507            return bar.signed_distance(x);
508        }
509        match self.tool {
510            SweptTool::Bar { .. } => f64::INFINITY,
511            SweptTool::Revolved { axis_origin, axis_direction, meridian, .. } => {
512                let axis = axis_direction.normalized_or(*axis_direction);
513                let d = x.sub(*axis_origin);
514                let e = d.dot(axis);
515                let radial = d.sub(axis.scale(e)).length();
516                outline_signed_distance(meridian, [radial, e])
517            }
518            SweptTool::Prism { origin, normal, x_axis, outline, from, to } => {
519                let n = normal.normalized_or(*normal);
520                let xa = x_axis.normalized_or(*x_axis);
521                let ya = n.cross(xa);
522                let d = x.sub(*origin);
523                let h = d.dot(n);
524                let planar = outline_signed_distance(outline, [d.dot(xa), d.dot(ya)]);
525                planar.max(from - h).max(h - to)
526            }
527        }
528    }
529
530    /// The world point of a source at its parameters (at the tool's own place
531    /// for revolved tools; carried by the motion for prisms).
532    fn source_point(&self, source: Source, u: f64, v: f64) -> Vec3 {
533        if let Some(bar) = &self.bar {
534            match source {
535                Source::BarSide { piece } => return bar.side(piece, u, v),
536                Source::BarEdge { piece } => return bar.joint(piece, u),
537                Source::BarRim { piece, end } => return bar.side(piece, u, if end { bar.to } else { bar.from }),
538                _ => {}
539            }
540        }
541        match (self.tool, source) {
542            (SweptTool::Bar { origin, .. }, _) => *origin,
543            (SweptTool::Revolved { axis_origin, axis_direction, radial, meridian }, _) => {
544                let axis = axis_direction.normalized_or(*axis_direction);
545                let r0 = radial.sub(axis.scale(radial.dot(axis))).normalized_or(*radial);
546                let r1 = axis.cross(r0);
547                let (m, phi) = match source {
548                    Source::RevolvedFace { piece } => (meridian[piece].point(u), v),
549                    Source::RevolvedCorner { piece } => (meridian[piece].point(0.0), u),
550                    _ => unreachable!(),
551                };
552                axis_origin
553                    .add(r0.scale(m[0] * phi.cos()))
554                    .add(r1.scale(m[0] * phi.sin()))
555                    .add(axis.scale(m[1]))
556            }
557            (SweptTool::Prism { origin, normal, x_axis, outline, from, to }, _) => {
558                let n = normal.normalized_or(*normal);
559                let xa = x_axis.normalized_or(*x_axis);
560                let ya = n.cross(xa);
561                let at_own_place = match source {
562                    Source::ScrewPrismSide { piece } => Some((outline[piece].point(u), v)),
563                    Source::ScrewPrismEdge { piece } => Some((outline[piece].point(0.0), u)),
564                    Source::ScrewPrismRim { piece, end } => Some((outline[piece].point(u), if end { *to } else { *from })),
565                    _ => None,
566                };
567                if let Some((q, h)) = at_own_place {
568                    return origin.add(xa.scale(q[0])).add(ya.scale(q[1])).add(n.scale(h));
569                }
570                let (q, t) = match source {
571                    Source::PrismFace { piece } => (outline[piece].point(u), v),
572                    Source::PrismVertex { piece } => (outline[piece].point(0.0), u),
573                    Source::PrismEnd { piece, end } => (
574                        outline[piece].point(u),
575                        if end { self.motion.to } else { self.motion.from },
576                    ),
577                    _ => unreachable!(),
578                };
579                let x = origin
580                    .add(xa.scale(q[0]))
581                    .add(ya.scale(q[1]))
582                    .add(n.scale(self.prism_height));
583                self.motion_apply(t, x)
584            }
585        }
586    }
587
588    fn source_reduced(&self, source: Source, u: f64, v: f64) -> (f64, f64) {
589        self.reduce(self.frame.local(self.source_point(source, u, v)))
590    }
591
592    fn is_face(source: Source) -> bool {
593        matches!(source, Source::RevolvedFace { .. } | Source::PrismFace { .. } | Source::ScrewPrismSide { .. } | Source::BarSide { .. })
594    }
595
596    /// Parameter domain of a source: (u range, v range, v periodic).
597    fn domain(&self, source: Source) -> ([f64; 2], [f64; 2], bool) {
598        let time = [self.motion.from, self.motion.to];
599        match source {
600            Source::RevolvedFace { .. } => ([0.0, 1.0], [0.0, TAU], true),
601            Source::RevolvedCorner { .. } => ([0.0, TAU], [0.0, 0.0], false),
602            Source::PrismFace { .. } => ([0.0, 1.0], time, false),
603            Source::PrismVertex { .. } => (time, [0.0, 0.0], false),
604            Source::PrismEnd { .. } => ([0.0, 1.0], [0.0, 0.0], false),
605            Source::ScrewPrismSide { .. } => ([0.0, 1.0], self.prism_extent(), false),
606            Source::ScrewPrismEdge { .. } => (self.prism_extent(), [0.0, 0.0], false),
607            Source::ScrewPrismRim { .. } => ([0.0, 1.0], [0.0, 0.0], false),
608            Source::BarSide { .. } => ([0.0, 1.0], self.prism_extent(), false),
609            Source::BarEdge { .. } => (self.prism_extent(), [0.0, 0.0], false),
610            Source::BarRim { .. } => ([0.0, 1.0], [0.0, 0.0], false),
611        }
612    }
613
614    fn prism_extent(&self) -> [f64; 2] {
615        if let Some(bar) = &self.bar {
616            return [bar.from, bar.to];
617        }
618        match self.tool {
619            SweptTool::Bar { from, to, .. } => [*from, *to],
620            SweptTool::Prism { from, to, .. } => [*from, *to],
621            SweptTool::Revolved { .. } => [0.0, 0.0],
622        }
623    }
624
625    /// Is the face's first parameter periodic (a full circle in the meridian or
626    /// outline, which has no corner to bound it)?
627    fn u_periodic(&self, source: Source) -> bool {
628        match (self.tool, source) {
629            (_, Source::BarSide { .. }) => self.bar.as_ref().is_some_and(|bar| bar.periodic),
630            (SweptTool::Revolved { meridian, .. }, Source::RevolvedFace { piece }) => meridian[piece].is_full_circle(),
631            (SweptTool::Prism { outline, .. }, Source::PrismFace { piece } | Source::ScrewPrismSide { piece }) => outline[piece].is_full_circle(),
632            _ => false,
633        }
634    }
635
636    fn o_difference(&self, a: f64, b: f64) -> f64 {
637        if self.angular {
638            wrap_pi(a - b)
639        } else {
640            a - b
641        }
642    }
643
644    /// Newton on {ℓ = level, det(∇o, ∇ℓ) = 0} over a face source.
645    fn face_extremum(&self, source: Source, level: f64, mut u: f64, mut v: f64) -> Option<(f64, f64, f64)> {
646        let (ur, vr, periodic) = self.domain(source);
647        let hu = 1e-6 * (ur[1] - ur[0]).max(1e-3);
648        let hv = 1e-6 * (vr[1] - vr[0]).max(1e-3);
649        let residual = |u: f64, v: f64| -> [f64; 2] {
650            let (l, o) = self.source_reduced(source, u, v);
651            let (lu1, ou1) = self.source_reduced(source, u + hu, v);
652            let (lu0, ou0) = self.source_reduced(source, u - hu, v);
653            let (lv1, ov1) = self.source_reduced(source, u, v + hv);
654            let (lv0, ov0) = self.source_reduced(source, u, v - hv);
655            let (lu, lv) = ((lu1 - lu0) / (2.0 * hu), (lv1 - lv0) / (2.0 * hv));
656            let ou = self.o_difference(ou1, ou0) / (2.0 * hu);
657            let ov = self.o_difference(ov1, ov0) / (2.0 * hv);
658            // det scaled by the level's gradient so its size is that of ∇o.
659            let norm = lu.hypot(lv).max(1e-300);
660            let _ = o;
661            [l - level, (ou * lv - ov * lu) / norm]
662        };
663        let mut f = residual(u, v);
664        for _ in 0..60 {
665            let (du_step, dv_step) = (hu * 10.0, hv * 10.0);
666            let fu1 = residual(u + du_step, v);
667            let fu0 = residual(u - du_step, v);
668            let fv1 = residual(u, v + dv_step);
669            let fv0 = residual(u, v - dv_step);
670            let j = [
671                [(fu1[0] - fu0[0]) / (2.0 * du_step), (fv1[0] - fv0[0]) / (2.0 * dv_step)],
672                [(fu1[1] - fu0[1]) / (2.0 * du_step), (fv1[1] - fv0[1]) / (2.0 * dv_step)],
673            ];
674            let det = j[0][0] * j[1][1] - j[0][1] * j[1][0];
675            if !det.is_finite() || det.abs() < 1e-300 {
676                return None;
677            }
678            let du = -(f[0] * j[1][1] - f[1] * j[0][1]) / det;
679            let dv = -(j[0][0] * f[1] - j[1][0] * f[0]) / det;
680            let norm0 = f[0].hypot(f[1]);
681            let mut step = 1.0;
682            let mut accepted = false;
683            while step > 1e-4 {
684                let (nu, nv) = (u + step * du, v + step * dv);
685                let candidate = residual(nu, nv);
686                if candidate[0].hypot(candidate[1]) < norm0 || norm0 < 1e-14 * self.scale {
687                    u = nu;
688                    v = nv;
689                    f = candidate;
690                    accepted = true;
691                    break;
692                }
693                step *= 0.5;
694            }
695            if !accepted {
696                break;
697            }
698            if (du * step).abs() < 1e-15 * (ur[1] - ur[0]) && (dv * step).abs() < 1e-15 * (vr[1] - vr[0]).max(1.0) {
699                break;
700            }
701        }
702        if periodic {
703            v = vr[0] + (v - vr[0]).rem_euclid(vr[1] - vr[0]);
704        }
705        if self.u_periodic(source) {
706            u = ur[0] + (u - ur[0]).rem_euclid(ur[1] - ur[0]);
707        }
708        let tolerance = 1e-9;
709        if u < ur[0] - tolerance || u > ur[1] + tolerance || (!periodic && (v < vr[0] - tolerance || v > vr[1] + tolerance)) {
710            return None;
711        }
712        if f[0].abs() > 1e-10 * self.scale || f[1].abs() > 1e-6 {
713            return None;
714        }
715        let (l, o) = self.source_reduced(source, u.clamp(ur[0], ur[1]), v);
716        Some((l, o, u))
717    }
718
719    fn build_grid(&self, source: Source) -> Grid {
720        let (u, v, v_periodic) = self.domain(source);
721        let (nu, nv) = match source {
722            Source::RevolvedFace { .. } => (64, 256),
723            Source::ScrewPrismSide { .. } => (64, 64),
724            Source::BarSide { .. } => (128, 64),
725            _ => {
726                let turn = self
727                    .motion
728                    .steps
729                    .iter()
730                    .map(|step| step.turn.abs())
731                    .fold(0.0, f64::max)
732                    * (self.motion.to - self.motion.from).abs();
733                (48, ((turn * 128.0) as usize).clamp(256, 4096))
734            }
735        };
736        let mut values = Vec::with_capacity(nu * nv);
737        for i in 0..nu {
738            let uu = u[0] + (u[1] - u[0]) * i as f64 / (nu - 1) as f64;
739            for j in 0..nv {
740                let vv = if v_periodic {
741                    v[0] + (v[1] - v[0]) * j as f64 / nv as f64
742                } else {
743                    v[0] + (v[1] - v[0]) * j as f64 / (nv - 1) as f64
744                };
745                values.push(self.source_reduced(source, uu, vv));
746            }
747        }
748        Grid { nu, nv, u, v, v_periodic, values }
749    }
750
751    fn grid_param(grid: &Grid, i: usize, j: usize) -> (f64, f64) {
752        let u = grid.u[0] + (grid.u[1] - grid.u[0]) * i as f64 / (grid.nu - 1) as f64;
753        let v = if grid.v_periodic {
754            grid.v[0] + (grid.v[1] - grid.v[0]) * j as f64 / grid.nv as f64
755        } else {
756            grid.v[0] + (grid.v[1] - grid.v[0]) * j as f64 / (grid.nv - 1) as f64
757        };
758        (u, v)
759    }
760
761    /// Candidates of one source at a level: (o, source index).
762    fn source_candidates(&self, index: usize, level: f64, out: &mut Vec<(f64, usize)>) {
763        let source = self.sources[index];
764        if Self::is_face(source) {
765            let grid = self.grids[index].as_ref().expect("face grid");
766            // Crossings of the level along grid edges, then seeds where o is a
767            // local extremum among the crossings of neighbouring cells.
768            let at = |i: usize, j: usize| grid.values[i * grid.nv + j % grid.nv];
769            let jmax = if grid.v_periodic { grid.nv } else { grid.nv - 1 };
770            let mut crossings: Vec<(usize, usize, f64, f64, f64)> = Vec::new();
771            for i in 0..grid.nu {
772                for j in 0..jmax {
773                    let a = at(i, j);
774                    let b = at(i, j + 1);
775                    if (a.0 - level) * (b.0 - level) <= 0.0 && a.0 != b.0 {
776                        let w = (level - a.0) / (b.0 - a.0);
777                        let o = a.1 + self.o_difference(b.1, a.1) * w;
778                        let (u, v0) = Self::grid_param(grid, i, j);
779                        let (_, v1) = Self::grid_param(grid, i, j + 1);
780                        let v1 = if grid.v_periodic && j + 1 == grid.nv { grid.v[1] } else { v1 };
781                        crossings.push((i, j, o, u, v0 + (v1 - v0) * w));
782                    }
783                }
784            }
785            for i in 0..grid.nu.saturating_sub(1) {
786                for j in 0..grid.nv {
787                    let a = at(i, j);
788                    let b = at(i + 1, j);
789                    if (a.0 - level) * (b.0 - level) <= 0.0 && a.0 != b.0 {
790                        let w = (level - a.0) / (b.0 - a.0);
791                        let o = a.1 + self.o_difference(b.1, a.1) * w;
792                        let (u0, v) = Self::grid_param(grid, i, j);
793                        let (u1, _) = Self::grid_param(grid, i + 1, j);
794                        crossings.push((i, j, o, u0 + (u1 - u0) * w, v));
795                    }
796                }
797            }
798            let mut found: Vec<(f64, f64, f64)> = Vec::new();
799            let push = |found: &mut Vec<(f64, f64, f64)>, result: Option<(f64, f64, f64)>| {
800                if let Some((_, o_new, u_new)) = result {
801                    if !found
802                        .iter()
803                        .any(|&(o_old, u_old, _)| self.o_difference(o_old, o_new).abs() < 1e-11 && (u_old - u_new).abs() < 1e-6)
804                    {
805                        found.push((o_new, u_new, 0.0));
806                    }
807                }
808            };
809            // Near a tip the contour can be smaller than a cell: seed from the
810            // tip itself, pushed off it in four directions.
811            if let Some(params) = self.critical_params.get(index) {
812                let (ur, vr, _) = self.domain(source);
813                for &(u, v) in params {
814                    for (du, dv) in [(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] {
815                        let (su, sv) = (u + du * 1e-3 * (ur[1] - ur[0]), v + dv * 1e-3 * (vr[1] - vr[0]));
816                        push(&mut found, self.face_extremum(source, level, su, sv));
817                    }
818                }
819            }
820            let mut buckets: std::collections::HashMap<(usize, usize), Vec<usize>> = std::collections::HashMap::new();
821            for (k, &(i, j, _, _, _)) in crossings.iter().enumerate() {
822                buckets.entry((i, j)).or_default().push(k);
823            }
824            for (k, &(i, j, o, u, v)) in crossings.iter().enumerate() {
825                let mut is_max = true;
826                let mut is_min = true;
827                let mut neighbours = Vec::new();
828                for di in [-1i64, 0, 1] {
829                    for dj in [-1i64, 0, 1] {
830                        let i2 = i as i64 + di;
831                        if i2 < 0 {
832                            continue;
833                        }
834                        let j2 = j as i64 + dj;
835                        let j2 = if grid.v_periodic { j2.rem_euclid(grid.nv as i64) } else { j2 };
836                        if j2 < 0 {
837                            continue;
838                        }
839                        if let Some(list) = buckets.get(&(i2 as usize, j2 as usize)) {
840                            neighbours.extend(list.iter().copied());
841                        }
842                    }
843                }
844                for m in neighbours {
845                    if m == k {
846                        continue;
847                    }
848                    let o2 = crossings[m].2;
849                    {
850                        let d = self.o_difference(o2, o);
851                        if d > 0.0 {
852                            is_max = false;
853                        }
854                        if d < 0.0 {
855                            is_min = false;
856                        }
857                    }
858                }
859                if !(is_max || is_min) {
860                    continue;
861                }
862                push(&mut found, self.face_extremum(source, level, u, v));
863            }
864            out.extend(found.into_iter().map(|(o, _, _)| (o, index)));
865        } else {
866            let (range, _, _) = self.domain(source);
867            let periodic = matches!(source, Source::RevolvedCorner { .. });
868            let n = match source {
869                Source::RevolvedCorner { .. }
870                | Source::PrismEnd { .. }
871                | Source::ScrewPrismEdge { .. }
872                | Source::ScrewPrismRim { .. }
873                | Source::BarEdge { .. }
874                | Source::BarRim { .. } => 1024,
875                _ => self.grids_len_for_time(),
876            };
877            let _ = periodic;
878            // The uniform samples, with the curve's own level extrema merged in:
879            // near a tip the two roots of `ℓ = ℓ₀` fall either side of the extremum,
880            // closer than any fixed step, and would be missed together.
881            let mut samples: Vec<f64> = (0..=n).map(|k| range[0] + (range[1] - range[0]) * k as f64 / n as f64).collect();
882            if let Some(extra) = self.critical_params.get(index) {
883                samples.extend(extra.iter().map(|p| p.0).filter(|t| *t > range[0] && *t < range[1]));
884                samples.sort_by(|a, b| a.total_cmp(b));
885            }
886            let mut previous = self.source_reduced(source, samples[0], 0.0).0 - level;
887            for k in 1..samples.len() {
888                let p = samples[k];
889                let value = self.source_reduced(source, p, 0.0).0 - level;
890                if previous == 0.0 {
891                    // A root exactly on the sample (a band's end level on the
892                    // curve's own end): bisecting from a zero walks to the far
893                    // end of the bracket, a whole sample step away.
894                    out.push((self.source_reduced(source, samples[k - 1], 0.0).1, index));
895                } else if previous * value < 0.0 {
896                    let (mut a, mut b) = (samples[k - 1], p);
897                    let fa0 = previous;
898                    for _ in 0..200 {
899                        let m = 0.5 * (a + b);
900                        let fm = self.source_reduced(source, m, 0.0).0 - level;
901                        if (fm < 0.0) == (fa0 < 0.0) && fm != 0.0 {
902                            a = m;
903                        } else {
904                            b = m;
905                        }
906                        if (b - a).abs() < 1e-15 * (range[1] - range[0]).abs().max(1.0) {
907                            break;
908                        }
909                    }
910                    let (_, o) = self.source_reduced(source, 0.5 * (a + b), 0.0);
911                    out.push((o, index));
912                }
913                previous = value;
914            }
915            if previous == 0.0 {
916                let last = *samples.last().expect("nonempty");
917                out.push((self.source_reduced(source, last, 0.0).1, index));
918            }
919        }
920    }
921
922    fn grids_len_for_time(&self) -> usize {
923        let turn = self
924            .motion
925            .steps
926            .iter()
927            .map(|step| step.turn.abs())
928            .fold(0.0, f64::max)
929            * (self.motion.to - self.motion.from).abs();
930        ((turn * 256.0) as usize).clamp(1024, 8192)
931    }
932
933    /// The clip-frame point a reduced coordinate is tested at.
934    fn lift(&self, level: f64, o: f64) -> [f64; 3] {
935        let axial = 0.5 * (self.clip.axial[0] + self.clip.axial[1]);
936        match self.class {
937            Class::Screw(c) => {
938                let alpha = o + axial / c;
939                [level * alpha.cos(), level * alpha.sin(), axial]
940            }
941            Class::Turn => {
942                let theta = self.clip.angle.map(|a| 0.5 * (a[0] + a[1])).unwrap_or(0.0);
943                [level * theta.cos(), level * theta.sin(), o]
944            }
945            Class::Planar => [level * o.cos(), level * o.sin(), axial],
946        }
947    }
948
949    /// Is the reduced point inside the sweep: does the point's preimage under
950    /// the motion meet the tool for some time in the range?
951    ///
952    /// Walked in time by the tool's signed distance: it bounds how far the
953    /// preimage is from the tool, and the preimage moves no faster than
954    /// `speed_bound`, so no time within `distance / speed` of the current one can
955    /// be inside. The walk is exact for the tool's own distance (a lower bound for
956    /// a prism, which is conservative), and the floor on the step only stops a
957    /// grazing walk from creeping.
958    fn removed(&self, level: f64, o: f64) -> bool {
959        let x = self.frame.world(self.lift(level, o));
960        let (t0, t1) = (self.motion.from, self.motion.to);
961        let speed = self.speed_bound(x);
962        // The floor only keeps a grazing walk from creeping; a coarse floor
963        // jumps over a shallow pass of the tool (1e-5 of the plus wheel's range
964        // is 0.02 mm of travel, and read a 4e-3 mm sliver of its tooth space as
965        // material). A walk still grazing after `cap` steps is on the boundary.
966        let floor = (t1 - t0) * 1e-8;
967        let cap = 200_000usize;
968        let touching = 1e-10 * self.scale;
969        let clock = web_time::Instant::now();
970        let mut t = t0;
971        let mut steps = 0usize;
972        let inside = loop {
973            steps += 1;
974            let distance = self.tool_signed_distance(self.motion_invert(t, x));
975            if distance <= touching || steps > cap {
976                break true;
977            }
978            if t >= t1 {
979                break false;
980            }
981            t = (t + (distance / speed).max(floor)).min(t1);
982        };
983        let mut c = self.counters.get();
984        c.1 += 1;
985        c.2 += steps;
986        c.4 += clock.elapsed().as_secs_f64();
987        self.counters.set(c);
988        inside
989    }
990
991    /// An upper bound on how fast the preimage `M(t)⁻¹ x` moves per unit `t`.
992    fn speed_bound(&self, x: Vec3) -> f64 {
993        let centre = self.frame.origin;
994        let span = self.motion.from.abs().max(self.motion.to.abs());
995        let mut reach = x.sub(centre).length();
996        for step in &self.motion.steps {
997            reach += 2.0 * step.axis_origin.sub(centre).length() + step.advance.abs() * span;
998        }
999        let speed: f64 = self
1000            .motion
1001            .steps
1002            .iter()
1003            .map(|step| step.turn.abs() * (reach + step.axis_origin.sub(centre).length()) + step.advance.abs())
1004            .sum();
1005        speed.max(1e-300)
1006    }
1007
1008    /// The region's intervals at a level, sorted by `lo` (angular: `lo` in
1009    /// [0, 2π), `hi` may exceed 2π).
1010    fn intervals_at(&self, level: f64) -> Result<Vec<Interval>, KernelRefusal> {
1011        if let Some(hit) = self.cache.borrow().get(&level.to_bits()) {
1012            return Ok(hit.clone());
1013        }
1014        let clock = web_time::Instant::now();
1015        let before = self.counters.get();
1016        let intervals = self.intervals_uncached(level)?;
1017        if clock.elapsed().as_secs_f64() > 0.5 && std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
1018            let after = self.counters.get();
1019            eprintln!(
1020                "  slow level {level:.12}: {:.2}s, candidates {:.2}s, oracle calls {} steps {} ({:.2}s), {} intervals",
1021                clock.elapsed().as_secs_f64(),
1022                after.3 - before.3,
1023                after.1 - before.1,
1024                after.2 - before.2,
1025                after.4 - before.4,
1026                intervals.len()
1027            );
1028        }
1029        self.cache.borrow_mut().insert(level.to_bits(), intervals.clone());
1030        Ok(intervals)
1031    }
1032
1033    fn intervals_uncached(&self, level: f64) -> Result<Vec<Interval>, KernelRefusal> {
1034        let clock = web_time::Instant::now();
1035        let mut candidates = Vec::new();
1036        for index in 0..self.sources.len() {
1037            self.source_candidates(index, level, &mut candidates);
1038        }
1039        let mut c = self.counters.get();
1040        c.0 += 1;
1041        c.3 += clock.elapsed().as_secs_f64();
1042        self.counters.set(c);
1043        if self.angular {
1044            for candidate in &mut candidates {
1045                candidate.0 = candidate.0.rem_euclid(TAU);
1046            }
1047        }
1048        candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
1049        candidates.dedup_by(|b, a| (b.0 - a.0).abs() < 1e-12);
1050        if candidates.is_empty() {
1051            let probes = 64;
1052            let (base, span) = if self.angular { (0.0, TAU) } else { (-self.scale * 4.0, self.scale * 8.0) };
1053            if (0..probes).all(|k| self.removed(level, base + span * (k as f64 + 0.5) / probes as f64)) {
1054                return Err(refuse(
1055                    "whole_level",
1056                    format!("{WHOLE_LEVEL} {level}, which this construction does not build"),
1057                ));
1058            }
1059            return Ok(Vec::new());
1060        }
1061        let n = candidates.len();
1062        let gaps = if self.angular { n } else { n - 1 };
1063        let mut removed = Vec::with_capacity(gaps);
1064        for k in 0..gaps {
1065            let a = candidates[k].0;
1066            let b = if k + 1 < n { candidates[k + 1].0 } else { candidates[0].0 + TAU };
1067            // A gap far below any feature is the two ends of one boundary
1068            // point; its middle is on the boundary, where the oracle can only
1069            // graze. It joins whatever is on either side.
1070            if (b - a) * level.max(1.0) < 1e-9 * self.scale {
1071                removed.push(true);
1072                continue;
1073            }
1074            removed.push(self.removed(level, 0.5 * (a + b)));
1075        }
1076        let mut intervals = Vec::new();
1077        // Below a crest some material is left, however narrow: the widest gap,
1078        // which the oracle can no longer see inside.
1079        if self.crest_gap && self.angular && removed.iter().all(|r| *r) {
1080            let width = |k: usize| if k + 1 < n { candidates[k + 1].0 - candidates[k].0 } else { candidates[0].0 + TAU - candidates[k].0 };
1081            if let Some(widest) = (0..gaps).max_by(|&a, &b| width(a).total_cmp(&width(b))) {
1082                removed[widest] = false;
1083            }
1084        }
1085        if self.angular && removed.iter().all(|r| *r) {
1086            return Err(refuse(
1087                "whole_level",
1088                format!("{WHOLE_LEVEL} {level}, which this construction does not build"),
1089            ));
1090        }
1091        // Start the walk after a material gap so a run never straddles the start.
1092        let start = if self.angular {
1093            removed.iter().position(|r| !r).map(|k| (k + 1) % n).unwrap_or(0)
1094        } else {
1095            0
1096        };
1097        let mut k = 0;
1098        while k < gaps {
1099            let g = (start + k) % n.max(1);
1100            if !removed[g] {
1101                k += 1;
1102                continue;
1103            }
1104            let first = g;
1105            let mut last = g;
1106            while k + 1 < gaps && removed[(start + k + 1) % n] {
1107                k += 1;
1108                last = (start + k) % n;
1109            }
1110            let lo = candidates[first];
1111            let hi_index = (last + 1) % n;
1112            let hi = candidates[hi_index];
1113            let mut hi_value = hi.0;
1114            if self.angular && hi_value <= lo.0 {
1115                hi_value += TAU;
1116            }
1117            intervals.push(Interval {
1118                lo: lo.0,
1119                hi: hi_value,
1120                lo_source: lo.1,
1121                hi_source: hi.1,
1122            });
1123            k += 1;
1124        }
1125        intervals.sort_by(|a, b| a.lo.total_cmp(&b.lo));
1126        Ok(intervals)
1127    }
1128
1129    /// Critical points of the level over a source (tips and plateaus).
1130    /// The face's characteristic function: `det(∇o, ∇ℓ) / |∇ℓ|`, zero where
1131    /// the face's image turns back (its envelope), and the level there.
1132    fn characteristic(&self, source: Source, u: f64, v: f64) -> (f64, f64) {
1133        let (ur, vr, _) = self.domain(source);
1134        let hu = 1e-6 * (ur[1] - ur[0]).max(1e-3);
1135        let hv = 1e-6 * (vr[1] - vr[0]).max(1e-3);
1136        let (l, _) = self.source_reduced(source, u, v);
1137        let (lu1, ou1) = self.source_reduced(source, u + hu, v);
1138        let (lu0, ou0) = self.source_reduced(source, u - hu, v);
1139        let (lv1, ov1) = self.source_reduced(source, u, v + hv);
1140        let (lv0, ov0) = self.source_reduced(source, u, v - hv);
1141        let (lu, lv) = ((lu1 - lu0) / (2.0 * hu), (lv1 - lv0) / (2.0 * hv));
1142        let ou = self.o_difference(ou1, ou0) / (2.0 * hu);
1143        let ov = self.o_difference(ov1, ov0) / (2.0 * hv);
1144        ((ou * lv - ov * lu) / lu.hypot(lv).max(1e-300), l)
1145    }
1146
1147    /// FOLDS and KINKS of a face, recorded as its critical points so events snap
1148    /// to them and band ends read them exactly:
1149    /// - a FOLD is where the level is extremal along the face's own envelope
1150    ///   (`D = 0`): two extrema of `o` on one level contour annihilate there
1151    ///   (the plus wheel's lobes merging at ρ = 20, the tip of its arm's flat
1152    ///   end). Newton on {D = 0, ℓ_u·D_v − ℓ_v·D_u = 0}, seeded where the level
1153    ///   is locally extremal among the grid's crossings of D = 0.
1154    /// - a KINK is where the envelope runs into the face's own boundary and the
1155    ///   boundary's edge takes over: roots of D along each non-periodic side.
1156    fn folds_and_kinks(&self, source: Source, grid: &Grid, out: &mut Vec<(f64, f64)>, params: &mut Vec<(f64, f64)>) {
1157        let (ur, vr, v_periodic) = self.domain(source);
1158        let u_periodic = self.u_periodic(source);
1159        let (nu, nv) = (grid.nu, grid.nv);
1160        let mut d = vec![0.0; nu * nv];
1161        for i in 0..nu {
1162            for j in 0..nv {
1163                let (u, v) = Self::grid_param(grid, i, j);
1164                d[i * nv + j] = self.characteristic(source, u, v).0;
1165            }
1166        }
1167        // Crossings of D = 0 along grid edges: (i, j, u, v, level).
1168        let mut crossings: Vec<(usize, usize, f64, f64, f64)> = Vec::new();
1169        let jmax = if v_periodic { nv } else { nv - 1 };
1170        for i in 0..nu {
1171            for j in 0..jmax {
1172                let (a, b) = (d[i * nv + j], d[i * nv + (j + 1) % nv]);
1173                if a * b < 0.0 {
1174                    let w = a / (a - b);
1175                    let (u, v0) = Self::grid_param(grid, i, j);
1176                    let (_, v1) = Self::grid_param(grid, i, j + 1);
1177                    let v1 = if v_periodic && j + 1 == nv { vr[1] } else { v1 };
1178                    let v = v0 + (v1 - v0) * w;
1179                    crossings.push((i, j, u, v, self.source_reduced(source, u, v).0));
1180                }
1181            }
1182        }
1183        for i in 0..nu - 1 {
1184            for j in 0..nv {
1185                let (a, b) = (d[i * nv + j], d[(i + 1) * nv + j]);
1186                if a * b < 0.0 {
1187                    let w = a / (a - b);
1188                    let (u0, v) = Self::grid_param(grid, i, j);
1189                    let (u1, _) = Self::grid_param(grid, i + 1, j);
1190                    let u = u0 + (u1 - u0) * w;
1191                    crossings.push((i, j, u, v, self.source_reduced(source, u, v).0));
1192                }
1193            }
1194        }
1195        let mut buckets: std::collections::HashMap<(usize, usize), Vec<usize>> = std::collections::HashMap::new();
1196        for (k, c) in crossings.iter().enumerate() {
1197            buckets.entry((c.0, c.1)).or_default().push(k);
1198        }
1199        let ku = 1e-4 * (ur[1] - ur[0]);
1200        let kv = 1e-4 * (vr[1] - vr[0]);
1201        let fold = |u: f64, v: f64| -> [f64; 2] {
1202            let (dd, _) = self.characteristic(source, u, v);
1203            let du = (self.characteristic(source, u + ku, v).0 - self.characteristic(source, u - ku, v).0) / (2.0 * ku);
1204            let dv = (self.characteristic(source, u, v + kv).0 - self.characteristic(source, u, v - kv).0) / (2.0 * kv);
1205            let lu = (self.source_reduced(source, u + ku, v).0 - self.source_reduced(source, u - ku, v).0) / (2.0 * ku);
1206            let lv = (self.source_reduced(source, u, v + kv).0 - self.source_reduced(source, u, v - kv).0) / (2.0 * kv);
1207            let norm = (lu.hypot(lv) * du.hypot(dv)).max(1e-300);
1208            [dd, (lu * dv - lv * du) / norm]
1209        };
1210        for (k, &(i, j, u0, v0, level)) in crossings.iter().enumerate() {
1211            let mut is_min = true;
1212            let mut is_max = true;
1213            for di in [-1i64, 0, 1] {
1214                for dj in [-1i64, 0, 1] {
1215                    let i2 = i as i64 + di;
1216                    let j2 = if v_periodic { (j as i64 + dj).rem_euclid(nv as i64) } else { j as i64 + dj };
1217                    if i2 < 0 || j2 < 0 {
1218                        continue;
1219                    }
1220                    if let Some(list) = buckets.get(&(i2 as usize, j2 as usize)) {
1221                        for &m in list {
1222                            if m == k {
1223                                continue;
1224                            }
1225                            if crossings[m].4 < level {
1226                                is_min = false;
1227                            }
1228                            if crossings[m].4 > level {
1229                                is_max = false;
1230                            }
1231                        }
1232                    }
1233                }
1234            }
1235            if !(is_min || is_max) {
1236                continue;
1237            }
1238            let (mut u, mut v) = (u0, v0);
1239            let mut converged = false;
1240            for _ in 0..40 {
1241                let f = fold(u, v);
1242                let (su, sv) = (ku * 10.0, kv * 10.0);
1243                let fu1 = fold(u + su, v);
1244                let fu0 = fold(u - su, v);
1245                let fv1 = fold(u, v + sv);
1246                let fv0 = fold(u, v - sv);
1247                let j00 = (fu1[0] - fu0[0]) / (2.0 * su);
1248                let j01 = (fv1[0] - fv0[0]) / (2.0 * sv);
1249                let j10 = (fu1[1] - fu0[1]) / (2.0 * su);
1250                let j11 = (fv1[1] - fv0[1]) / (2.0 * sv);
1251                let det = j00 * j11 - j01 * j10;
1252                if !det.is_finite() || det.abs() < 1e-300 {
1253                    break;
1254                }
1255                let du = -(f[0] * j11 - f[1] * j01) / det;
1256                let dv = -(j00 * f[1] - j10 * f[0]) / det;
1257                // Stay near the seed: a fold is local to its crossing.
1258                let cap = 4.0 * ((ur[1] - ur[0]) / (nu as f64)).max((vr[1] - vr[0]) / (nv as f64));
1259                let scale = (du.hypot(dv) / cap).max(1.0);
1260                u += du / scale;
1261                v += dv / scale;
1262                if du.hypot(dv) < 1e-12 * (ur[1] - ur[0]).max(vr[1] - vr[0]) {
1263                    converged = true;
1264                    break;
1265                }
1266            }
1267            let f = fold(u, v);
1268            if !(converged || (f[0].abs() < 1e-9 && f[1].abs() < 1e-5)) {
1269                continue;
1270            }
1271            if u_periodic {
1272                u = ur[0] + (u - ur[0]).rem_euclid(ur[1] - ur[0]);
1273            }
1274            if v_periodic {
1275                v = vr[0] + (v - vr[0]).rem_euclid(vr[1] - vr[0]);
1276            }
1277            if u > ur[0] && u < ur[1] && (v_periodic || (v > vr[0] && v < vr[1])) {
1278                out.push(self.source_reduced(source, u, v));
1279                params.push((u, v));
1280            }
1281        }
1282        // Kinks: roots of D along each non-periodic side of the face.
1283        let mut sides: Vec<(bool, f64)> = Vec::new(); // (along v at fixed u, the fixed value)
1284        if !u_periodic {
1285            sides.push((true, ur[0]));
1286            sides.push((true, ur[1]));
1287        }
1288        if !v_periodic {
1289            sides.push((false, vr[0]));
1290            sides.push((false, vr[1]));
1291        }
1292        for (along_v, fixed) in sides {
1293            let (range, n) = if along_v { (vr, nv * 4) } else { (ur, nu * 4) };
1294            let at = |t: f64| if along_v { (fixed, t) } else { (t, fixed) };
1295            let value = |t: f64| {
1296                let (u, v) = at(t);
1297                self.characteristic(source, u, v).0
1298            };
1299            let mut previous = value(range[0]);
1300            for k in 1..=n {
1301                let t = range[0] + (range[1] - range[0]) * k as f64 / n as f64;
1302                let current = value(t);
1303                if previous * current < 0.0 {
1304                    let (mut a, mut b) = (t - (range[1] - range[0]) / n as f64, t);
1305                    let fa = previous;
1306                    for _ in 0..100 {
1307                        let m = 0.5 * (a + b);
1308                        if (value(m) < 0.0) == (fa < 0.0) {
1309                            a = m;
1310                        } else {
1311                            b = m;
1312                        }
1313                    }
1314                    let (u, v) = at(0.5 * (a + b));
1315                    out.push(self.source_reduced(source, u, v));
1316                    params.push((u, v));
1317                }
1318                previous = current;
1319            }
1320        }
1321    }
1322
1323    fn source_critical(&self, index: usize) -> (Vec<(f64, f64)>, Vec<(f64, f64)>) {
1324        let source = self.sources[index];
1325        let mut out = Vec::new();
1326        let mut params = Vec::new();
1327        if Self::is_face(source) {
1328            let grid = self.grids[index].as_ref().expect("face grid");
1329            let (ur, vr, periodic) = self.domain(source);
1330            let at = |i: usize, j: usize| grid.values[i * grid.nv + j].0;
1331            let u_periodic = self.u_periodic(source);
1332            // A periodic first parameter has its last row equal to its first.
1333            let rows = if u_periodic { grid.nu - 1 } else { grid.nu };
1334            for i in 0..rows {
1335                if !u_periodic && (i == 0 || i + 1 == grid.nu) {
1336                    continue;
1337                }
1338                for j in 0..grid.nv {
1339                    if !periodic && (j == 0 || j + 1 == grid.nv) {
1340                        continue;
1341                    }
1342                    let here = at(i, j);
1343                    let mut is_min = true;
1344                    let mut is_max = true;
1345                    for di in [-1i64, 0, 1] {
1346                        for dj in [-1i64, 0, 1] {
1347                            if di == 0 && dj == 0 {
1348                                continue;
1349                            }
1350                            let i2 = ((i as i64 + di).rem_euclid(rows as i64)) as usize;
1351                            let j2 = ((j as i64 + dj).rem_euclid(grid.nv as i64)) as usize;
1352                            let there = at(i2, j2);
1353                            if there < here {
1354                                is_min = false;
1355                            }
1356                            if there > here {
1357                                is_max = false;
1358                            }
1359                        }
1360                    }
1361                    if !(is_min || is_max) {
1362                        continue;
1363                    }
1364                    // Newton on ∇ℓ = 0.
1365                    let (mut u, mut v) = Self::grid_param(grid, i, j);
1366                    let hu = 1e-5 * (ur[1] - ur[0]);
1367                    let hv = 1e-5 * (vr[1] - vr[0]);
1368                    let level = |u: f64, v: f64| self.source_reduced(source, u, v).0;
1369                    for _ in 0..50 {
1370                        let f = level(u, v);
1371                        let fu = (level(u + hu, v) - level(u - hu, v)) / (2.0 * hu);
1372                        let fv = (level(u, v + hv) - level(u, v - hv)) / (2.0 * hv);
1373                        let fuu = (level(u + hu, v) - 2.0 * f + level(u - hu, v)) / (hu * hu);
1374                        let fvv = (level(u, v + hv) - 2.0 * f + level(u, v - hv)) / (hv * hv);
1375                        let fuv = (level(u + hu, v + hv) - level(u + hu, v - hv) - level(u - hu, v + hv)
1376                            + level(u - hu, v - hv))
1377                            / (4.0 * hu * hv);
1378                        let det = fuu * fvv - fuv * fuv;
1379                        if det.abs() < 1e-300 {
1380                            break;
1381                        }
1382                        let du = -(fu * fvv - fv * fuv) / det;
1383                        let dv = -(fuu * fv - fuv * fu) / det;
1384                        u += du;
1385                        v += dv;
1386                        if du.abs() < 1e-14 && dv.abs() < 1e-14 {
1387                            break;
1388                        }
1389                    }
1390                    if u_periodic {
1391                        u = ur[0] + (u - ur[0]).rem_euclid(ur[1] - ur[0]);
1392                    }
1393                    if periodic {
1394                        v = vr[0] + (v - vr[0]).rem_euclid(vr[1] - vr[0]);
1395                    }
1396                    if u >= ur[0] && u <= ur[1] && (periodic || (v >= vr[0] && v <= vr[1])) {
1397                        out.push(self.source_reduced(source, u, v));
1398                        params.push((u, v));
1399                    }
1400                }
1401            }
1402            self.folds_and_kinks(source, grid, &mut out, &mut params);
1403        } else {
1404            let (range, _, _) = self.domain(source);
1405            let n = 2048;
1406            let param = |k: usize| range[0] + (range[1] - range[0]) * k as f64 / n as f64;
1407            let values: Vec<f64> = (0..=n).map(|k| self.source_reduced(source, param(k), 0.0).0).collect();
1408            for k in 1..n {
1409                let (a, b, c) = (values[k - 1], values[k], values[k + 1]);
1410                if (b <= a && b <= c) || (b >= a && b >= c) {
1411                    let sign = if b <= a && b <= c { 1.0 } else { -1.0 };
1412                    let (mut lo, mut hi) = (param(k - 1), param(k + 1));
1413                    let ratio = 0.618_033_988_749_894_9;
1414                    for _ in 0..100 {
1415                        let c1 = hi - ratio * (hi - lo);
1416                        let d1 = lo + ratio * (hi - lo);
1417                        if sign * self.source_reduced(source, c1, 0.0).0 < sign * self.source_reduced(source, d1, 0.0).0 {
1418                            hi = d1;
1419                        } else {
1420                            lo = c1;
1421                        }
1422                    }
1423                    out.push(self.source_reduced(source, 0.5 * (lo + hi), 0.0));
1424                    params.push((0.5 * (lo + hi), 0.0));
1425                }
1426            }
1427        }
1428        (out, params)
1429    }
1430}
1431
1432/// Are two sources the same boundary piece of the sweep: the same source, or
1433/// a piece and the one that continues it across a set-periodic motion's wrap?
1434/// A face handing over to the edge that bounds it is NOT the same: the V
1435/// wheel's flank meets its tip circle's image at a kink, and fitting one curve
1436/// through it read the groove 1.5e-6 off (split: 1.1e-8).
1437fn same_or_bounding(engine: &Engine, a: usize, b: usize) -> bool {
1438    if a == b {
1439        return true;
1440    }
1441    let pieces = match (&engine.bar, engine.tool) {
1442        (Some(bar), _) => bar.piece_count(),
1443        (None, SweptTool::Revolved { meridian, .. }) => meridian.len(),
1444        (None, SweptTool::Prism { outline, .. }) => outline.len(),
1445        (None, SweptTool::Bar { section, .. }) => section.len(),
1446    };
1447    // (piece of the face, piece whose start the edge is)
1448    let face = |s: Source| match s {
1449        Source::RevolvedFace { piece } | Source::PrismFace { piece } | Source::ScrewPrismSide { piece } | Source::BarSide { piece } => Some(piece),
1450        _ => None,
1451    };
1452    let edge = |s: Source| match s {
1453        Source::RevolvedCorner { piece } | Source::PrismVertex { piece } | Source::ScrewPrismEdge { piece } | Source::BarEdge { piece } => Some(piece),
1454        _ => None,
1455    };
1456    let (sa, sb) = (engine.sources[a], engine.sources[b]);
1457    // Across the wrap, piece `k` continues as `wrap[k]`.
1458    let same_piece = |x: usize, y: usize| {
1459        x == y || engine.wrap.as_ref().is_some_and(|map| map[x] == y || map[y] == x)
1460    };
1461    let bounds = |f: usize, e: usize| {
1462        same_piece(e, f) || same_piece(e, (f + 1) % pieces)
1463    };
1464    let _ = bounds;
1465    match (face(sa), edge(sa), face(sb), edge(sb)) {
1466        (Some(f), _, Some(g), _) => same_piece(f, g),
1467        (_, Some(e), _, Some(g)) => same_piece(e, g),
1468        _ => false,
1469    }
1470}
1471
1472/// Do two interval lists describe the same structure (same count, each end on
1473/// the same source or one that hands over to it smoothly, matched in order)?
1474fn compatible(engine: &Engine, a: &[Interval], b: &[Interval]) -> bool {
1475    let angular = engine.angular;
1476    if a.len() != b.len() {
1477        return false;
1478    }
1479    // Match each interval of `a` to the one of `b` nearest its middle.
1480    let mut used = vec![false; b.len()];
1481    for x in a {
1482        let mid = 0.5 * (x.lo + x.hi);
1483        let mut best = None;
1484        let mut best_distance = f64::INFINITY;
1485        for (k, y) in b.iter().enumerate() {
1486            let other = 0.5 * (y.lo + y.hi);
1487            let d = if angular { wrap_pi(mid - other).abs() } else { (mid - other).abs() };
1488            if d < best_distance {
1489                best_distance = d;
1490                best = Some(k);
1491            }
1492        }
1493        let Some(k) = best else { return false };
1494        let y = &b[k];
1495        let overlap = if angular {
1496            let shift = (wrap_pi(y.lo - x.lo)) - (y.lo - x.lo);
1497            let (ylo, yhi) = (y.lo + shift, y.hi + shift);
1498            x.hi.min(yhi) - x.lo.max(ylo)
1499        } else {
1500            x.hi.min(y.hi) - x.lo.max(y.lo)
1501        };
1502        if used[k]
1503            || overlap < 0.0
1504            || !same_or_bounding(engine, x.lo_source, y.lo_source)
1505            || !same_or_bounding(engine, x.hi_source, y.hi_source)
1506        {
1507            return false;
1508        }
1509        used[k] = true;
1510    }
1511    true
1512}
1513
1514/// A boundary piece in reduced coordinates, as a polyline of exact samples
1515/// (the first and last are the piece's ends) with their `σ`.
1516struct Piece {
1517    points: Vec<(f64, f64)>,
1518    sigma: Vec<f64>,
1519    /// A straight level segment (built exactly, not fitted).
1520    level_segment: bool,
1521}
1522
1523/// Build the sweep of `tool` along `motion` inside `clip`, as one body per
1524/// connected region of the reduced section.
1525pub fn sweep_solid_within(
1526    tool: &SweptTool,
1527    motion: &SolidMotion,
1528    clip: &SweepClip,
1529) -> Result<Vec<BrepSolid>, KernelRefusal> {
1530    // A convex polygon's prism carried round a closed planar motion (turns
1531    // about axes along its own, ending where it starts: a planet on its
1532    // carrier): the plane region its section covers, found exactly and
1533    // extruded. It is the whole sweep, so it holds whatever lies in the clip.
1534    if let SweptTool::Prism { origin, normal, x_axis, outline, from, to } = tool {
1535        if motion.steps.len() >= 2 {
1536            let steps: Vec<(Vec3, Vec3, f64, f64)> = motion.steps.iter().map(|step| (step.axis_origin, step.axis_direction, step.turn, step.advance)).collect();
1537            if let Some(body) = crate::solid_sweep_caps::closed_planar_prism(*origin, *normal, *x_axis, outline, *from, *to, &steps, motion.from, motion.to)? {
1538                return Ok(vec![body]);
1539            }
1540        }
1541    }
1542    let narrowed: SweepClip;
1543    // --- Frame and classification.
1544    let ez = clip
1545        .axis_direction
1546        .normalized()
1547        .or_refuse(KernelStage::Collect, "clip_axis")?;
1548    let ex = clip
1549        .reference
1550        .sub(ez.scale(clip.reference.dot(ez)))
1551        .normalized()
1552        .or_refuse(KernelStage::Collect, "clip_reference")?;
1553    let frame = Frame { origin: clip.axis_origin, ex, ey: ez.cross(ex), ez };
1554    if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
1555        return Err(KernelRefusal::input(
1556            KernelStage::Collect,
1557            "motion_range",
1558            format!("{SOLID_SWEEP_REFUSAL}: the motion's range must run forwards"),
1559        ));
1560    }
1561    if motion.steps.is_empty() {
1562        return Err(KernelRefusal::input(KernelStage::Collect, "motion_empty", format!("{SOLID_SWEEP_REFUSAL}: no motion")));
1563    }
1564    let mut axes = Vec::with_capacity(motion.steps.len());
1565    for step in &motion.steps {
1566        axes.push(step.axis_direction.normalized().or_refuse(KernelStage::Collect, "step_axis")?);
1567    }
1568    if !(clip.radius[0] >= 0.0 && clip.radius[1] > clip.radius[0] && clip.axial[1] > clip.axial[0]) {
1569        return Err(KernelRefusal::input(
1570            KernelStage::Collect,
1571            "clip_range",
1572            format!("{SOLID_SWEEP_REFUSAL}: the clip's ranges must be increasing"),
1573        ));
1574    }
1575    let on_axis = |origin: Vec3, axis: Vec3| -> bool {
1576        let parallel = axis.cross(ez).length() < 1e-12;
1577        let offset = origin.sub(clip.axis_origin);
1578        parallel && offset.sub(ez.scale(offset.dot(ez))).length() < 1e-9 * (1.0 + clip.radius[1])
1579    };
1580    // One screw about the clip's axis, as its axial advance per radian about +ez.
1581    let screw_about_clip = || -> Option<f64> {
1582        let step = motion.steps.first()?;
1583        (motion.steps.len() == 1 && step.turn != 0.0 && step.advance != 0.0 && on_axis(step.axis_origin, axes[0])).then(|| {
1584            let sense = axes[0].dot(ez).signum();
1585            (step.advance * sense) / (step.turn * sense)
1586        })
1587    };
1588    let mut bar: Option<crate::solid_sweep_bar::Bar> = None;
1589    let class = 'class: { match tool {
1590        SweptTool::Bar { origin, normal, section, from, to, draft } => {
1591            let Some(c) = screw_about_clip() else {
1592                return Err(refuse("motion_class", "a bar is swept here only by one screw about the clip's axis".into()));
1593            };
1594            bar = Some(crate::solid_sweep_bar::Bar::new(*origin, *normal, section, *from, *to, *draft)?);
1595            Class::Screw(c)
1596        }
1597        SweptTool::Revolved { meridian, .. } => {
1598            validate_outline(meridian, "meridian")?;
1599            if motion.steps.len() != 1 || !on_axis(motion.steps[0].axis_origin, axes[0]) {
1600                return Err(refuse(
1601                    "motion_class",
1602                    "a solid of revolution is swept here only by one screw or turn about the clip's axis".into(),
1603                ));
1604            }
1605            let step = motion.steps[0];
1606            let sense = axes[0].dot(ez).signum();
1607            if step.turn == 0.0 {
1608                return Err(refuse("motion_class", "a slide of a solid of revolution is not built here".into()));
1609            }
1610            if step.advance == 0.0 {
1611                Class::Turn
1612            } else {
1613                // axial advance per radian about +ez
1614                Class::Screw((step.advance * sense) / (step.turn * sense))
1615            }
1616        }
1617        SweptTool::Prism { normal, outline, from, to, origin, x_axis } => {
1618            validate_outline(outline, "prism")?;
1619            let n = normal.normalized().or_refuse(KernelStage::Collect, "prism_normal")?;
1620            let screw = motion.steps.len() == 1
1621                && motion.steps[0].turn != 0.0
1622                && motion.steps[0].advance != 0.0
1623                && on_axis(motion.steps[0].axis_origin, axes[0])
1624                && n.cross(ez).length() <= 1e-12;
1625            if screw {
1626                // A screw carries the prism's ends along, so the clip may run past them.
1627                let step = motion.steps[0];
1628                let sense = axes[0].dot(ez).signum();
1629                break 'class Class::Screw((step.advance * sense) / (step.turn * sense));
1630            }
1631            if n.cross(ez).length() > 1e-12 {
1632                // Across the screw's axis the prism is a bar with no draft.
1633                if let Some(c) = screw_about_clip() {
1634                    let xa = x_axis.sub(n.scale(x_axis.dot(n))).normalized().or_refuse(KernelStage::Collect, "prism_x_axis")?;
1635                    let ya = n.cross(xa);
1636                    let at = |q: [f64; 2]| origin.add(xa.scale(q[0])).add(ya.scale(q[1]));
1637                    let mut section = Vec::with_capacity(outline.len());
1638                    for piece in outline {
1639                        section.push(match *piece {
1640                            OutlinePiece::Line { from, to } => make_line(at(from), at(to)),
1641                            // an arc run clockwise is one run the other way about the mirrored axis
1642                            OutlinePiece::Arc { centre, radius, start, end } if end >= start => make_arc(at(centre), xa, ya, radius, start, end),
1643                            OutlinePiece::Arc { centre, radius, start, end } => make_arc(at(centre), xa, ya.scale(-1.0), radius, -start, -end),
1644                        }
1645                        .or_refuse(KernelStage::Collect, "prism_outline")?);
1646                    }
1647                    bar = Some(crate::solid_sweep_bar::Bar::new(*origin, n, &section, *from, *to, 0.0)?);
1648                    break 'class Class::Screw(c);
1649                }
1650                return Err(refuse("motion_class", "a prism is swept here only along its own direction's clip axis".into()));
1651            }
1652            for (step, axis) in motion.steps.iter().zip(&axes) {
1653                let turn_ok = step.turn == 0.0 || axis.cross(n).length() < 1e-12;
1654                let advance_ok = step.advance == 0.0 || (step.turn == 0.0 && axis.dot(n).abs() < 1e-12);
1655                if !(turn_ok && advance_ok) {
1656                    return Err(refuse(
1657                        "motion_class",
1658                        "a prism is swept here only by turns about axes along it and slides across it".into(),
1659                    ));
1660                }
1661            }
1662            // The clip's axial range must lie within the prism's extent.
1663            let base = clip.axis_origin.sub(*origin).dot(n);
1664            let sense = ez.dot(n);
1665            let h0 = base + sense * clip.axial[0];
1666            let h1 = base + sense * clip.axial[1];
1667            if h0.min(h1) < *from || h0.max(h1) > *to {
1668                return Err(refuse(
1669                    "clip_past_prism",
1670                    "the clip reaches past the prism's ends, where the sweep is not a prism".into(),
1671                ));
1672            }
1673            Class::Planar
1674        }
1675    } };
1676    // A leaning end face folds into a wall of its own, which is not built.
1677    if let (Some(bar), Class::Screw(c)) = (&bar, class) {
1678        if bar.end_folds(clip.axis_origin, ez, c, clip.radius) {
1679            return Err(refuse(
1680                "bar_end_fold",
1681                "an end face of the bar leans to the screw's axis and folds inside the clip region, a wall this construction does not build".into(),
1682            ));
1683        }
1684    }
1685    let prism_height = match tool {
1686        SweptTool::Prism { from, to, .. } => 0.5 * (from + to),
1687        _ => 0.0,
1688    };
1689
1690    // Does the motion end where it began, as a set? For a prism, every outline
1691    // vertex at the last position must sit on some vertex at the first (the plus
1692    // turns 540°, which its half-turn symmetry makes a whole period). The
1693    // permutation says which piece continues which across the wrap.
1694    let wrap: Option<Vec<usize>> = match tool {
1695        SweptTool::Bar { .. } => None,
1696        SweptTool::Prism { .. } if matches!(class, Class::Screw(_)) => None,
1697        SweptTool::Prism { origin, normal, x_axis, outline, .. } => {
1698            let probe = Engine {
1699                tool,
1700                motion,
1701                axes: axes.clone(),
1702                frame,
1703                class,
1704                clip,
1705                bar: None,
1706                crest_gap: false,
1707                sources: Vec::new(),
1708                grids: Vec::new(),
1709                critical: Vec::new(),
1710                critical_params: Vec::new(),
1711                angular: true,
1712                prism_height,
1713                scale: 1.0,
1714                cache: std::cell::RefCell::new(std::collections::HashMap::new()),
1715                wrap: None,
1716                counters: std::cell::Cell::new((0, 0, 0, 0.0, 0.0)),
1717            };
1718            let n = normal.normalized_or(*normal);
1719            let xa = x_axis.normalized_or(*x_axis);
1720            let ya = n.cross(xa);
1721            let vertex = |k: usize, t: f64| {
1722                let q = outline[k].point(0.0);
1723                probe.motion_apply(t, origin.add(xa.scale(q[0])).add(ya.scale(q[1])).add(n.scale(prism_height)))
1724            };
1725            let size = scale_of(outline);
1726            let mut map = Vec::with_capacity(outline.len());
1727            for k in 0..outline.len() {
1728                let end = vertex(k, motion.to);
1729                match (0..outline.len()).find(|&j| vertex(j, motion.from).sub(end).length() < 1e-9 * size) {
1730                    Some(j) => map.push(j),
1731                    None => break,
1732                }
1733            }
1734            let consistent = map.len() == outline.len()
1735                && (0..outline.len()).all(|k| map[(k + 1) % outline.len()] == (map[k] + 1) % outline.len());
1736            consistent.then_some(map)
1737        }
1738        SweptTool::Revolved { .. } => None,
1739    };
1740    let periodic_motion = wrap.is_some();
1741    let mut sources = Vec::new();
1742    match tool {
1743        _ if bar.is_some() => {
1744            let bar = bar.as_ref().expect("bar");
1745            for piece in 0..bar.piece_count() {
1746                sources.push(Source::BarSide { piece });
1747                if !bar.periodic {
1748                    sources.push(Source::BarEdge { piece });
1749                }
1750                sources.push(Source::BarRim { piece, end: false });
1751                sources.push(Source::BarRim { piece, end: true });
1752            }
1753        }
1754        SweptTool::Bar { .. } => {}
1755        SweptTool::Revolved { meridian, .. } => {
1756            // A piece lying on the axis revolves into nothing, and a corner on the
1757            // axis into a point: neither bounds the tool.
1758            let on_axis = |p: [f64; 2]| p[0].abs() <= 1e-12 * scale_of(meridian);
1759            for piece in 0..meridian.len() {
1760                let lies_on_axis = matches!(meridian[piece], OutlinePiece::Line { from, to } if on_axis(from) && on_axis(to));
1761                if !lies_on_axis {
1762                    sources.push(Source::RevolvedFace { piece });
1763                }
1764                if !meridian[piece].is_full_circle() && !on_axis(meridian[piece].point(0.0)) {
1765                    sources.push(Source::RevolvedCorner { piece });
1766                }
1767            }
1768        }
1769        SweptTool::Prism { outline, .. } if matches!(class, Class::Screw(_)) => {
1770            for piece in 0..outline.len() {
1771                sources.push(Source::ScrewPrismSide { piece });
1772                if !outline[piece].is_full_circle() {
1773                    sources.push(Source::ScrewPrismEdge { piece });
1774                }
1775                sources.push(Source::ScrewPrismRim { piece, end: false });
1776                sources.push(Source::ScrewPrismRim { piece, end: true });
1777            }
1778        }
1779        SweptTool::Prism { outline, .. } => {
1780            for piece in 0..outline.len() {
1781                sources.push(Source::PrismFace { piece });
1782                if !outline[piece].is_full_circle() {
1783                    sources.push(Source::PrismVertex { piece });
1784                }
1785                if !periodic_motion {
1786                    sources.push(Source::PrismEnd { piece, end: false });
1787                    sources.push(Source::PrismEnd { piece, end: true });
1788                }
1789            }
1790        }
1791    }
1792    let scale = clip.radius[1].max(1.0);
1793    let mut engine = Engine {
1794        tool,
1795        motion,
1796        axes,
1797        frame,
1798        class,
1799        clip,
1800        bar,
1801        crest_gap: false,
1802        sources,
1803        grids: Vec::new(),
1804        critical: Vec::new(),
1805        critical_params: Vec::new(),
1806        angular: class != Class::Turn,
1807        prism_height,
1808        scale,
1809        cache: std::cell::RefCell::new(std::collections::HashMap::new()),
1810        wrap,
1811        counters: std::cell::Cell::new((0, 0, 0, 0.0, 0.0)),
1812    };
1813    engine.grids = engine
1814        .sources
1815        .iter()
1816        .map(|source| if Engine::is_face(*source) { Some(engine.build_grid(*source)) } else { None })
1817        .collect();
1818    let critical: Vec<_> = (0..engine.sources.len()).map(|k| engine.source_critical(k)).collect();
1819    engine.critical_params = critical.iter().map(|c| c.1.clone()).collect();
1820    engine.critical = critical.into_iter().map(|c| c.0).collect();
1821    if let (SweptTool::Revolved { axis_origin, axis_direction, meridian, .. }, true) = (tool, apex_tip_on()) {
1822        let axis = axis_direction.normalized_or(*axis_direction);
1823        let count = meridian.len();
1824        for piece in 0..count {
1825            let corner = meridian[piece].point(0.0);
1826            if corner[0].abs() > 1e-12 * scale_of(meridian) {
1827                continue;
1828            }
1829            let apex = engine.reduce(engine.frame.local(axis_origin.add(axis.scale(corner[1]))));
1830            // the faces on either side of the corner
1831            for neighbour in [piece, (piece + count - 1) % count] {
1832                if let Some(index) = engine.sources.iter().position(|source| matches!(source, Source::RevolvedFace { piece } if *piece == neighbour)) {
1833                    engine.critical[index].push(apex);
1834                }
1835            }
1836        }
1837    }
1838
1839    // --- Ends: a screw or turn must not reach the clip at either end.
1840    if matches!(class, Class::Screw(_) | Class::Turn) {
1841        check_ends_clear(&engine)?;
1842    }
1843
1844    // --- A screw whose grooves meet: above a crest level nothing stays. Build
1845    //     what stays below it, and take that from the clip at the end.
1846    let mut crest = None;
1847    if matches!(class, Class::Screw(_)) && clip.radius[0] == 0.0 && clip.angle.is_none() && whole_level_on() {
1848        crest = crest_level(&engine)?;
1849        if let Some(level) = crest {
1850            narrowed = SweepClip { radius: [0.0, level], ..clip.clone() };
1851            engine.clip = &narrowed;
1852            engine.crest_gap = true;
1853        }
1854    }
1855
1856    // --- Scan the levels for events.
1857    let (l0, l1) = (engine.clip.radius[0], engine.clip.radius[1]);
1858    let scan = 192;
1859    let mut levels: Vec<f64> = (0..=scan).map(|k| l0 + (l1 - l0) * k as f64 / scan as f64).collect();
1860    // Never sample exactly on a critical level: nudge the scan off them.
1861    for level in &mut levels {
1862        for critical in engine.critical.iter().flatten() {
1863            if (critical.0 - *level).abs() < 1e-9 * scale {
1864                *level += 1e-7 * (l1 - l0);
1865            }
1866        }
1867    }
1868    let mut structure = Vec::with_capacity(levels.len());
1869    for &level in &levels {
1870        structure.push(engine.intervals_at(level)?);
1871    }
1872    let debug = std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok();
1873    let mut breaks = vec![l0];
1874    for k in 0..scan {
1875        find_events(&engine, levels[k], &structure[k], levels[k + 1], &structure[k + 1], &mut breaks, 0)?;
1876    }
1877    breaks.push(l1);
1878    // Snap each event to a critical level of a source when one is that close.
1879    // A birth or death is found by bisection only to where the seeding first
1880    // sees the level's contour, which near a tip is a √ away from it: the
1881    // critical level is the exact one.
1882    let last = breaks.len() - 1;
1883    for level in breaks[1..last].iter_mut() {
1884        let mut nearest = *level;
1885        let mut distance = 1e-5 * scale;
1886        for critical in engine.critical.iter().flatten() {
1887            if (critical.0 - *level).abs() < distance {
1888                distance = (critical.0 - *level).abs();
1889                nearest = critical.0;
1890            }
1891        }
1892        *level = nearest;
1893    }
1894    breaks.sort_by(|a, b| a.total_cmp(b));
1895    // A source handing over to the next one at an edge can flicker over a few
1896    // bisection steps (the face's extremum sits a hair inside its domain); the
1897    // bands that leaves are far below any feature. Keep the first break of each
1898    // cluster, and the clip's own ends.
1899    let mut kept: Vec<f64> = Vec::with_capacity(breaks.len());
1900    for (index, &level) in breaks.iter().enumerate() {
1901        let is_end = index == 0 || index + 1 == breaks.len();
1902        match kept.last() {
1903            Some(&previous) if level - previous < 1e-5 * scale => {
1904                if is_end {
1905                    kept.pop();
1906                    kept.push(level);
1907                }
1908            }
1909            _ => kept.push(level),
1910        }
1911    }
1912    let mut breaks = kept;
1913
1914    // --- Merges no critical point explains: a FOLD the face's own Newton cannot
1915    //     reach (the plus wheel's arm tip: its level varies by 1e-4 along the
1916    //     envelope there). The gap between the two merging ends closes as
1917    //     √(ℓf − ℓ), so gap² is smooth in ℓ: fit it as a quadratic through three
1918    //     levels below the event, outside the band where the extremum Newton
1919    //     flickers, and take its root as the merge level; the gap's middle,
1920    //     extrapolated the same way, is the merge point. Both ends' sources
1921    //     record it as a critical point, and the bands keep their samples away
1922    //     from it (`fold_ends`).
1923    let mut fold_ends: Vec<f64> = Vec::new();
1924    for index in 1..breaks.len().saturating_sub(1) {
1925        let level = breaks[index];
1926        let snapped = engine.critical.iter().flatten().any(|c| (c.0 - level).abs() < 1e-9 * scale);
1927        if snapped {
1928            continue;
1929        }
1930        let room = (level - breaks[index - 1]).min(breaks[index + 1] - level);
1931        // Close enough that the √ law holds to the fit's order, far enough to be
1932        // clear of the flicker (the plus wheel: 2e-4 out, flicker inside 1e-5).
1933        let delta = (5e-6 * scale).min(room / 8.0);
1934        let below = engine.intervals_at(level - delta)?;
1935        let above = engine.intervals_at(level + delta)?;
1936        if below.len() <= above.len() {
1937            continue;
1938        }
1939        // Adjacent intervals below whose facing ends close into one above.
1940        let mut refined: Vec<(f64, f64, usize, usize)> = Vec::new();
1941        for k in 0..below.len() {
1942            let (x, y) = (below[k], below[(k + 1) % below.len()]);
1943            if !engine.angular && k + 1 == below.len() {
1944                break;
1945            }
1946            let gap_at = |intervals: &[Interval]| -> Option<(f64, f64)> {
1947                // the pair nearest (x.hi, y.lo) at this level
1948                let mut best: Option<(f64, f64, f64)> = None;
1949                for i in 0..intervals.len() {
1950                    let (p, q) = (intervals[i], intervals[(i + 1) % intervals.len()]);
1951                    let d = engine.o_difference(p.hi, x.hi).abs() + engine.o_difference(q.lo, y.lo).abs();
1952                    if best.map_or(true, |b| d < b.2) {
1953                        let gap = engine.o_difference(q.lo, p.hi);
1954                        best = Some((gap, p.hi + 0.5 * gap, d));
1955                    }
1956                }
1957                best.map(|b| (b.0, b.1))
1958            };
1959            let mut samples = Vec::new();
1960            for factor in [1.0, 2.0, 4.0] {
1961                let l = level - delta * factor;
1962                let intervals = engine.intervals_at(l)?;
1963                if intervals.len() != below.len() {
1964                    break;
1965                }
1966                if let Some((gap, middle)) = gap_at(&intervals) {
1967                    samples.push((l, gap, middle));
1968                }
1969            }
1970            if samples.len() < 3 || samples.iter().any(|s| s.1 <= 0.0 || s.1 > 0.5) {
1971                continue;
1972            }
1973            // Quadratic through (l, gap²); its root above the samples.
1974            let quad = |values: [f64; 3]| -> (f64, f64, f64) {
1975                let (x0, x1, x2) = (samples[0].0, samples[1].0, samples[2].0);
1976                let (y0, y1, y2) = (values[0], values[1], values[2]);
1977                let d01 = (y0 - y1) / (x0 - x1);
1978                let d12 = (y1 - y2) / (x1 - x2);
1979                let a2 = (d01 - d12) / (x0 - x2);
1980                let a1 = d01 - a2 * (x0 + x1);
1981                let a0 = y0 - a1 * x0 - a2 * x0 * x0;
1982                (a0, a1, a2)
1983            };
1984            let (c0, c1, c2) = quad([samples[0].1.powi(2), samples[1].1.powi(2), samples[2].1.powi(2)]);
1985            let root = if c2.abs() < 1e-300 {
1986                -c0 / c1
1987            } else {
1988                let disc = c1 * c1 - 4.0 * c2 * c0;
1989                if disc < 0.0 {
1990                    continue;
1991                }
1992                let r1 = (-c1 + disc.sqrt()) / (2.0 * c2);
1993                let r2 = (-c1 - disc.sqrt()) / (2.0 * c2);
1994                if (r1 - level).abs() < (r2 - level).abs() { r1 } else { r2 }
1995            };
1996            if !(root > samples[0].0 && (root - level).abs() < delta) {
1997                continue;
1998            }
1999            let (m0, m1, m2) = quad([samples[0].2, samples[1].2, samples[2].2]);
2000            let middle = m0 + m1 * root + m2 * root * root;
2001            refined.push((root, middle, x.hi_source, y.lo_source));
2002        }
2003        if !refined.is_empty() {
2004            // Every merging pair records its own point; the break is their mean
2005            // level (equal to round-off where the spaces are copies of one).
2006            let root = refined.iter().map(|r| r.0).sum::<f64>() / refined.len() as f64;
2007            for &(own, middle, a_source, b_source) in &refined {
2008                if debug {
2009                    eprintln!("  fold: break {level:.12} -> {own:.12} at o {middle:.12}");
2010                }
2011                engine.critical[a_source].push((root, middle));
2012                engine.critical[b_source].push((root, middle));
2013            }
2014            breaks[index] = root;
2015            fold_ends.push(root);
2016        }
2017    }
2018
2019    if debug {
2020        eprintln!("solid sweep: after events {:?} breaks {}", engine.counters.get(), breaks.len());
2021    }
2022    // --- Sample each band's interval ends.
2023    let mut pieces: Vec<Piece> = Vec::new();
2024    // Per band: the intervals at its bottom and top (for the level segments).
2025    let mut band_ends: Vec<(f64, f64, Vec<(usize, usize)>)> = Vec::new();
2026    for window in breaks.windows(2) {
2027        let (a, b) = (window[0], window[1]);
2028        if b - a < 1e-12 * scale {
2029            continue;
2030        }
2031        let mid = engine.intervals_at(0.5 * (a + b))?;
2032        if mid.is_empty() {
2033            continue;
2034        }
2035        let (band_pieces, _, _) = sample_band(&engine, a, b, &mid, &fold_ends)?;
2036        let first = pieces.len();
2037        let pairs = (0..band_pieces.len() / 2).map(|i| (first + 2 * i, first + 2 * i + 1)).collect();
2038        pieces.extend(band_pieces);
2039        band_ends.push((a, b, pairs));
2040    }
2041    if pieces.is_empty() {
2042        return Ok(Vec::new());
2043    }
2044    if debug {
2045        eprintln!("solid sweep: after bands {:?}", engine.counters.get());
2046        for (k, critical) in engine.critical.iter().enumerate() {
2047            eprintln!("  source {k} {:?}: critical {:?}", engine.sources[k], critical);
2048        }
2049    }
2050
2051    // --- One value per interval end at each break. The band below and the band
2052    //     above read an end that continues across a break from their own
2053    //     sources, at a level found only to the flicker cluster; the two agree to
2054    //     far below any feature but not to the bit, and a sliver of level segment
2055    //     between them is an edge no solid should carry. Snap every end at a level
2056    //     to its cluster's first value (ends of one interval meeting at a tip
2057    //     included).
2058    let snap_length = 1e-5 * scale;
2059    let mut break_levels: Vec<f64> = band_ends.iter().flat_map(|e| [e.0, e.1]).collect();
2060    break_levels.sort_by(|a, b| a.total_cmp(b));
2061    break_levels.dedup_by(|b, a| (*b - *a).abs() < 1e-12 * scale);
2062    for &level in &break_levels {
2063        let tolerance = if engine.angular { snap_length / level.max(1e-12) } else { snap_length };
2064        let mut ends: Vec<(usize, bool)> = Vec::new();
2065        for (index, piece) in pieces.iter().enumerate() {
2066            if (piece.points[0].0 - level).abs() < 1e-12 * scale {
2067                ends.push((index, false));
2068            }
2069            if (piece.points.last().expect("nonempty").0 - level).abs() < 1e-12 * scale {
2070                ends.push((index, true));
2071            }
2072        }
2073        let value = |pieces: &Vec<Piece>, (index, last): (usize, bool)| {
2074            if last { pieces[index].points.last().expect("nonempty").1 } else { pieces[index].points[0].1 }
2075        };
2076        for i in 0..ends.len() {
2077            let anchor = value(&pieces, ends[i]);
2078            for j in i + 1..ends.len() {
2079                let other = value(&pieces, ends[j]);
2080                let d = engine.o_difference(other, anchor);
2081                if d.abs() < tolerance && d != 0.0 {
2082                    let (index, last) = ends[j];
2083                    let target = other - d;
2084                    let points = &mut pieces[index].points;
2085                    if last {
2086                        points.last_mut().expect("nonempty").1 = target;
2087                    } else {
2088                        points[0].1 = target;
2089                    }
2090                }
2091            }
2092        }
2093    }
2094
2095    // --- Level segments: where the intervals above and below a level differ.
2096    let mut all_levels: Vec<f64> = band_ends.iter().flat_map(|e| [e.0, e.1]).collect();
2097    all_levels.sort_by(|a, b| a.total_cmp(b));
2098    all_levels.dedup_by(|b, a| (*b - *a).abs() < 1e-12 * scale);
2099    for &level in &all_levels {
2100        let mut below: Vec<(f64, f64)> = Vec::new();
2101        let mut above: Vec<(f64, f64)> = Vec::new();
2102        for (a, b, pairs) in &band_ends {
2103            for &(lo, hi) in pairs {
2104                let (lo, hi) = (&pieces[lo].points, &pieces[hi].points);
2105                if (b - level).abs() < 1e-12 * scale {
2106                    below.push((lo.last().expect("nonempty").1, hi.last().expect("nonempty").1));
2107                }
2108                if (a - level).abs() < 1e-12 * scale {
2109                    above.push((lo[0].1, hi[0].1));
2110                }
2111            }
2112        }
2113        let tolerance = if engine.angular { 1e-9 * scale / level.max(1e-12) } else { 1e-9 * scale };
2114        for (lo, hi) in symmetric_difference(&below, &above, engine.angular, tolerance) {
2115            let steps = 2;
2116            pieces.push(Piece {
2117                points: (0..=steps)
2118                    .map(|k| (level, lo + (hi - lo) * k as f64 / steps as f64))
2119                    .collect(),
2120                sigma: (0..=steps).map(|k| k as f64 / steps as f64).collect(),
2121                level_segment: true,
2122            });
2123        }
2124    }
2125
2126    if std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
2127        eprintln!("solid sweep: breaks {breaks:?}");
2128        for piece in &pieces {
2129            let a = piece.points[0];
2130            let b = *piece.points.last().expect("nonempty");
2131            eprintln!(
2132                "  piece {} ({:.9}, {:.9}) -> ({:.9}, {:.9}) n={}",
2133                if piece.level_segment { "LEVEL" } else { "edge " },
2134                a.0, a.1, b.0, b.1, piece.points.len()
2135            );
2136            if std::env::var("BREP_DEBUG_SOLID_SWEEP").as_deref() == Ok("2") {
2137                for p in piece.points.iter().take(6) {
2138                    eprintln!("      {:.12} {:.12}", p.0, p.1);
2139                }
2140            }
2141        }
2142    }
2143    // --- At a crest the walls have met: the top arc is no boundary of what stays.
2144    if let Some(level) = crest {
2145        pieces.retain(|piece| !(piece.level_segment && (piece.points[0].0 - level).abs() < 1e-9 * scale));
2146    }
2147    // --- Assemble loops and build the bodies.
2148    let loops = assemble_loops(&engine, pieces)?;
2149    let mut bodies = Vec::new();
2150    for pieces in loops {
2151        bodies.push(build_body(&engine, &pieces)?);
2152    }
2153    if crest.is_some() {
2154        let [kept] = bodies.as_slice() else {
2155            return Err(refuse("whole_level", "what stays below the crest is not one body".into()));
2156        };
2157        return clip_less(clip, frame_base(&engine), kept);
2158    }
2159    Ok(bodies)
2160}
2161
2162/// Replace a screw loft's side surfaces and helical edges by quintic splines
2163/// through the exact screw and its first two derivatives. A cubic interpolant
2164/// through `segments + 1` sections misses a turn by h⁴; these by h⁶, which is
2165/// what lets a long fine thread be built with few spans. Sections, caps and
2166/// parameters are the loft's, so the trims stay as they are.
2167fn carry_along_screw(body: &mut BrepSolid, engine: &Engine, c: f64, span: f64, segments: usize) -> Result<(), KernelRefusal> {
2168    let origin = engine.clip.axis_origin;
2169    let ez = engine.frame.ez;
2170    // The six Bézier points of each span collapse to three a span, C² at the joints.
2171    let carry = |start: Vec3| -> Vec<Vec3> {
2172        let h = span / segments as f64;
2173        let axial = ez.scale(start.sub(origin).dot(ez));
2174        let radial = start.sub(origin).sub(axial);
2175        let at = |k: usize| {
2176            let angle = h * k as f64;
2177            let r = radial.rotate_about(ez, angle);
2178            let value = origin.add(axial).add(r).add(ez.scale(c * angle));
2179            (value, ez.cross(r).add(ez.scale(c)), r.scale(-1.0))
2180        };
2181        let piece = |k: usize| {
2182            let ((f0, d0, a0), (f1, d1, a1)) = (at(k), at(k + 1));
2183            [
2184                f0,
2185                f0.add(d0.scale(h / 5.0)),
2186                f0.add(d0.scale(2.0 * h / 5.0)).add(a0.scale(h * h / 20.0)),
2187                f1.sub(d1.scale(2.0 * h / 5.0)).add(a1.scale(h * h / 20.0)),
2188                f1.sub(d1.scale(h / 5.0)),
2189                f1,
2190            ]
2191        };
2192        let mut points = Vec::with_capacity(3 * segments + 3);
2193        let first = piece(0);
2194        points.extend_from_slice(&first[..3]);
2195        for k in 0..segments - 1 {
2196            let (here, next) = (piece(k), piece(k + 1));
2197            points.push(here[3]);
2198            points.push(here[4].scale(2.0).sub(here[3]));
2199            points.push(next[2]);
2200        }
2201        let last = piece(segments - 1);
2202        points.extend_from_slice(&last[3..]);
2203        points
2204    };
2205    let knots = |lo: f64, hi: f64| -> Vec<f64> {
2206        let mut knots = vec![lo; 6];
2207        for k in 1..segments {
2208            knots.extend([lo + (hi - lo) * k as f64 / segments as f64; 3]);
2209        }
2210        knots.extend([hi; 6]);
2211        knots
2212    };
2213    let point = |p: &crate::Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
2214    let moved = |p: &crate::Vec4, angle: f64| -> Vec3 {
2215        rotate(point(p), origin, ez, angle).add(ez.scale(c * angle))
2216    };
2217    let tolerance = 1e-7 * engine.scale;
2218    for face in body.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
2219        let rows = &face.surface.control_points;
2220        if rows[0].len() != segments + 1 {
2221            continue; // a cap
2222        }
2223        // The loft's columns must already be this screw, from section to section.
2224        if rows.iter().any(|row| moved(&row[0], span).sub(point(&row[segments])).length() > tolerance) {
2225            return Err(refuse("screw_loft", "a lofted wall does not follow the screw".into()));
2226        }
2227        let lifted: Vec<Vec<crate::Vec4>> = rows
2228            .iter()
2229            .map(|row| {
2230                let w = row[0].w;
2231                carry(point(&row[0])).into_iter().map(|q| crate::Vec4::from_point(q, w)).collect()
2232            })
2233            .collect();
2234        let v = &face.surface.knots_v;
2235        let (lo, hi) = (v[0], *v.last().expect("knots"));
2236        face.surface = crate::NurbsSurface::new(face.surface.degree_u, 5, face.surface.knots_u.clone(), knots(lo, hi), lifted)
2237            .or_refuse(KernelStage::Fragment, "screw_surface")?;
2238    }
2239    let height = c * span;
2240    let points: rustc_hash::FxHashMap<u64, Vec3> = body.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
2241    for edge in &mut body.edges {
2242        let (from, to) = (points[&edge.start_vertex_id], points[&edge.end_vertex_id]);
2243        let rise = to.sub(from).dot(ez);
2244        // An edge in a cap rises nothing, a carried one the whole height: told apart
2245        // well inside the height itself, however short the clip against its radius.
2246        if (rise.abs() - height.abs()).abs() > tolerance.min(0.25 * height.abs()) {
2247            continue; // lies in a cap
2248        }
2249        let domain = edge.curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
2250        let forward = rise * height > 0.0;
2251        let mut path = carry(if forward { from } else { to });
2252        if !forward {
2253            path.reverse();
2254        }
2255        edge.curve = NurbsCurve::new(5, knots(domain[0], domain[1]), path.into_iter().map(|q| crate::Vec4::from_point(q, 1.0)).collect())
2256            .or_refuse(KernelStage::Fragment, "screw_edge")?;
2257    }
2258    Ok(())
2259}
2260
2261/// `rows` copies of `row` along the screw, each the image of the last, sharing
2262/// the section edges and vertices between neighbours; only the first bottom cap
2263/// and the last top cap stay.
2264fn stack_screw_rows(
2265    row: &BrepSolid,
2266    engine: &Engine,
2267    c: f64,
2268    span: f64,
2269    segments: usize,
2270    rows: usize,
2271) -> Result<BrepSolid, KernelRefusal> {
2272    let origin = engine.clip.axis_origin;
2273    let ez = engine.frame.ez;
2274    let moved = |x: Vec3, copy: usize| -> Vec3 {
2275        let angle = span * copy as f64;
2276        rotate(x, origin, ez, angle).add(ez.scale(c * angle))
2277    };
2278    let tolerance = 1e-7 * engine.scale;
2279    let height = |x: Vec3| x.sub(origin).dot(ez);
2280    let points: rustc_hash::FxHashMap<u64, Vec3> = row.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
2281    let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
2282    for vertex in &row.vertices {
2283        low = low.min(height(vertex.point));
2284        high = high.max(height(vertex.point));
2285    }
2286    let at = |id: u64, level: f64| (height(points[&id]) - level).abs() <= tolerance;
2287    let in_level = |edge: &crate::topology::EdgeRecord, level: f64| at(edge.start_vertex_id, level) && at(edge.end_vertex_id, level);
2288    let (bottom, top) = if c * span > 0.0 { (low, high) } else { (high, low) };
2289    // Each bottom vertex and edge of a copy is a top one of the copy before.
2290    let mut vertex_below: rustc_hash::FxHashMap<u64, u64> = Default::default();
2291    for vertex in row.vertices.iter().filter(|vertex| at(vertex.id, bottom)) {
2292        let up = moved(vertex.point, 1);
2293        let below = row.vertices.iter().find(|other| at(other.id, top) && other.point.sub(up).length() <= tolerance);
2294        let Some(below) = below else { return Err(refuse("screw_rows", "a row's section does not meet the next".into())) };
2295        vertex_below.insert(vertex.id, below.id);
2296    }
2297    let mut edge_below: rustc_hash::FxHashMap<u64, u64> = Default::default();
2298    for edge in row.edges.iter().filter(|edge| in_level(edge, bottom)) {
2299        let ends = (vertex_below[&edge.start_vertex_id], vertex_below[&edge.end_vertex_id]);
2300        let below = row.edges.iter().find(|other| in_level(other, top) && (other.start_vertex_id, other.end_vertex_id) == ends);
2301        let Some(below) = below else { return Err(refuse("screw_rows", "a row's section edge does not meet the next".into())) };
2302        edge_below.insert(edge.id, below.id);
2303    }
2304    let face_ids = row.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| {
2305        std::iter::once(face.id).chain(face.loops.iter().flat_map(|l| std::iter::once(l.id).chain(l.coedges.iter().map(|c| c.id))))
2306    });
2307    let stride = row
2308        .vertices
2309        .iter()
2310        .map(|v| v.id)
2311        .chain(row.edges.iter().map(|e| e.id))
2312        .chain(face_ids)
2313        .max()
2314        .unwrap_or(0)
2315        + 1;
2316    let vertex_id = |id: u64, copy: usize| match vertex_below.get(&id) {
2317        Some(&below) if copy > 0 => below + stride * (copy as u64 - 1),
2318        _ => id + stride * copy as u64,
2319    };
2320    let edge_id = |id: u64, copy: usize| match edge_below.get(&id) {
2321        Some(&below) if copy > 0 => below + stride * (copy as u64 - 1),
2322        _ => id + stride * copy as u64,
2323    };
2324    let is_cap = |face: &crate::FaceRecord| face.surface.control_points[0].len() != 3 * segments + 3;
2325    let cap_level = |face: &crate::FaceRecord, level: f64| {
2326        face.loops.iter().flat_map(|l| &l.coedges).all(|coedge| {
2327            row.edges.iter().find(|edge| edge.id == coedge.edge_id).is_some_and(|edge| in_level(edge, level))
2328        })
2329    };
2330    let mut stacked = row.clone();
2331    stacked.mass_properties_cache = Default::default();
2332    stacked.vertices.clear();
2333    stacked.edges.clear();
2334    for shell in &mut stacked.shells {
2335        shell.faces.clear();
2336    }
2337    for copy in 0..rows {
2338        for vertex in &row.vertices {
2339            if copy == 0 || !vertex_below.contains_key(&vertex.id) {
2340                stacked.vertices.push(crate::topology::VertexRecord { id: vertex_id(vertex.id, copy), point: moved(vertex.point, copy) });
2341            }
2342        }
2343        for edge in &row.edges {
2344            if copy == 0 || !edge_below.contains_key(&edge.id) {
2345                stacked.edges.push(crate::topology::EdgeRecord {
2346                    id: edge_id(edge.id, copy),
2347                    curve: transform_curve(&edge.curve, |x| moved(x, copy))?,
2348                    t0: edge.t0,
2349                    t1: edge.t1,
2350                    start_vertex_id: vertex_id(edge.start_vertex_id, copy),
2351                    end_vertex_id: vertex_id(edge.end_vertex_id, copy),
2352                    degenerate: edge.degenerate,
2353                    name: edge.name.clone(),
2354                });
2355            }
2356        }
2357        for (target, shell) in stacked.shells.iter_mut().zip(&row.shells) {
2358            for face in &shell.faces {
2359                if is_cap(face) && !((copy == 0 && cap_level(face, bottom)) || (copy + 1 == rows && cap_level(face, top))) {
2360                    continue;
2361                }
2362                let control_points = face
2363                    .surface
2364                    .control_points
2365                    .iter()
2366                    .map(|line| {
2367                        line.iter()
2368                            .map(|p| {
2369                                let w = p.w;
2370                                crate::Vec4::from_point(moved(Vec3::new(p.x / w, p.y / w, p.z / w), copy), w)
2371                            })
2372                            .collect()
2373                    })
2374                    .collect();
2375                let surface = crate::NurbsSurface::new(
2376                    face.surface.degree_u,
2377                    face.surface.degree_v,
2378                    face.surface.knots_u.clone(),
2379                    face.surface.knots_v.clone(),
2380                    control_points,
2381                )
2382                .or_refuse(KernelStage::Fragment, "screw_rows")?;
2383                let mut copied = face.clone();
2384                copied.surface = surface;
2385                copied.id += stride * copy as u64;
2386                for loop_record in &mut copied.loops {
2387                    loop_record.id += stride * copy as u64;
2388                    for coedge in &mut loop_record.coedges {
2389                        coedge.id += stride * copy as u64;
2390                        coedge.edge_id = edge_id(coedge.edge_id, copy);
2391                    }
2392                }
2393                target.faces.push(copied);
2394            }
2395        }
2396    }
2397    let issues = stacked.validate();
2398    if issues.iter().any(|issue| issue.severity == "error") {
2399        return Err(refuse("screw_rows", format!("the stacked thread is invalid: {issues:?}")));
2400    }
2401    Ok(stacked)
2402}
2403
2404/// Where the clip's solid starts, on its axis.
2405fn frame_base(engine: &Engine) -> Vec3 {
2406    engine.frame.world([0.0, 0.0, engine.clip.axial[0]])
2407}
2408
2409/// The whole clip cylinder with `kept` taken out of it.
2410fn clip_less(clip: &SweepClip, base: Vec3, kept: &BrepSolid) -> Result<Vec<BrepSolid>, KernelRefusal> {
2411    let direction = clip.axis_direction.normalized().or_refuse(KernelStage::Collect, "clip_axis")?;
2412    let cylinder = crate::make_cylinder_brep(base, direction, clip.radius[1], clip.axial[1] - clip.axial[0])
2413        .or_refuse(KernelStage::Fragment, "clip_cylinder")?;
2414    if thread_rows_on() {
2415        if let Some(direct) = clip_less_direct(&cylinder, base, direction, kept)? {
2416            return Ok(vec![direct]);
2417        }
2418    }
2419    let r = crate::boolean_operation(&cylinder, kept, crate::BooleanOperation::Subtract, &Default::default())?;
2420    Ok(vec![r])
2421}
2422
2423/// `cylinder` with `kept` taken out, where `kept` runs from cap to cap inside
2424/// the wall: nothing crosses, so the result is written down: `kept`'s end loops
2425/// become holes in the caps and its sides turn inside out. `None` when the
2426/// bodies are not that shape; the caller takes the boolean then.
2427fn clip_less_direct(
2428    cylinder: &BrepSolid,
2429    base: Vec3,
2430    direction: Vec3,
2431    kept: &BrepSolid,
2432) -> Result<Option<BrepSolid>, KernelRefusal> {
2433    if kept.shells.len() != 1 || cylinder.shells.len() != 1 {
2434        return Ok(None);
2435    }
2436    let mut stride = 0;
2437    for shell in &cylinder.shells {
2438        for face in &shell.faces {
2439            stride = stride.max(face.id);
2440            for loop_record in &face.loops {
2441                stride = stride.max(loop_record.id);
2442                stride = loop_record.coedges.iter().fold(stride, |m, c| m.max(c.id));
2443            }
2444        }
2445    }
2446    stride = cylinder.vertices.iter().fold(stride, |m, v| m.max(v.id));
2447    stride = cylinder.edges.iter().fold(stride, |m, e| m.max(e.id)) + 1;
2448    let corners = |surface: &crate::NurbsSurface| -> Result<([f64; 4], [Vec3; 3]), String> {
2449        let (u0, u1) = (surface.knots_u[0], *surface.knots_u.last().ok_or("knots")?);
2450        let (v0, v1) = (surface.knots_v[0], *surface.knots_v.last().ok_or("knots")?);
2451        Ok(([u0, u1, v0, v1], [surface.evaluate(u0, v0)?, surface.evaluate(u1, v0)?, surface.evaluate(u0, v1)?]))
2452    };
2453    let mut result = cylinder.clone();
2454    result.mass_properties_cache = Default::default();
2455    result.genus = 1;
2456    result.vertices.extend(kept.vertices.iter().map(|v| crate::topology::VertexRecord { id: v.id + stride, point: v.point }));
2457    for edge in &kept.edges {
2458        let mut edge = edge.clone();
2459        edge.id += stride;
2460        edge.start_vertex_id += stride;
2461        edge.end_vertex_id += stride;
2462        result.edges.push(edge);
2463    }
2464    let mut holes = 0;
2465    let turned = |loop_record: &crate::topology::LoopRecord| -> Result<crate::topology::LoopRecord, KernelRefusal> {
2466        let mut coedges = Vec::with_capacity(loop_record.coedges.len());
2467        for coedge in loop_record.coedges.iter().rev() {
2468            coedges.push(crate::topology::CoedgeRecord {
2469                id: coedge.id + stride,
2470                edge_id: coedge.edge_id + stride,
2471                forward: !coedge.forward,
2472                pcurve: coedge.pcurve.reversed().or_refuse(KernelStage::Fragment, "clip_less_pcurve")?,
2473            });
2474        }
2475        Ok(crate::topology::LoopRecord { id: loop_record.id + stride, coedges })
2476    };
2477    for face in &kept.shells[0].faces {
2478        let mut loops = Vec::with_capacity(face.loops.len());
2479        for loop_record in &face.loops {
2480            loops.push(turned(loop_record)?);
2481        }
2482        if !face.surface.is_affine().unwrap_or(false) {
2483            result.shells[0].faces.push(crate::FaceRecord {
2484                id: face.id + stride,
2485                surface: face.surface.clone(),
2486                same_sense: !face.same_sense,
2487                loops,
2488                name: face.name.clone(),
2489            });
2490            continue;
2491        }
2492        // An end: its loops are holes in the cap at its height, read in that cap's chart.
2493        let (from_box, from) = corners(&face.surface).or_refuse(KernelStage::Fragment, "clip_less_chart")?;
2494        let height = from[0].sub(base).dot(direction);
2495        let mut caps = result.shells[0].faces.iter_mut().filter(|cap| {
2496            cap.surface.is_affine().unwrap_or(false)
2497                && cap.surface.evaluate(cap.surface.knots_u[0], cap.surface.knots_v[0]).is_ok_and(|p| (p.sub(base).dot(direction) - height).abs() < 1e-9 * (1.0 + height.abs()))
2498        });
2499        let (Some(cap), None) = (caps.next(), caps.next()) else { return Ok(None) };
2500        let (to_box, to) = corners(&cap.surface).or_refuse(KernelStage::Fragment, "clip_less_chart")?;
2501        let (eu, ev) = (to[1].sub(to[0]), to[2].sub(to[0]));
2502        if eu.dot(ev).abs() > 1e-9 * eu.length() * ev.length() {
2503            return Ok(None);
2504        }
2505        let chart = |p: Vec3| {
2506            let d = p.sub(to[0]);
2507            [
2508                to_box[0] + (to_box[1] - to_box[0]) * d.dot(eu) / eu.dot(eu),
2509                to_box[2] + (to_box[3] - to_box[2]) * d.dot(ev) / ev.dot(ev),
2510            ]
2511        };
2512        let source = |a: f64, b: f64| from[0].add(from[1].sub(from[0]).scale(a)).add(from[2].sub(from[0]).scale(b));
2513        let (origin, across, up) = (chart(source(0.0, 0.0)), chart(source(1.0, 0.0)), chart(source(0.0, 1.0)));
2514        for loop_record in &mut loops {
2515            for coedge in &mut loop_record.coedges {
2516                let curve = &coedge.pcurve;
2517                let control_points = curve
2518                    .control_points
2519                    .iter()
2520                    .map(|p| {
2521                        let a = (p.x / p.w - from_box[0]) / (from_box[1] - from_box[0]);
2522                        let b = (p.y / p.w - from_box[2]) / (from_box[3] - from_box[2]);
2523                        let x = origin[0] + a * (across[0] - origin[0]) + b * (up[0] - origin[0]);
2524                        let y = origin[1] + a * (across[1] - origin[1]) + b * (up[1] - origin[1]);
2525                        crate::Vec4 { x: x * p.w, y: y * p.w, z: p.z, w: p.w }
2526                    })
2527                    .collect();
2528                coedge.pcurve = NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
2529                    .or_refuse(KernelStage::Fragment, "clip_less_pcurve")?;
2530            }
2531        }
2532        cap.loops.extend(loops);
2533        holes += 1;
2534    }
2535    if holes != 2 || result.validate().iter().any(|issue| issue.severity == "error") {
2536        return Ok(None);
2537    }
2538    Ok(Some(result))
2539}
2540
2541/// The level above which a screw's sweep covers every angle, up to the clip,
2542/// when the material between its turns narrows to nothing there; `None` when
2543/// the sweep leaves something at the clip's edge.
2544fn crest_level(engine: &Engine) -> Result<Option<f64>, KernelRefusal> {
2545    let whole = |level: f64| -> Result<bool, KernelRefusal> {
2546        match engine.intervals_at(level) {
2547            Ok(_) => Ok(false),
2548            Err(error) if error.message.contains(WHOLE_LEVEL) => Ok(true),
2549            Err(error) => Err(error),
2550        }
2551    };
2552    let [l0, l1] = engine.clip.radius;
2553    let scan = 64;
2554    let level_at = |k: usize| l0 + (l1 - l0) * k as f64 / scan as f64;
2555    if !whole(l1)? {
2556        return Ok(None);
2557    }
2558    let mut first = scan;
2559    while first > 0 && whole(level_at(first - 1))? {
2560        first -= 1;
2561    }
2562    if first == 0 {
2563        return Ok(None);
2564    }
2565    let (mut below, mut above) = (level_at(first - 1), level_at(first));
2566    for _ in 0..60 {
2567        let middle = 0.5 * (below + above);
2568        if whole(middle)? {
2569            above = middle;
2570        } else {
2571            below = middle;
2572        }
2573    }
2574    // The material must narrow to nothing there, not stop at some width. Near
2575    // the end the walls have already crossed unseen (the oracle stops seeing the
2576    // gap a little past the crest), so the crest is where the gap, measured
2577    // well below, extrapolates to zero.
2578    let gap = |level: f64| -> Result<f64, KernelRefusal> {
2579        Ok(TAU - engine.intervals_at(level)?.iter().map(|interval| interval.hi - interval.lo).sum::<f64>())
2580    };
2581    let step = 4e-5 * (l1 - l0);
2582    let (x0, x1, x2) = (below - 3.0 * step, below - 2.0 * step, below - step);
2583    let (g0, g1, g2) = (gap(x0)?, gap(x1)?, gap(x2)?);
2584    if !(g2 > 0.0 && g1 > g2 && g0 > g1) || g2 > 16.0 * (g1 - g2) {
2585        return Ok(None);
2586    }
2587    let curve = |x: f64| {
2588        g0 * (x - x1) * (x - x2) / ((x0 - x1) * (x0 - x2))
2589            + g1 * (x - x0) * (x - x2) / ((x1 - x0) * (x1 - x2))
2590            + g2 * (x - x0) * (x - x1) / ((x2 - x0) * (x2 - x1))
2591    };
2592    let (mut lo, mut hi) = (x2, below + step);
2593    if curve(hi) > 0.0 {
2594        return Ok(None);
2595    }
2596    for _ in 0..80 {
2597        let middle = 0.5 * (lo + hi);
2598        if curve(middle) > 0.0 {
2599            lo = middle;
2600        } else {
2601            hi = middle;
2602        }
2603    }
2604    Ok(Some(0.5 * (lo + hi)))
2605}
2606
2607fn find_events(
2608    engine: &Engine,
2609    a: f64,
2610    sa: &[Interval],
2611    b: f64,
2612    sb: &[Interval],
2613    breaks: &mut Vec<f64>,
2614    depth: usize,
2615) -> Result<(), KernelRefusal> {
2616    if compatible(engine, sa, sb) {
2617        return Ok(());
2618    }
2619    if depth <= 2 && std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
2620        let summary = |s: &[Interval]| -> Vec<(usize, usize, f64, f64)> {
2621            s.iter().map(|x| (x.lo_source, x.hi_source, (x.lo * 1e4).round() / 1e4, (x.hi * 1e4).round() / 1e4)).collect()
2622        };
2623        eprintln!("  find_events depth {depth} [{a:.9}, {b:.9}] {:?}\n      -> {:?} counters {:?}", summary(sa), summary(sb), engine.counters.get());
2624    }
2625    if b - a < 1e-13 * engine.scale || depth > 60 {
2626        breaks.push(0.5 * (a + b));
2627        return Ok(());
2628    }
2629    let m = 0.5 * (a + b);
2630    let sm = engine.intervals_at(m)?;
2631    // Both halves stay incompatible only where the reading flickers; follow the
2632    // half that changes first and let the other be found from the scan above.
2633    if !compatible(engine, sa, &sm) && !compatible(engine, &sm, sb) && depth > 8 {
2634        breaks.push(m);
2635        return Ok(());
2636    }
2637    find_events(engine, a, sa, m, &sm, breaks, depth + 1)?;
2638    find_events(engine, m, &sm, b, sb, breaks, depth + 1)
2639}
2640
2641/// The candidate of `source` at `level` nearest `guess` (or its critical point
2642/// at that level); `fallback` when the source has none there.
2643fn end_value(engine: &Engine, source: usize, level: f64, guess: f64, fallback: f64) -> f64 {
2644    let mut candidates = Vec::new();
2645    engine.source_candidates(source, level, &mut candidates);
2646    let mut options: Vec<f64> = candidates.iter().map(|c| c.0).collect();
2647    for critical in &engine.critical[source] {
2648        if (critical.0 - level).abs() < 1e-7 * engine.scale {
2649            options.push(critical.1);
2650        }
2651    }
2652    let mut best = fallback;
2653    let mut distance = f64::INFINITY;
2654    for option in options {
2655        let d = engine.o_difference(option, guess).abs();
2656        if d < distance {
2657            distance = d;
2658            best = guess + engine.o_difference(option, guess);
2659        }
2660    }
2661    best
2662}
2663
2664/// Sample a band (a, b) of constant structure; return its end pieces and the
2665/// intervals at its bottom and top.
2666#[allow(clippy::type_complexity)]
2667fn sample_band(
2668    engine: &Engine,
2669    a: f64,
2670    b: f64,
2671    mid: &[Interval],
2672    fold_ends: &[f64],
2673) -> Result<(Vec<Piece>, Vec<(f64, f64)>, Vec<(f64, f64)>), KernelRefusal> {
2674    let count = mid.len();
2675    let n = 24usize;
2676    // Next to a fold the extremum Newton flickers; keep every sample at least
2677    // this far from a fold end (the end itself reads the fold's critical point).
2678    let near_fold = fold_ends.iter().any(|f| (f - a).abs() < 1e-12 * engine.scale || (f - b).abs() < 1e-12 * engine.scale);
2679    let n_cap = if near_fold {
2680        let keep = (1e-4 * engine.scale).min((b - a) / 50.0);
2681        // smallest σ step: (b − a)(1 − cos(π/n))/2 ≥ keep
2682        let ratio = (1.0 - 2.0 * keep / (b - a)).clamp(-1.0, 1.0);
2683        ((PI / ratio.acos()).floor() as usize).max(8)
2684    } else {
2685        192
2686    };
2687    let mut n = n.min(n_cap);
2688    loop {
2689        let sigma: Vec<f64> = (0..=n).map(|k| k as f64 / n as f64).collect();
2690        let level_at = |s: f64| a + (b - a) * (1.0 - (PI * s).cos()) / 2.0;
2691        // Track every interval from the middle sample outward.
2692        let mut lo = vec![vec![f64::NAN; n + 1]; count];
2693        let mut hi = vec![vec![f64::NAN; n + 1]; count];
2694        let mut lo_src = vec![vec![0usize; n + 1]; count];
2695        let mut hi_src = vec![vec![0usize; n + 1]; count];
2696        let mid_index = n / 2;
2697        let mid_intervals = engine.intervals_at(level_at(sigma[mid_index]))?;
2698        if mid_intervals.len() != count {
2699            return Err(refuse("band_structure", format!("the structure changes inside the band {a}..{b}")));
2700        }
2701        for (i, interval) in mid_intervals.iter().enumerate() {
2702            lo[i][mid_index] = interval.lo;
2703            hi[i][mid_index] = interval.hi;
2704            lo_src[i][mid_index] = interval.lo_source;
2705            hi_src[i][mid_index] = interval.hi_source;
2706        }
2707        for direction in [-1i64, 1] {
2708            let mut k = mid_index as i64 + direction;
2709            while k > 0 && (k as usize) < n {
2710                let ku = k as usize;
2711                let previous = (ku as i64 - direction) as usize;
2712                let intervals = engine.intervals_at(level_at(sigma[ku]))?;
2713                if intervals.len() != count {
2714                    return Err(refuse("band_structure", format!("the structure changes inside the band {a}..{b}")));
2715                }
2716                for i in 0..count {
2717                    let centre = 0.5 * (lo[i][previous] + hi[i][previous]);
2718                    let nearest = intervals
2719                        .iter()
2720                        .min_by(|x, y| {
2721                            let dx = engine.o_difference(0.5 * (x.lo + x.hi), centre).abs();
2722                            let dy = engine.o_difference(0.5 * (y.lo + y.hi), centre).abs();
2723                            dx.total_cmp(&dy)
2724                        })
2725                        .expect("nonempty");
2726                    let shift = engine.o_difference(nearest.lo, lo[i][previous]) - (nearest.lo - lo[i][previous]);
2727                    lo[i][ku] = nearest.lo + shift;
2728                    hi[i][ku] = nearest.hi + shift;
2729                    lo_src[i][ku] = nearest.lo_source;
2730                    hi_src[i][ku] = nearest.hi_source;
2731                }
2732                k += direction;
2733            }
2734        }
2735        // Ends: the same source's value at exactly the band's end levels,
2736        // nearest the linear extrapolation of the two nearest samples.
2737        for i in 0..count {
2738            for (end, inner, inner2, inner3, level) in [(0usize, 1usize, 2usize, 3usize, a), (n, n - 1, n - 2, n - 3, b)] {
2739                // A quadratic in the sample index through the three nearest samples.
2740                // The levels cluster as σ² at the ends, so a regular end is quadratic
2741                // in σ and a √ end (a tip) linear: this is exact for both, where
2742                // `2v₁ − v₂` misses the first by the slope times a sample spacing. A
2743                // source whose domain ends at this level has no candidate there, so
2744                // the estimate IS the end value (1e-3 on the bar swung on its edge).
2745                let near = |values: &Vec<f64>| 2.0 * values[inner] - values[inner2];
2746                let quadratic = |values: &Vec<f64>| 3.0 * values[inner] - 3.0 * values[inner2] + values[inner3];
2747                lo[i][end] = end_value(engine, lo_src[i][inner], level, near(&lo[i]), quadratic(&lo[i]));
2748                hi[i][end] = end_value(engine, hi_src[i][inner], level, near(&hi[i]), quadratic(&hi[i]));
2749            }
2750        }
2751        // Accuracy: compare the fitted ends at the σ mid-points with exact values.
2752        let mut worst = 0.0f64;
2753        let mut worst_at = (0usize, 0usize, 0usize, 0.0f64, 0.0f64);
2754        for i in 0..count {
2755            for (side, values) in [&lo[i], &hi[i]].into_iter().enumerate() {
2756                let points: Vec<Vec3> = (0..=n)
2757                    .map(|k| reduced_to_plane(engine, level_at(sigma[k]), values[k]))
2758                    .collect();
2759                let curve = fit_piece(&points)?;
2760                let parameters = chord_parameters(&points);
2761                // The end spans too: an end value is read differently from the samples.
2762                for k in (1..n - 1).step_by((n / 8).max(1)).chain([0, n - 1]) {
2763                    let s = 0.5 * (sigma[k] + sigma[k + 1]);
2764                    let level = level_at(s);
2765                    let intervals = engine.intervals_at(level)?;
2766                    let guess = 0.5 * (values[k] + values[k + 1]);
2767                    let exact = intervals
2768                        .iter()
2769                        .flat_map(|x| [x.lo, x.hi])
2770                        .map(|o| guess + engine.o_difference(o, guess))
2771                        .min_by(|x, y| (x - guess).abs().total_cmp(&(y - guess).abs()))
2772                        .unwrap_or(guess);
2773                    let truth = reduced_to_plane(engine, level, exact);
2774                    let bracket = (parameters[k.saturating_sub(1)], parameters[(k + 2).min(n)]);
2775                    let off = distance_in_bracket(&curve, truth, bracket.0, bracket.1)?;
2776                    if off > worst {
2777                        worst = off;
2778                        worst_at = (i, side, k, level, exact);
2779                    }
2780                }
2781            }
2782        }
2783        if std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
2784            eprintln!("  band {a:.9}..{b:.9} n {n} worst {worst:.3e} at {worst_at:?}");
2785        }
2786        if n >= n_cap && worst > 1e-6 * engine.scale {
2787            return Err(refuse(
2788                "fit_tolerance",
2789                format!(
2790                    "a boundary piece of the band {a}..{b} stays {worst:.3e} off its envelope at {n} samples \
2791                     (interval {}, {}, sample {}, level {}, o {})",
2792                    worst_at.0,
2793                    if worst_at.1 == 0 { "lo" } else { "hi" },
2794                    worst_at.2,
2795                    worst_at.3,
2796                    worst_at.4
2797                ),
2798            ));
2799        }
2800        if worst <= 1e-8 * engine.scale || n >= n_cap {
2801            let mut pieces = Vec::new();
2802            for i in 0..count {
2803                for values in [&lo[i], &hi[i]] {
2804                    pieces.push(Piece {
2805                        points: (0..=n).map(|k| (level_at(sigma[k]), values[k])).collect(),
2806                        sigma: sigma.clone(),
2807                        level_segment: false,
2808                    });
2809                }
2810            }
2811            let bottoms = (0..count).map(|i| (lo[i][0], hi[i][0])).collect();
2812            let tops = (0..count).map(|i| (lo[i][n], hi[i][n])).collect();
2813            return Ok((pieces, bottoms, tops));
2814        }
2815        n = (n * 2).min(n_cap);
2816    }
2817}
2818
2819/// Chord-length parameters for interpolating `points`, normalised to [0, 1].
2820/// Not the sampling's own `σ`: the levels cluster at both ends of a band, which
2821/// near a tip is what keeps a √ end smooth, but at a regular end it makes the
2822/// curve's speed vanish there, and an interpolant through a zero-speed end
2823/// cusps (the screw groove's wall folded where it met the closing arc).
2824fn chord_parameters(points: &[Vec3]) -> Vec<f64> {
2825    let mut parameters = vec![0.0; points.len()];
2826    for k in 1..points.len() {
2827        parameters[k] = parameters[k - 1] + points[k].sub(points[k - 1]).length();
2828    }
2829    let total = parameters[points.len() - 1].max(1e-300);
2830    for parameter in &mut parameters {
2831        *parameter /= total;
2832    }
2833    let last = points.len() - 1;
2834    parameters[last] = 1.0;
2835    parameters
2836}
2837
2838fn fit_piece(points: &[Vec3]) -> Result<NurbsCurve, KernelRefusal> {
2839    interpolate_curve(points, 3, &chord_parameters(points)).or_refuse(KernelStage::Fragment, "piece_fit")
2840}
2841
2842/// Distance from `target` to `curve` over the parameter bracket [a, b].
2843fn distance_in_bracket(curve: &NurbsCurve, target: Vec3, a: f64, b: f64) -> Result<f64, KernelRefusal> {
2844    let distance = |t: f64| -> Result<f64, KernelRefusal> {
2845        Ok(curve.evaluate(t).or_refuse(KernelStage::Fragment, "piece_eval")?.sub(target).length())
2846    };
2847    let ratio = 0.618_033_988_749_894_9;
2848    let (mut lo, mut hi) = (a, b);
2849    for _ in 0..80 {
2850        let c = hi - ratio * (hi - lo);
2851        let d = lo + ratio * (hi - lo);
2852        if distance(c)? < distance(d)? {
2853            hi = d;
2854        } else {
2855            lo = c;
2856        }
2857    }
2858    distance(0.5 * (lo + hi))
2859}
2860
2861/// `below Δ above` as intervals of `o` (both lists at one level).
2862fn symmetric_difference(below: &[(f64, f64)], above: &[(f64, f64)], angular: bool, tolerance: f64) -> Vec<(f64, f64)> {
2863    // Normalise to [base, base + 2π) for angular values, splitting wrapped ones.
2864    let normalise = |list: &[(f64, f64)]| -> Vec<(f64, f64)> {
2865        let mut out = Vec::new();
2866        for &(lo, hi) in list {
2867            if angular {
2868                let shift = lo.rem_euclid(TAU) - lo;
2869                let (lo, hi) = (lo + shift, hi + shift);
2870                if hi > TAU {
2871                    out.push((lo, TAU));
2872                    out.push((0.0, hi - TAU));
2873                } else {
2874                    out.push((lo, hi));
2875                }
2876            } else {
2877                out.push((lo, hi));
2878            }
2879        }
2880        out
2881    };
2882    let a = normalise(below);
2883    let b = normalise(above);
2884    let mut cuts: Vec<f64> = a.iter().chain(&b).flat_map(|&(lo, hi)| [lo, hi]).collect();
2885    cuts.sort_by(|x, y| x.total_cmp(y));
2886    cuts.dedup_by(|y, x| (*y - *x).abs() < tolerance);
2887    let inside = |list: &Vec<(f64, f64)>, x: f64| list.iter().any(|&(lo, hi)| x > lo && x < hi);
2888    let mut out: Vec<(f64, f64)> = Vec::new();
2889    for w in cuts.windows(2) {
2890        let m = 0.5 * (w[0] + w[1]);
2891        if inside(&a, m) != inside(&b, m) && w[1] - w[0] > tolerance {
2892            if let Some(last) = out.last_mut() {
2893                if (last.1 - w[0]).abs() < tolerance {
2894                    last.1 = w[1];
2895                    continue;
2896                }
2897            }
2898            out.push((w[0], w[1]));
2899        }
2900    }
2901    if angular && out.len() > 1 {
2902        let first = out[0];
2903        let last = *out.last().expect("nonempty");
2904        if first.0.abs() < tolerance && (last.1 - TAU).abs() < tolerance {
2905            out.pop();
2906            out[0] = (last.0 - TAU, first.1);
2907        }
2908    }
2909    out
2910}
2911
2912/// A reduced point on the section plane the body is built from.
2913fn reduced_to_plane(engine: &Engine, level: f64, o: f64) -> Vec3 {
2914    let clip = engine.clip;
2915    match engine.class {
2916        Class::Screw(c) => {
2917            let z = clip.axial[0];
2918            let alpha = o + z / c;
2919            engine.frame.world([level * alpha.cos(), level * alpha.sin(), z])
2920        }
2921        Class::Turn => {
2922            let theta = clip.angle.map(|a| a[0]).unwrap_or(0.0);
2923            engine.frame.world([level * theta.cos(), level * theta.sin(), o])
2924        }
2925        Class::Planar => engine.frame.world([level * o.cos(), level * o.sin(), clip.axial[0]]),
2926    }
2927}
2928
2929/// Join pieces end to end into closed loops (in the section plane).
2930fn assemble_loops(engine: &Engine, pieces: Vec<Piece>) -> Result<Vec<Vec<Piece>>, KernelRefusal> {
2931    let tolerance = 1e-6 * engine.scale;
2932    let ends: Vec<(Vec3, Vec3)> = pieces
2933        .iter()
2934        .map(|piece| {
2935            let first = piece.points[0];
2936            let last = *piece.points.last().expect("nonempty");
2937            (reduced_to_plane(engine, first.0, first.1), reduced_to_plane(engine, last.0, last.1))
2938        })
2939        .collect();
2940    let mut used = vec![false; pieces.len()];
2941    let mut orders: Vec<Vec<(usize, bool)>> = Vec::new();
2942    for start in 0..pieces.len() {
2943        if used[start] {
2944            continue;
2945        }
2946        used[start] = true;
2947        let mut order = vec![(start, false)];
2948        let origin = ends[start].0;
2949        let mut cursor = ends[start].1;
2950        let mut guard = 0;
2951        while cursor.sub(origin).length() > tolerance {
2952            guard += 1;
2953            if guard > pieces.len() {
2954                return Err(refuse("loop_open", "the section's boundary does not close".into()));
2955            }
2956            let mut next = None;
2957            let mut best = tolerance;
2958            for k in 0..pieces.len() {
2959                if used[k] {
2960                    continue;
2961                }
2962                for (reversed, end) in [(false, ends[k].0), (true, ends[k].1)] {
2963                    let d = end.sub(cursor).length();
2964                    if d < best {
2965                        best = d;
2966                        next = Some((k, reversed));
2967                    }
2968                }
2969            }
2970            let Some((k, reversed)) = next else {
2971                return Err(refuse(
2972                    "loop_open",
2973                    format!("the section's boundary does not close (a gap at {:?})", cursor),
2974                ));
2975            };
2976            used[k] = true;
2977            order.push((k, reversed));
2978            cursor = if reversed { ends[k].0 } else { ends[k].1 };
2979        }
2980        orders.push(order);
2981    }
2982    if orders.len() > 1 {
2983        // A loop inside another is a hole; not built here.
2984        let polygon = |order: &Vec<(usize, bool)>| -> Vec<Vec3> {
2985            order
2986                .iter()
2987                .flat_map(|&(k, _)| pieces[k].points.iter().map(|p| reduced_to_plane(engine, p.0, p.1)))
2988                .collect()
2989        };
2990        let polygons: Vec<Vec<Vec3>> = orders.iter().map(polygon).collect();
2991        for (i, a) in polygons.iter().enumerate() {
2992            for (j, b) in polygons.iter().enumerate() {
2993                if i != j && point_in_polygon(engine, a[0], b) {
2994                    return Err(refuse("section_hole", "the section has a hole, which is not built here".into()));
2995                }
2996            }
2997        }
2998    }
2999    let mut slots: Vec<Option<Piece>> = pieces.into_iter().map(Some).collect();
3000    Ok(orders
3001        .into_iter()
3002        .map(|order| {
3003            order
3004                .into_iter()
3005                .map(|(k, reversed)| {
3006                    let mut piece = slots[k].take().expect("each piece once");
3007                    if reversed {
3008                        piece.points.reverse();
3009                        piece.sigma = piece.sigma.iter().rev().map(|s| 1.0 - s).collect();
3010                    }
3011                    piece
3012                })
3013                .collect()
3014        })
3015        .collect())
3016}
3017
3018pub fn point_in_polygon(engine: &Engine, p: Vec3, polygon: &[Vec3]) -> bool {
3019    let local = |x: Vec3| -> [f64; 2] {
3020        let l = engine.frame.local(x);
3021        match engine.class {
3022            Class::Turn => [l[0].hypot(l[1]), l[2]],
3023            _ => [l[0], l[1]],
3024        }
3025    };
3026    let q = local(p);
3027    let mut inside = false;
3028    for k in 0..polygon.len() {
3029        let a = local(polygon[k]);
3030        let b = local(polygon[(k + 1) % polygon.len()]);
3031        if (a[1] > q[1]) != (b[1] > q[1]) {
3032            let x = a[0] + (q[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
3033            if x > q[0] {
3034                inside = !inside;
3035            }
3036        }
3037    }
3038    inside
3039}
3040
3041/// Fit each piece and build the body for one loop.
3042fn build_body(engine: &Engine, pieces: &[Piece]) -> Result<BrepSolid, KernelRefusal> {
3043    let clip = engine.clip;
3044    let mut profile: Vec<NurbsCurve> = Vec::new();
3045    // Snap shared ends so consecutive curves meet exactly.
3046    let count = pieces.len();
3047    let mut start_points: Vec<Vec3> = pieces
3048        .iter()
3049        .map(|p| reduced_to_plane(engine, p.points[0].0, p.points[0].1))
3050        .collect();
3051    // A level segment is built exactly from its own ends, so the piece after
3052    // it starts where it ends.
3053    for (index, piece) in pieces.iter().enumerate() {
3054        if piece.level_segment && engine.class != Class::Turn {
3055            let (level, o1) = *piece.points.last().expect("nonempty");
3056            start_points[(index + 1) % count] = reduced_to_plane(engine, level, o1);
3057        }
3058    }
3059    for (index, piece) in pieces.iter().enumerate() {
3060        let start = start_points[index];
3061        let end = start_points[(index + 1) % count];
3062        if piece.level_segment {
3063            let (level, o0) = piece.points[0];
3064            let o1 = piece.points.last().expect("nonempty").1;
3065            let curve = match engine.class {
3066                Class::Turn => make_line(start, end),
3067                Class::Screw(c) => {
3068                    let shift = clip.axial[0] / c;
3069                    level_arc(engine, level, o0 + shift, o1 + shift)
3070                }
3071                Class::Planar => level_arc(engine, level, o0, o1),
3072            }
3073            .or_refuse(KernelStage::Fragment, "level_segment")?;
3074            profile.push(curve);
3075            continue;
3076        }
3077        let mut points: Vec<Vec3> = piece
3078            .points
3079            .iter()
3080            .map(|p| reduced_to_plane(engine, p.0, p.1))
3081            .collect();
3082        points[0] = start;
3083        let last = points.len() - 1;
3084        points[last] = end;
3085        profile.push(fit_piece(&points)?);
3086    }
3087    match engine.class {
3088        Class::Screw(c) => {
3089            let span = (clip.axial[1] - clip.axial[0]) / c; // radians of screw
3090            // Over a crest the walls are re-carried below to high order, so 12 a turn is enough.
3091            // A bar's walls are carried to high order too: a cubic through 64
3092            // sections a turn stands r·h⁴/384 off the screw (1e-6 at a groove's
3093            // floor), the quintic through 48 below 1e-9.
3094            let carried = engine.crest_gap || engine.bar.is_some() || screw_carry_on();
3095            let per_turn = if engine.crest_gap { 12.0 } else if carried { 48.0 } else { 64.0 };
3096            // Every turn is the screw image of the first: build one and stack
3097            // copies, so no surface or edge runs the thread's whole length.
3098            let rows = if carried && thread_rows_on() { (span.abs() / TAU / TURNS_PER_ROW).round().max(1.0) as usize } else { 1 };
3099            let span = span / rows as f64;
3100            let sections = ((span.abs() / TAU * per_turn).ceil() as usize).max(8) + 1;
3101            let mut lofted = Vec::with_capacity(sections);
3102            for k in 0..sections {
3103                let angle = span * k as f64 / (sections - 1) as f64;
3104                let lift = engine.frame.ez.scale(c * angle);
3105                let moved: Vec<NurbsCurve> = profile
3106                    .iter()
3107                    .map(|curve| transform_curve(curve, |x| rotate(x, clip.axis_origin, engine.frame.ez, angle).add(lift)))
3108                    .collect::<Result<_, _>>()?;
3109                lofted.push(moved);
3110            }
3111            let mut body = loft_profile_brep(&lofted)?;
3112            if carried {
3113                carry_along_screw(&mut body, engine, c, span, sections - 1)?;
3114            }
3115            if rows > 1 {
3116                body = stack_screw_rows(&body, engine, c, span, sections - 1, rows)?;
3117            }
3118            Ok(body)
3119        }
3120        Class::Turn => {
3121            let angle = clip.angle.map(|a| a[1] - a[0]).unwrap_or(TAU);
3122            revolve_profile_brep(&profile, clip.axis_origin, engine.frame.ez, angle)
3123                .or_refuse(KernelStage::Fragment, "revolve")
3124        }
3125        Class::Planar => extrude_profile_brep(&profile, engine.frame.ez, clip.axial[1] - clip.axial[0]),
3126    }
3127}
3128
3129fn level_arc(engine: &Engine, level: f64, a0: f64, a1: f64) -> Result<NurbsCurve, String> {
3130    let centre = engine.frame.world([0.0, 0.0, match engine.class {
3131        Class::Screw(_) | Class::Planar => engine.clip.axial[0],
3132        Class::Turn => 0.0,
3133    }]);
3134    let (start, end) = if a1 >= a0 { (a0, a1) } else { (a1, a0) };
3135    let arc = make_arc(centre, engine.frame.ex, engine.frame.ey, level, start, end)?;
3136    if a1 >= a0 {
3137        Ok(arc)
3138    } else {
3139        arc.reversed()
3140    }
3141}
3142
3143fn transform_curve(curve: &NurbsCurve, map: impl Fn(Vec3) -> Vec3) -> Result<NurbsCurve, KernelRefusal> {
3144    let control_points = curve
3145        .control_points
3146        .iter()
3147        .map(|p| {
3148            let w = p.w;
3149            let x = map(Vec3::new(p.x / w, p.y / w, p.z / w));
3150            crate::Vec4 { x: x.x * w, y: x.y * w, z: x.z * w, w }
3151        })
3152        .collect();
3153    NurbsCurve::new(curve.degree, curve.knots.clone(), control_points).or_refuse(KernelStage::Fragment, "curve_new")
3154}
3155
3156/// Refuse a screw or turn whose first or last position reaches the clip.
3157fn check_ends_clear(engine: &Engine) -> Result<(), KernelRefusal> {
3158    let clip = engine.clip;
3159    // Tool boundary samples at its own place (clip frame).
3160    let mut samples: Vec<[f64; 3]> = Vec::new();
3161    for (index, source) in engine.sources.iter().enumerate() {
3162        if let Some(grid) = &engine.grids[index] {
3163            for i in 0..grid.nu {
3164                for j in 0..grid.nv {
3165                    let (u, v) = Engine::grid_param(grid, i, j);
3166                    samples.push(engine.frame.local(engine.source_point(*source, u, v)));
3167                }
3168            }
3169        }
3170    }
3171    let margin = 1e-6 * engine.scale;
3172    for t in [engine.motion.from, engine.motion.to] {
3173        for p in &samples {
3174            let x = engine.frame.local(engine.motion_apply(t, engine.frame.world(*p)));
3175            let level = x[0].hypot(x[1]);
3176            if level > clip.radius[1] + margin || level < clip.radius[0] - margin {
3177                continue;
3178            }
3179            if x[2] < clip.axial[0] - margin || x[2] > clip.axial[1] + margin {
3180                continue;
3181            }
3182            if let Some([a0, a1]) = clip.angle {
3183                let angle = x[1].atan2(x[0]);
3184                let mid = 0.5 * (a0 + a1);
3185                let rel = wrap_pi(angle - mid);
3186                if rel.abs() > 0.5 * (a1 - a0) + 1e-9 {
3187                    continue;
3188                }
3189            }
3190            return Err(refuse(
3191                "ends_reach_clip",
3192                format!(
3193                    "the tool reaches the clip region at the motion's {} (t = {t}); the sweep is \
3194                     not invariant there, so the region would be wrong",
3195                    if t == engine.motion.from { "start" } else { "end" }
3196                ),
3197            ));
3198        }
3199    }
3200    Ok(())
3201}
3202