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