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    /// The elliptic arc about `centre` with semi-axis `semi[0]` along the
84    /// direction at angle `rotation` (radians from the first coordinate) and
85    /// `semi[1]` square to it, from eccentric angle `start` to `end` (radians;
86    /// `end < start` runs clockwise): the points `centre + R(rotation)·(semi[0]
87    /// cos θ, semi[1] sin θ)`. A whole ellipse is `0 → 2π`. Taken by the region
88    /// engine of [`sweep_solid_within`] (a solid of revolution's meridian, a
89    /// prism's outline); refused by the whole sweep.
90    Ellipse { centre: [f64; 2], semi: [f64; 2], rotation: f64, start: f64, end: f64 },
91}
92
93impl OutlinePiece {
94    fn point(&self, s: f64) -> [f64; 2] {
95        match *self {
96            OutlinePiece::Line { from, to } => {
97                [from[0] + (to[0] - from[0]) * s, from[1] + (to[1] - from[1]) * s]
98            }
99            OutlinePiece::Arc { centre, radius, start, end } => {
100                let angle = start + (end - start) * s;
101                [centre[0] + radius * angle.cos(), centre[1] + radius * angle.sin()]
102            }
103            OutlinePiece::Ellipse { centre, semi, rotation, start, end } => {
104                ellipse_point(centre, semi, rotation, start + (end - start) * s)
105            }
106        }
107    }
108
109    /// The derivative of [`Self::point`] with respect to `s`.
110    fn tangent(&self, s: f64) -> [f64; 2] {
111        match *self {
112            OutlinePiece::Line { from, to } => [to[0] - from[0], to[1] - from[1]],
113            OutlinePiece::Arc { radius, start, end, .. } => {
114                let angle = start + (end - start) * s;
115                let k = radius * (end - start);
116                [-k * angle.sin(), k * angle.cos()]
117            }
118            OutlinePiece::Ellipse { semi, rotation, start, end, .. } => {
119                let theta = start + (end - start) * s;
120                let (x, y) = (-semi[0] * theta.sin() * (end - start), semi[1] * theta.cos() * (end - start));
121                let (c, s) = (rotation.cos(), rotation.sin());
122                [c * x - s * y, s * x + c * y]
123            }
124        }
125    }
126
127    fn is_full_circle(&self) -> bool {
128        matches!(*self, OutlinePiece::Arc { start, end, .. } | OutlinePiece::Ellipse { start, end, .. } if ((end - start).abs() - TAU).abs() < 1e-12)
129    }
130
131    /// Unsigned distance from `p` to the piece.
132    fn distance(&self, p: [f64; 2]) -> f64 {
133        match *self {
134            OutlinePiece::Line { from, to } => {
135                let d = [to[0] - from[0], to[1] - from[1]];
136                let length2 = d[0] * d[0] + d[1] * d[1];
137                let t = if length2 > 0.0 {
138                    (((p[0] - from[0]) * d[0] + (p[1] - from[1]) * d[1]) / length2).clamp(0.0, 1.0)
139                } else {
140                    0.0
141                };
142                let q = [from[0] + d[0] * t - p[0], from[1] + d[1] * t - p[1]];
143                q[0].hypot(q[1])
144            }
145            OutlinePiece::Arc { centre, radius, start, end } => {
146                let v = [p[0] - centre[0], p[1] - centre[1]];
147                let angle = v[1].atan2(v[0]);
148                if self.is_full_circle() || angle_within(angle, start, end) {
149                    (v[0].hypot(v[1]) - radius).abs()
150                } else {
151                    let a = self.point(0.0);
152                    let b = self.point(1.0);
153                    (a[0] - p[0]).hypot(a[1] - p[1]).min((b[0] - p[0]).hypot(b[1] - p[1]))
154                }
155            }
156            OutlinePiece::Ellipse { centre, semi, rotation, start, end } => {
157                // Every point of the ellipse where the distance is critical,
158                // kept where it lies on the arc, and the arc's ends.
159                let (c, s) = (rotation.cos(), rotation.sin());
160                let local = [c * (p[0] - centre[0]) + s * (p[1] - centre[1]), -s * (p[0] - centre[0]) + c * (p[1] - centre[1])];
161                let mut best = [self.point(0.0), self.point(1.0)]
162                    .iter()
163                    .map(|q| (q[0] - p[0]).hypot(q[1] - p[1]))
164                    .fold(f64::INFINITY, f64::min);
165                for theta in ellipse_critical_angles(semi, local) {
166                    if self.is_full_circle() || angle_within(theta, start, end) {
167                        let q = ellipse_point(centre, semi, rotation, theta);
168                        best = best.min((q[0] - p[0]).hypot(q[1] - p[1]));
169                    }
170                }
171                best
172            }
173        }
174    }
175
176    /// Crossings of the ray from `p` towards +x with the piece (for the parity
177    /// inside test). Half-open in y so a vertex is counted once.
178    fn ray_crossings(&self, p: [f64; 2]) -> usize {
179        match *self {
180            OutlinePiece::Line { from, to } => {
181                let (a, b) = (from, to);
182                if (a[1] > p[1]) != (b[1] > p[1]) {
183                    let x = a[0] + (p[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
184                    usize::from(x > p[0])
185                } else {
186                    0
187                }
188            }
189            OutlinePiece::Arc { centre, radius, start, end } => {
190                let dy = p[1] - centre[1];
191                if dy.abs() >= radius {
192                    return 0;
193                }
194                let dx = (radius * radius - dy * dy).sqrt();
195                let mut count = 0;
196                for x in [centre[0] - dx, centre[0] + dx] {
197                    if x <= p[0] {
198                        continue;
199                    }
200                    let angle = dy.atan2(x - centre[0]);
201                    if self.is_full_circle() || angle_within(angle, start, end) {
202                        // Half-open at the arc's own ends, like the segment rule:
203                        // count an end only where the arc leaves upwards.
204                        count += 1;
205                    }
206                }
207                count
208            }
209            OutlinePiece::Ellipse { centre, semi, rotation, start, end } => {
210                // The segments' rule, half-open in y: count each change of
211                // "above p" (y > p.y) along the arc, where it happens, if
212                // that place lies to the right of p. y(θ) = cy + A cos θ +
213                // B sin θ with A = a sin φ, B = b cos φ; it meets p.y at the
214                // roots θ = atan2(B, A) ± acos((p.y − cy)/r).
215                let (a, b) = (semi[0] * rotation.sin(), semi[1] * rotation.cos());
216                let r = a.hypot(b);
217                let target = p[1] - centre[1];
218                let span = end - start;
219                let at = |fraction: f64| ellipse_point(centre, semi, rotation, start + span * fraction);
220                let above = |q: [f64; 2]| q[1] > p[1];
221                // An end within rounding of p's height is on it, as the
222                // segment beside it reads its exact vertex (not above).
223                let snap = 1e-12 * (1.0 + semi[0].max(semi[1]) + centre[0].abs().max(centre[1].abs()));
224                let above_end = |q: [f64; 2]| q[1] > p[1] + snap;
225                // Roots as fractions of the arc, in order.
226                let mut cuts: Vec<f64> = Vec::new();
227                if target.abs() < r {
228                    let base = b.atan2(a);
229                    let spread = (target / r).acos();
230                    for theta in [base + spread, base - spread] {
231                        let fraction = ((theta - start) * span.signum()).rem_euclid(TAU) / span.abs();
232                        // a root at an end is that end's
233                        let full = self.is_full_circle();
234                        if (full && fraction < 1.0) || (fraction > 1e-12 && fraction < 1.0 - 1e-12) {
235                            cuts.push(fraction);
236                        }
237                    }
238                }
239                cuts.sort_by(|x, y| x.total_cmp(y));
240                let full = self.is_full_circle();
241                // Breakpoints: the arc's ends (not for a whole ellipse) and its roots.
242                let mut marks: Vec<f64> = Vec::with_capacity(cuts.len() + 2);
243                if !full {
244                    marks.push(0.0);
245                }
246                marks.extend(&cuts);
247                if !full {
248                    marks.push(1.0);
249                }
250                if marks.is_empty() {
251                    return 0;
252                }
253                let state_at = |k: usize| -> bool {
254                    // the state just after mark k (between it and the next)
255                    let next = if k + 1 < marks.len() { marks[k + 1] } else if full { marks[0] + 1.0 } else { 1.0 };
256                    above(at(0.5 * (marks[k] + next)))
257                };
258                let mut count = 0;
259                for k in 0..marks.len() {
260                    let before = if k > 0 {
261                        state_at(k - 1)
262                    } else if full {
263                        state_at(marks.len() - 1)
264                    } else {
265                        above_end(at(0.0))
266                    };
267                    let after = if !full && k + 1 == marks.len() { above_end(at(1.0)) } else { state_at(k) };
268                    if before != after && at(marks[k])[0] > p[0] {
269                        count += 1;
270                    }
271                }
272                count
273            }
274        }
275    }
276}
277
278/// The eccentric angles of every point of the ellipse of semi-axes `semi`
279/// (centred, unrotated) where the distance to `q` is critical. The foot of the
280/// normal through `q` is `(a²x/(a²+t), b²y/(b²+t))` at each root of
281/// `F(t) = (a x/(a²+t))² + (b y/(b²+t))² = 1`: one past the nearer pole (the
282/// nearest point), none or two between the poles, one before the farther
283/// pole (the farthest). A coordinate of `q` on an axis loses its term: the
284/// vertices and the feet at that pole are added as candidates always.
285fn ellipse_critical_angles(semi: [f64; 2], q: [f64; 2]) -> Vec<f64> {
286    let [a, b] = semi;
287    let (x, y) = (q[0], q[1]);
288    let big = |t: f64| (a * x / (a * a + t)).powi(2) + (b * y / (b * b + t)).powi(2) - 1.0;
289    let angle = |t: f64| {
290        let (u, v) = (a * x / (a * a + t), b * y / (b * b + t));
291        v.atan2(u)
292    };
293    let mut out = vec![0.0, std::f64::consts::FRAC_PI_2, PI, -std::f64::consts::FRAC_PI_2];
294    // At a pole whose term vanishes (q on that axis) the feet are the limits
295    // there: x/(a² − b²)·a = cos θ at t = −b², y/(b² − a²)·b = sin θ at t = −a².
296    // Every candidate is a point of the ellipse, so an extra one never reads
297    // a distance short.
298    if (a - b).abs() > 0.0 {
299        let cos = a * x / (a * a - b * b);
300        if cos.abs() <= 1.0 {
301            out.push(cos.acos());
302            out.push(-cos.acos());
303        }
304        let sin = b * y / (b * b - a * a);
305        if sin.abs() <= 1.0 {
306            out.push(sin.asin());
307            out.push(PI - sin.asin());
308        }
309    }
310    let bisect = |mut lo: f64, mut hi: f64| -> f64 {
311        // `big` changes sign between lo and hi
312        let up = big(lo) < 0.0;
313        for _ in 0..200 {
314            let mid = 0.5 * (lo + hi);
315            if mid <= lo || mid >= hi {
316                break;
317            }
318            if (big(mid) < 0.0) == up {
319                lo = mid;
320            } else {
321                hi = mid;
322            }
323        }
324        0.5 * (lo + hi)
325    };
326    let (p_far, p_near) = { let (s, t) = (-(a * a), -(b * b)); if s < t { (s, t) } else { (t, s) } };
327    let scale = a.max(b) * (a.max(b) + x.hypot(y));
328    // Past the nearer pole F falls from +∞ (or its finite value) to −1.
329    {
330        let mut hi = p_near + scale.max(1.0);
331        while big(hi) > 0.0 {
332            hi = p_near + 2.0 * (hi - p_near);
333        }
334        let lo = p_near + 1e-300f64.max(1e-15 * scale);
335        if big(lo) > 0.0 {
336            out.push(angle(bisect(lo, hi)));
337        }
338    }
339    // Between the poles F is convex: at its least, two roots where it dips below 1.
340    if p_near - p_far > 0.0 {
341        let (mut lo, mut hi) = (p_far, p_near);
342        for _ in 0..200 {
343            let m1 = lo + (hi - lo) / 3.0;
344            let m2 = hi - (hi - lo) / 3.0;
345            if big(m1) < big(m2) { hi = m2 } else { lo = m1 }
346        }
347        let least = 0.5 * (lo + hi);
348        if big(least) < 0.0 {
349            let pad = 1e-15 * scale.max(1.0);
350            out.push(angle(bisect(least, p_near - pad)));
351            out.push(angle(bisect(p_far + pad, least)));
352        }
353    }
354    out
355}
356
357/// The point of an ellipse at eccentric angle `theta` (see [`OutlinePiece::Ellipse`]).
358pub(crate) fn ellipse_point(centre: [f64; 2], semi: [f64; 2], rotation: f64, theta: f64) -> [f64; 2] {
359    let (x, y) = (semi[0] * theta.cos(), semi[1] * theta.sin());
360    let (c, s) = (rotation.cos(), rotation.sin());
361    [centre[0] + c * x - s * y, centre[1] + s * x + c * y]
362}
363
364/// Is `angle` on the arc that runs from `start` to `end` (either sense)?
365fn angle_within(angle: f64, start: f64, end: f64) -> bool {
366    let (low, high) = if end >= start { (start, end) } else { (end, start) };
367    let shifted = low + (angle - low).rem_euclid(TAU);
368    shifted <= high
369}
370
371fn scale_of(outline: &[OutlinePiece]) -> f64 {
372    outline
373        .iter()
374        .flat_map(|piece| [piece.point(0.0), piece.point(1.0)])
375        .map(|p| p[0].abs().max(p[1].abs()))
376        .fold(1.0f64, f64::max)
377}
378
379/// Signed distance to a closed outline (negative inside).
380pub fn outline_signed_distance(outline: &[OutlinePiece], p: [f64; 2]) -> f64 {
381    let distance = outline
382        .iter()
383        .map(|piece| piece.distance(p))
384        .fold(f64::INFINITY, f64::min);
385    let crossings: usize = outline.iter().map(|piece| piece.ray_crossings(p)).sum();
386    if crossings % 2 == 1 {
387        -distance
388    } else {
389        distance
390    }
391}
392
393fn validate_outline(outline: &[OutlinePiece], what: &str) -> Result<(), KernelRefusal> {
394    if outline.is_empty() {
395        return Err(KernelRefusal::input(
396            KernelStage::Collect,
397            "outline_empty",
398            format!("sweepSolidWithin: the {what} outline is empty"),
399        ));
400    }
401    let scale = outline
402        .iter()
403        .flat_map(|piece| [piece.point(0.0), piece.point(1.0)])
404        .map(|p| p[0].abs().max(p[1].abs()))
405        .fold(1.0f64, f64::max);
406    for piece in outline {
407        if let OutlinePiece::Ellipse { semi, rotation, start, end, centre } = *piece {
408            let finite = semi.iter().chain(&centre).chain([&rotation, &start, &end]).all(|x| x.is_finite());
409            if !(finite && semi[0] > 0.0 && semi[1] > 0.0 && start != end) {
410                return Err(KernelRefusal::input(
411                    KernelStage::Collect,
412                    "outline_ellipse",
413                    format!("sweepSolidWithin: an ellipse of the {what} outline needs positive semi-axes and a span"),
414                ));
415            }
416        }
417    }
418    for (index, piece) in outline.iter().enumerate() {
419        let next = &outline[(index + 1) % outline.len()];
420        let a = piece.point(1.0);
421        let b = next.point(0.0);
422        if (a[0] - b[0]).hypot(a[1] - b[1]) > 1e-9 * scale {
423            return Err(KernelRefusal::input(
424                KernelStage::Collect,
425                "outline_open",
426                format!("sweepSolidWithin: the {what} outline is not closed after piece {index}"),
427            ));
428        }
429    }
430    Ok(())
431}
432
433/// The moving tool.
434#[derive(Clone, Debug)]
435pub enum SweptTool {
436    /// A solid of revolution: the region `meridian` bounds in the half-plane
437    /// spanned by `radial` (first coordinate, the distance from the axis, ≥ 0)
438    /// and `axis_direction` (second coordinate), turned about the axis through
439    /// `axis_origin`.
440    Revolved {
441        axis_origin: Vec3,
442        axis_direction: Vec3,
443        radial: Vec3,
444        meridian: Vec<OutlinePiece>,
445    },
446    /// A prism: the region `outline` bounds in the plane through `origin`
447    /// spanned by `x_axis` and `normal × x_axis`, extended along `normal` from
448    /// `from` to `to`.
449    Prism {
450        origin: Vec3,
451        normal: Vec3,
452        x_axis: Vec3,
453        outline: Vec<OutlinePiece>,
454        from: f64,
455        to: f64,
456    },
457    /// A bar: the region `section` bounds (curves end to end round a closed
458    /// loop, lying in the plane through `origin` square to `normal`), extended
459    /// along `normal` from height `from` to `to`. Its sides lean inward by
460    /// `draft` radians: at height `h` the section is the given one moved
461    /// inward by `h·tan(draft)` (outward where that is negative). Swept by a
462    /// screw about the clip's axis, whichever way the bar points.
463    Bar {
464        origin: Vec3,
465        normal: Vec3,
466        section: Vec<NurbsCurve>,
467        from: f64,
468        to: f64,
469        draft: f64,
470    },
471}
472
473/// One elementary motion, linear in the motion parameter `t`: a turn of
474/// `turn·t` radians, right-handed about the axis through `axis_origin` along
475/// `axis_direction`, together with an advance of `advance·t` along it. A turn
476/// alone is `advance = 0`, a slide alone is `turn = 0`.
477#[derive(Clone, Copy, Debug)]
478pub struct ScrewStep {
479    pub axis_origin: Vec3,
480    pub axis_direction: Vec3,
481    pub turn: f64,
482    pub advance: f64,
483}
484
485/// A rigid motion: the steps applied in order (the first to the tool first),
486/// for `t` from `from` to `to`.
487#[derive(Clone, Debug)]
488pub struct SolidMotion {
489    pub steps: Vec<ScrewStep>,
490    pub from: f64,
491    pub to: f64,
492}
493
494/// The region the result must agree with the sweep in, about an axis: levels
495/// (distance from the axis) in `radius`, axial positions in `axial` (measured
496/// from `axis_origin`), and polar angles in `angle` (from `reference`,
497/// right-handed about the axis), when given.
498#[derive(Clone, Copy, Debug)]
499pub struct SweepClip {
500    pub axis_origin: Vec3,
501    pub axis_direction: Vec3,
502    pub reference: Vec3,
503    pub radius: [f64; 2],
504    pub axial: [f64; 2],
505    pub angle: Option<[f64; 2]>,
506}
507
508/// The prefix of every refusal of this operation.
509pub const SOLID_SWEEP_REFUSAL: &str = "sweepSolidWithin";
510
511/// Words of the refusal for a level the sweep covers at every angle.
512const WHOLE_LEVEL: &str = "the sweep covers every angle at level";
513
514/// Turns of a thread each row of faces carries (measured: shorter rows cost more
515/// meshing, longer ones more edge reading).
516const TURNS_PER_ROW: f64 = 2.0;
517
518/// `BREP_SWEEP_THREAD_ROWS` (default on; `=0` one body-long face per wall and the
519/// boolean for the clip): a thread is built a few turns at a time, since readings
520/// over a face cost the square of its length.
521/// Faster level reading (default on; `BREP_SWEEP_FAST_LEVELS=0` restores the plain reading): an edge source's samples are reduced
522/// once, not at every level (their levels do not depend on the level read),
523/// and a face's extremum Newton stops once its residual is settled far inside
524/// the acceptance (the differenced Jacobian is noise past that).
525fn fast_levels_on() -> bool {
526    crate::switch!("BREP_SWEEP_FAST_LEVELS", true)
527}
528
529/// `BREP_SWEEP_EXTREMUM_JET` (default on; `=0` differences it): a face's extremum Newton
530/// reads the residual's gradients of the reduced coordinates exactly (from the
531/// source's own derivatives) instead of by central differences. The differenced
532/// residual costs five points and carries noise at its own stopping bar, so the
533/// Newton ran on into failed line searches; the exact one settles.
534pub(crate) fn extremum_jet_on() -> bool {
535    crate::switch!("BREP_SWEEP_EXTREMUM_JET", true)
536}
537
538/// `BREP_SWEEP_EXTREMUM_JET_CHECK` (default off): every level read both
539/// ways and compared, the differenced reading kept; the tally is this
540/// thread's [`extremum_jet_check_take`].
541fn extremum_jet_check_on() -> bool {
542    crate::switch!("BREP_SWEEP_EXTREMUM_JET_CHECK", false)
543}
544
545/// `BREP_SWEEP_CRITICAL_EVENTS` (on by default; `=0` restores the plain
546/// bisection): a scan interval whose two ends
547/// differ, with one source's critical level inside it, first reads just
548/// below and just above that level (`CRITICAL_EVENT_STEP` of the scale). If
549/// the structure changes across the pair, the event is the critical level
550/// itself (only where the count of intervals changes across it, a birth or
551/// death): the break the bisection's event is snapped to anyway (within
552/// `1e-5` of the scale, no other critical nearer). The two outer parts are
553/// searched as before. A tip's event no longer bisects to `1e-13` of the
554/// scale through some forty cold reads (the 0.27.0 torus-screwed row: about
555/// 40% of its build).
556pub(crate) fn critical_events_on() -> bool {
557    crate::switch!("BREP_SWEEP_CRITICAL_EVENTS", true)
558}
559
560/// `BREP_SWEEP_CRITICAL_EVENTS_CHECK` (default off): the scan's events found
561/// both ways, the snapped breaks compared, the bisection's kept; the tally
562/// is this thread's [`critical_events_check_take`].
563fn critical_events_check_on() -> bool {
564    crate::switch!("BREP_SWEEP_CRITICAL_EVENTS_CHECK", false)
565}
566
567/// How far either side of a critical level the shortcut reads, to the scale:
568/// a tenth of the snap's reach, so the event it names is the one the snap
569/// would give.
570const CRITICAL_EVENT_STEP: f64 = 1e-6;
571
572thread_local! {
573    static CRITICAL_EVENTS_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
574}
575
576/// (scans compared, scans whose snapped breaks differed or whose shortcut
577/// refused, events the shortcut named) on this thread since the last call.
578pub fn critical_events_check_take() -> (u64, u64, u64) {
579    CRITICAL_EVENTS_CHECK.with(|cell| cell.replace((0, 0, 0)))
580}
581
582fn critical_events_record(compared: u64, differed: u64, named: u64) {
583    CRITICAL_EVENTS_CHECK.with(|cell| {
584        let (a, b, c) = cell.get();
585        cell.set((a + compared, b + differed, c + named));
586    });
587}
588
589/// How far (to the scale) the two readings of a level's ends may part: the
590/// differenced reading's own error where a contour grazes (a disc carried by
591/// two turns, near its start pose's farthest reach, read its ends 1.7e-9 and
592/// 2.1e-9 rad off an independent 40-digit solve of the extremum, the exact
593/// reading 1e-12 and 1e-15).
594const JET_CHECK_BAR: f64 = 2e-8;
595
596/// The level's gradient (to the scale, per unit of a source's parameter)
597/// below which the extremum Newton keeps the differenced residual: about a
598/// tip, where the contour closes on a point, its ends move as the root of the
599/// level's distance from the tip's, and the two readings of the condition part
600/// by more than either's error away from it (a ball turned about an axis read
601/// its Pappus volume 7x closer differenced).
602const JET_GRADIENT_FLOOR: f64 = 1e-3;
603
604/// How near (to the scale) a critical level a reading counts as at a tip.
605/// There the differenced reading is the one that strays: the rod less a
606/// screwed torus, 1e-5 and 6e-5 above its tip level, read its ends 2.7e-8 and
607/// 1.6e-9 off an independent extremum of the contour (40 digits), the exact
608/// reading 5e-14 and 7e-13.
609const JET_CHECK_TIP: f64 = 1e-4;
610
611/// The check mode's tally on one thread.
612#[derive(Clone, Copy, Debug, Default)]
613pub(crate) struct JetCheck {
614    /// Levels read both ways.
615    pub levels: usize,
616    /// Levels whose readings differ (another count of intervals, an end past
617    /// the bar, or one refusing), away from every tip.
618    pub mismatches: usize,
619    /// Those within `JET_CHECK_TIP` of a critical level.
620    pub near_tip: usize,
621    /// The largest end difference there, to the scale, where both read as
622    /// many intervals.
623    pub worst_tip: f64,
624    /// Levels there read with another count of intervals. A ball turned about
625    /// an axis through its centre's circle: the plain reading holds nothing at
626    /// levels 1e-6 about its centre's, where its poles sit and its whole
627    /// diameter lies; the exact one holds the diameter.
628    pub tip_counts: usize,
629    /// Levels read alike but whose ends two sources name differently (a tie).
630    pub relabelled: usize,
631    /// The largest end difference away from the tips, to the scale.
632    pub worst_end: f64,
633    /// Residuals compared at a Newton's seed, and the largest difference of
634    /// the extremum condition between the two (the differenced one's own error
635    /// included).
636    pub residuals: usize,
637    pub worst_residual: f64,
638}
639
640thread_local! {
641    static JET_CHECK: std::cell::Cell<JetCheck> = std::cell::Cell::new(JetCheck::default());
642}
643
644fn jet_check_record(update: impl FnOnce(&mut JetCheck)) {
645    JET_CHECK.with(|cell| {
646        let mut stats = cell.get();
647        update(&mut stats);
648        cell.set(stats);
649    });
650}
651
652/// This thread's check tally, reset.
653#[allow(dead_code)]
654pub(crate) fn extremum_jet_check_take() -> JetCheck {
655    JET_CHECK.with(|cell| cell.replace(JetCheck::default()))
656}
657
658/// The check mode at a Newton's seed: the exact residual's extremum
659/// condition against the differenced one's.
660fn jet_check_residual(engine: &Engine, source: Source, level: f64, u: f64, v: f64, hu: f64, hv: f64) {
661    let Some((_, (lu, ou), (lv, ov))) = engine.source_reduced_jet(source, u, v) else { return };
662    // About a tip the exact residual is not read (below).
663    if lu.hypot(lv) < JET_GRADIENT_FLOOR * engine.scale {
664        return;
665    }
666    // Where the differences would read past a domain's end (a bar's side clamps there, a closed
667    // section's seam included, so they read half the slope) there is no fair reading to compare with.
668    let (ur, vr, v_periodic) = engine.domain(source);
669    let u_periodic = engine.u_periodic(source) && !matches!(source, Source::BarSide { .. });
670    if (!u_periodic && (u - hu < ur[0] || u + hu > ur[1])) || (!v_periodic && (v - hv < vr[0] || v + hv > vr[1])) {
671        return;
672    }
673    let _ = level;
674    let (lu1, ou1) = engine.source_reduced(source, u + hu, v);
675    let (lu0, ou0) = engine.source_reduced(source, u - hu, v);
676    let (lv1, ov1) = engine.source_reduced(source, u, v + hv);
677    let (lv0, ov0) = engine.source_reduced(source, u, v - hv);
678    let (dlu, dlv) = ((lu1 - lu0) / (2.0 * hu), (lv1 - lv0) / (2.0 * hv));
679    let dou = engine.o_difference(ou1, ou0) / (2.0 * hu);
680    let dov = engine.o_difference(ov1, ov0) / (2.0 * hv);
681    let exact = (ou * lv - ov * lu) / lu.hypot(lv).max(1e-300);
682    let plain = (dou * dlv - dov * dlu) / dlu.hypot(dlv).max(1e-300);
683    // Relative to the condition's own size (that of ∇o).
684    let size = ou.hypot(ov).max(1e-12);
685    jet_check_record(|stats| {
686        stats.residuals += 1;
687        stats.worst_residual = stats.worst_residual.max((exact - plain).abs() / size);
688    });
689}
690
691/// `BREP_SWEEP_LEVEL_EDGES` (default on; `=0` scans the whole grid): a face's crossings of a
692/// level are read from the grid edges whose levels span it, binned once,
693/// instead of every edge of the grid at every level. The same crossings in
694/// the same order: the reading is unchanged to the bit.
695fn level_edges_on() -> bool {
696    crate::switch!("BREP_SWEEP_LEVEL_EDGES", true)
697}
698
699/// `BREP_SWEEP_EDGE_TIPS` (default on; `=0` skips them): a closed edge's
700/// extremum of the level at its parameter's seam is one of its critical
701/// levels too (the scan read interior samples only, so a circle whose seam
702/// sits at its farthest or nearest point lost that tip).
703/// `BREP_SWEEP_APEX_BREAKS` (default on; `=0` reads them as events only): a
704/// solid of revolution's point on its own axis breaks the bands at its level.
705fn apex_breaks_on() -> bool {
706    crate::switch!("BREP_SWEEP_APEX_BREAKS", true)
707}
708
709/// `BREP_SWEEP_BAR_JET` (default on; `=0` differences it): the extremum
710/// Newton's exact residual on a bar's sides too.
711fn bar_jet_on() -> bool {
712    crate::switch!("BREP_SWEEP_BAR_JET", true)
713}
714
715fn edge_tips_on() -> bool {
716    crate::switch!("BREP_SWEEP_EDGE_TIPS", true)
717}
718
719
720fn thread_rows_on() -> bool {
721    crate::switch!("BREP_SWEEP_THREAD_ROWS", true)
722}
723
724/// `BREP_SWEEP_WHOLE_TURN` (default on; `=0` restores the refusal): a turn
725/// through a whole revolution or more about the clip's axis is built even where
726/// its ends lie in the clip; its sweep is the tool's (ρ, z) shadow turned round.
727fn whole_turn_on() -> bool {
728    crate::switch!("BREP_SWEEP_WHOLE_TURN", true)
729}
730
731/// `BREP_SWEEP_WHOLE_LEVEL` (default on; `=0` restores the refusal): a screw's
732/// sweep whose turns meet at a crest, built as the clip less what stays.
733fn whole_level_on() -> bool {
734    crate::switch!("BREP_SWEEP_WHOLE_LEVEL", true)
735}
736
737/// `BREP_SWEEP_SCREW_CARRY` (default on; `=0` restores the cubic loft): every
738/// screw sweep's walls are carried along the screw to high order, as a bar's
739/// and a crest's always are, instead of lofted as a cubic through 64 sections a
740/// turn (which stands r·h⁴/384 off the screw: 1e-6 at a groove's floor).
741fn screw_carry_on() -> bool {
742    crate::switch!("BREP_SWEEP_SCREW_CARRY", true)
743}
744
745/// `BREP_SWEEP_APEX_TIP` (default on; `=0` off): a point of a solid of
746/// revolution on its own axis (a cone's apex) is a critical point of the faces
747/// that meet there. It revolves into nothing, so no edge carries it, and a
748/// groove whose tip it cuts would end where bisection first sees the level's
749/// contour (3.5e-7 short of a cone point's tip) instead of at the point itself.
750fn apex_tip_on() -> bool {
751    crate::switch!("BREP_SWEEP_APEX_TIP", true)
752}
753
754/// `BREP_SWEEP_SEED_BANDS` (default on; `=0` seeds from every tip at every
755/// level): a face's tip seeds the extremum Newton only at levels whose contour
756/// about it could miss every grid node, those within the grid's levels about
757/// it. Beyond them the contour reaches a node and the grid's own crossings
758/// seed it. A face whose level does not change along the motion (a prism's
759/// side turned about its own axis) has a ridge of near-ties that reads as
760/// hundreds of tips, and seeding each at every level was nearly all of a
761/// clipped sweep's time.
762fn seed_bands_on() -> bool {
763    crate::switch!("BREP_SWEEP_SEED_BANDS", true)
764}
765
766/// `BREP_SWEEP_LEAN_WALLS` (default on; `=0` restores the quintic through 48
767/// sections a turn and the cubic through every sample): a carried screw
768/// sweep's walls in few spans. Along the screw, the carry is of degree 2·`LEAN_CARRY_ORDER` + 1
769/// through that many derivatives, `LEAN_CARRY_PER_TURN` spans a turn, instead
770/// of the quintic through 48 (over a crest, 12 spans a turn of degree
771/// 2·`LEAN_CREST_CARRY_ORDER` + 1). Across it, each boundary piece is a quintic
772/// fitted to its exact envelope samples and checked against the exact envelope
773/// between them (`lean_fit_piece`), instead of the cubic through all of them.
774/// Off, a wall has some 100 by 84 spans: a reader that integrates over its
775/// spans pays their product.
776fn lean_walls_on() -> bool {
777    crate::switch!("BREP_SWEEP_LEAN_WALLS", true)
778}
779
780/// Derivatives the lean carry matches at each span's ends (degree 2m + 1, C^m
781/// at the joints). Its error is r·(h/2)^(2m+2)/(2m+2)!: at m = 4 and eight
782/// spans a turn, 2.4e-11·r.
783const LEAN_CARRY_ORDER: usize = 4;
784
785/// Spans of the lean carry a turn.
786const LEAN_CARRY_PER_TURN: f64 = 8.0;
787
788/// Derivatives the lean carry matches over a crest, where a thread's walls
789/// keep 12 spans a turn: degree 7, whose error there is r·(h/2)^8/8! =
790/// 5.5e-10·r. Every reading of a wall (its sections, classification, the
791/// mass check) costs about half what it does at degree 9, and the degree-9
792/// carry gains nothing over a crest: on a fine thread whose crests are sharp
793/// the cut took twice as long at degree 9, its volume and area no nearer
794/// their closed forms (within 6.5e-10 and 7.5e-10 of them, against 3.2e-10
795/// and 2e-11 at degree 7).
796const LEAN_CREST_CARRY_ORDER: usize = 3;
797
798/// Derivatives the lean carry matches on `engine`'s walls.
799fn lean_carry_order(engine: &Engine) -> usize {
800    if engine.crest_gap {
801        LEAN_CREST_CARRY_ORDER
802    } else {
803        LEAN_CARRY_ORDER
804    }
805}
806
807/// How near (of the scale) the exact envelope a lean boundary piece passes at
808/// the mid-points between its samples, where the cubic it replaces passes
809/// further from it: a tenth of what `sample_band` holds that cubic to.
810const LEAN_FIT_TOLERANCE: f64 = 1e-9;
811
812fn refuse(what: &'static str, message: String) -> KernelRefusal {
813    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{SOLID_SWEEP_REFUSAL}: {message}"))
814}
815
816fn rotate(x: Vec3, origin: Vec3, axis: Vec3, angle: f64) -> Vec3 {
817    origin.add(x.sub(origin).rotate_about(axis, angle))
818}
819
820impl ScrewStep {
821    fn apply(&self, t: f64, x: Vec3, axis: Vec3) -> Vec3 {
822        rotate(x, self.axis_origin, axis, self.turn * t).add(axis.scale(self.advance * t))
823    }
824    fn invert(&self, t: f64, x: Vec3, axis: Vec3) -> Vec3 {
825        rotate(x.sub(axis.scale(self.advance * t)), self.axis_origin, axis, -self.turn * t)
826    }
827}
828
829/// Orthonormal frame of the clip: (ex, ey, ez).
830#[derive(Clone, Copy, Debug)]
831struct Frame {
832    origin: Vec3,
833    ex: Vec3,
834    ey: Vec3,
835    ez: Vec3,
836}
837
838impl Frame {
839    fn local(&self, x: Vec3) -> [f64; 3] {
840        let d = x.sub(self.origin);
841        [d.dot(self.ex), d.dot(self.ey), d.dot(self.ez)]
842    }
843    fn world(&self, p: [f64; 3]) -> Vec3 {
844        self.origin
845            .add(self.ex.scale(p[0]))
846            .add(self.ey.scale(p[1]))
847            .add(self.ez.scale(p[2]))
848    }
849}
850
851#[derive(Clone, Copy, Debug, PartialEq)]
852enum Class {
853    /// Axial advance per radian of the screw, in the clip frame (nonzero).
854    Screw(f64),
855    Turn,
856    Planar,
857}
858
859/// A tool-boundary source: a face patch over a 2D parameter box, or an edge
860/// over a 1D parameter interval. `periodic` marks a parameter that wraps.
861#[derive(Clone, Copy, Debug)]
862enum Source {
863    /// Revolved meridian piece `piece`, parameters (s ∈ [0,1], φ ∈ [0,2π)).
864    RevolvedFace { piece: usize },
865    /// Revolved meridian corner at the start of piece `piece`, parameter φ.
866    RevolvedCorner { piece: usize },
867    /// Prism outline piece `piece` carried through time: (s ∈ [0,1], t).
868    PrismFace { piece: usize },
869    /// Prism outline vertex at the start of piece `piece`, parameter t.
870    PrismVertex { piece: usize },
871    /// Prism outline piece `piece` at the motion's first (`end = false`) or last
872    /// position, parameter s.
873    PrismEnd { piece: usize, end: bool },
874    /// Under a screw, at the tool's own place (the screw's reduction is invariant
875    /// along it): side face of outline piece `piece`, (s ∈ [0,1], height).
876    ScrewPrismSide { piece: usize },
877    /// Under a screw: the upright edge at the start of piece `piece`, parameter height.
878    ScrewPrismEdge { piece: usize },
879    /// Under a screw: outline piece `piece` at the prism's low (`end = false`) or
880    /// high end, parameter s. An end cap itself maps one-to-one into the reduced
881    /// plane (polar coordinates at a fixed height), so only its rim can bound.
882    ScrewPrismRim { piece: usize, end: bool },
883    /// A bar's side on section curve `piece`, at its own place: (s ∈ [0,1], height).
884    BarSide { piece: usize },
885    /// A bar's upright edge at the start of section curve `piece`, parameter height.
886    BarEdge { piece: usize },
887    /// A bar's section curve `piece` at its low (`end = false`) or high end, parameter s.
888    BarRim { piece: usize, end: bool },
889}
890
891struct Engine<'a> {
892    tool: &'a SweptTool,
893    motion: &'a SolidMotion,
894    axes: Vec<Vec3>,
895    frame: Frame,
896    class: Class,
897    clip: &'a SweepClip,
898    /// The tool as a bar, where it is swept as one.
899    bar: Option<crate::solid_sweep_bar::Bar>,
900    /// The clip was narrowed to a crest level: below it some material is left.
901    crest_gap: bool,
902    sources: Vec<Source>,
903    /// Per face source: its parameter grid (nu × nv) of reduced coordinates.
904    grids: Vec<Option<Grid>>,
905    /// Per source: its critical points of the level, as (level, o).
906    critical: Vec<Vec<(f64, f64)>>,
907    /// Per face source: the parameters of its critical points (tips), which
908    /// seed the extremum Newton where the level's contour is smaller than a cell.
909    critical_params: Vec<Vec<(f64, f64)>>,
910    /// Per face source, beside each of `critical_params`: the levels a contour
911    /// about that tip can hold without reaching a grid node (the range of the
912    /// grid's levels about it, and the tip's own), or `None` for a fold or
913    /// kink, which seeds at every level.
914    critical_bands: Vec<Vec<Option<[f64; 2]>>>,
915    /// Angular `o` (wraps at 2π) or not.
916    angular: bool,
917    /// Prism height (along its normal) the planar sources are evaluated at.
918    prism_height: f64,
919    scale: f64,
920    /// `intervals_at` by level bits: the sampling revisits levels (a refined
921    /// band keeps every level of the coarser one).
922    cache: std::cell::RefCell<std::collections::HashMap<u64, Vec<Interval>>>,
923    /// The motion ends where it began as a set (the plus wheel: one turn of the
924    /// wheel, one and a half of the tool), so there are no end positions; piece
925    /// `k` at the end continues as piece `wrap[k]` at the start.
926    wrap: Option<Vec<usize>>,
927    /// Per edge source (under `fast_levels_on`): its samples' parameters and
928    /// levels, which do not depend on the level read.
929    edge_samples: std::cell::RefCell<std::collections::HashMap<usize, std::rc::Rc<Vec<(f64, f64)>>>>,
930    /// Debug counters: (levels evaluated, oracle calls, oracle steps, seconds in
931    /// candidates, seconds in the oracle).
932    counters: std::cell::Cell<(usize, usize, usize, f64, f64)>,
933    /// The extremum Newton reads its residual exactly ([`extremum_jet_on`]).
934    /// Under the check mode it starts off, so every reading answers as the
935    /// plain one, and is flipped only to read a level the second way.
936    jet: std::cell::Cell<bool>,
937    /// The tool's own frame, as [`tool_frame`] reads it once.
938    tool_frame: [Vec3; 3],
939}
940
941struct Grid {
942    nu: usize,
943    nv: usize,
944    u: [f64; 2],
945    v: [f64; 2],
946    v_periodic: bool,
947    values: Vec<(f64, f64)>,
948    /// Its edges by the levels they span ([`level_edges_on`]), made on first use.
949    edges: std::cell::OnceCell<EdgeIndex>,
950}
951
952/// A grid's edges binned by the levels they span. Edge ids run as the whole
953/// scan meets them: those along v from each node row by row (`i · jmax + j`),
954/// then those along u (`nu · jmax + i · nv + j`).
955struct EdgeIndex {
956    low: f64,
957    width: f64,
958    bins: Vec<Vec<u32>>,
959}
960
961impl EdgeIndex {
962    const BINS: usize = 1024;
963
964    /// The ids of every edge whose two levels hold `level` between them (with
965    /// a margin), ascending; the caller's own test decides each.
966    fn spanning(&self, level: f64) -> Vec<u32> {
967        if self.bins.is_empty() || !level.is_finite() {
968            return Vec::new();
969        }
970        let k = if self.width > 0.0 { ((level - self.low) / self.width).floor() } else { 0.0 };
971        if !(k >= -1.0 && k <= Self::BINS as f64) {
972            return Vec::new();
973        }
974        let k = (k.max(0.0) as usize).min(Self::BINS - 1);
975        self.bins[k].clone()
976    }
977}
978
979impl Grid {
980    fn edges(&self) -> &EdgeIndex {
981        self.edges.get_or_init(|| {
982            let at = |i: usize, j: usize| self.values[i * self.nv + j % self.nv].0;
983            let jmax = if self.v_periodic { self.nv } else { self.nv - 1 };
984            let mut spans: Vec<(u32, f64, f64)> = Vec::with_capacity(2 * self.nu * self.nv);
985            let mut push = |id: usize, a: f64, b: f64| {
986                // An edge whose ends share a level, or carry no number, never crosses.
987                if a != b && a.is_finite() && b.is_finite() {
988                    spans.push((id as u32, a.min(b), a.max(b)));
989                }
990            };
991            for i in 0..self.nu {
992                for j in 0..jmax {
993                    push(i * jmax + j, at(i, j), at(i, j + 1));
994                }
995            }
996            for i in 0..self.nu.saturating_sub(1) {
997                for j in 0..self.nv {
998                    push(self.nu * jmax + i * self.nv + j, at(i, j), at(i + 1, j));
999                }
1000            }
1001            if spans.is_empty() {
1002                return EdgeIndex { low: 0.0, width: 0.0, bins: Vec::new() };
1003            }
1004            let low = spans.iter().map(|s| s.1).fold(f64::INFINITY, f64::min);
1005            let high = spans.iter().map(|s| s.2).fold(f64::NEG_INFINITY, f64::max);
1006            let width = (high - low) / EdgeIndex::BINS as f64;
1007            // A margin well past where the scan's product test could read a
1008            // crossing outside an edge's levels (its product underflowing).
1009            let pad = (1e-9 * (high - low)).max(1e-150);
1010            let bin = |x: f64| -> usize {
1011                if width > 0.0 {
1012                    (((x - low) / width).floor().max(0.0) as usize).min(EdgeIndex::BINS - 1)
1013                } else {
1014                    0
1015                }
1016            };
1017            let mut bins = vec![Vec::new(); EdgeIndex::BINS];
1018            for &(id, lo, hi) in &spans {
1019                for k in bin(lo - pad)..=bin(hi + pad) {
1020                    bins[k].push(id);
1021                }
1022            }
1023            EdgeIndex { low, width, bins }
1024        })
1025    }
1026}
1027
1028/// One interval of the region at a level, with the sources of its ends.
1029#[derive(Clone, Copy, Debug)]
1030struct Interval {
1031    lo: f64,
1032    hi: f64,
1033    lo_source: usize,
1034    hi_source: usize,
1035}
1036
1037/// The switch for the level engine's walk speed about one line (default
1038/// on; `BREP_SWEEP_LINE_SPEED=0` restores the reach grown by every advance).
1039pub fn line_speed_on() -> bool {
1040    crate::switch!("BREP_SWEEP_LINE_SPEED", true)
1041}
1042
1043/// The frame a tool's points are read in: a solid of revolution's axis and
1044/// its two radial directions (the radial one square to the axis), or a
1045/// prism's normal, its outline's first axis and the second (the normal
1046/// across the first). Zero for a bar.
1047fn tool_frame(tool: &SweptTool) -> [Vec3; 3] {
1048    match tool {
1049        SweptTool::Revolved { axis_direction, radial, .. } => {
1050            let axis = axis_direction.normalized_or(*axis_direction);
1051            let r0 = radial.sub(axis.scale(radial.dot(axis))).normalized_or(*radial);
1052            [axis, r0, axis.cross(r0)]
1053        }
1054        SweptTool::Prism { normal, x_axis, .. } => {
1055            let n = normal.normalized_or(*normal);
1056            let xa = x_axis.normalized_or(*x_axis);
1057            [n, xa, n.cross(xa)]
1058        }
1059        SweptTool::Bar { .. } => [Vec3::new(0.0, 0.0, 0.0); 3],
1060    }
1061}
1062
1063fn wrap_pi(angle: f64) -> f64 {
1064    let wrapped = (angle + PI).rem_euclid(TAU) - PI;
1065    wrapped
1066}
1067
1068impl<'a> Engine<'a> {
1069    fn motion_apply(&self, t: f64, x: Vec3) -> Vec3 {
1070        self.motion
1071            .steps
1072            .iter()
1073            .zip(&self.axes)
1074            .fold(x, |x, (step, axis)| step.apply(t, x, *axis))
1075    }
1076
1077    fn motion_invert(&self, t: f64, x: Vec3) -> Vec3 {
1078        self.motion
1079            .steps
1080            .iter()
1081            .zip(&self.axes)
1082            .rev()
1083            .fold(x, |x, (step, axis)| step.invert(t, x, *axis))
1084    }
1085
1086    /// Reduced coordinates of a clip-frame point.
1087    fn reduce(&self, p: [f64; 3]) -> (f64, f64) {
1088        let level = p[0].hypot(p[1]);
1089        match self.class {
1090            Class::Screw(c) => (level, p[1].atan2(p[0]) - p[2] / c),
1091            Class::Turn => (level, p[2]),
1092            Class::Planar => (level, p[1].atan2(p[0])),
1093        }
1094    }
1095
1096    fn tool_signed_distance(&self, x: Vec3) -> f64 {
1097        if let Some(bar) = &self.bar {
1098            return bar.signed_distance(x);
1099        }
1100        match self.tool {
1101            SweptTool::Bar { .. } => f64::INFINITY,
1102            SweptTool::Revolved { axis_origin, meridian, .. } => {
1103                let [axis, _, _] = self.tool_frame;
1104                let d = x.sub(*axis_origin);
1105                let e = d.dot(axis);
1106                let radial = d.sub(axis.scale(e)).length();
1107                outline_signed_distance(meridian, [radial, e])
1108            }
1109            SweptTool::Prism { origin, outline, from, to, .. } => {
1110                let [n, xa, ya] = self.tool_frame;
1111                let d = x.sub(*origin);
1112                let h = d.dot(n);
1113                let planar = outline_signed_distance(outline, [d.dot(xa), d.dot(ya)]);
1114                planar.max(from - h).max(h - to)
1115            }
1116        }
1117    }
1118
1119    /// The world point of a source at its parameters (at the tool's own place
1120    /// for revolved tools; carried by the motion for prisms).
1121    fn source_point(&self, source: Source, u: f64, v: f64) -> Vec3 {
1122        if let Some(bar) = &self.bar {
1123            match source {
1124                Source::BarSide { piece } => return bar.side(piece, u, v),
1125                Source::BarEdge { piece } => return bar.joint(piece, u),
1126                Source::BarRim { piece, end } => return bar.side(piece, u, if end { bar.to } else { bar.from }),
1127                _ => {}
1128            }
1129        }
1130        match (self.tool, source) {
1131            (SweptTool::Bar { origin, .. }, _) => *origin,
1132            (SweptTool::Revolved { axis_origin, meridian, .. }, _) => {
1133                let [axis, r0, r1] = self.tool_frame;
1134                let (m, phi) = match source {
1135                    Source::RevolvedFace { piece } => (meridian[piece].point(u), v),
1136                    Source::RevolvedCorner { piece } => (meridian[piece].point(0.0), u),
1137                    _ => unreachable!(),
1138                };
1139                axis_origin
1140                    .add(r0.scale(m[0] * phi.cos()))
1141                    .add(r1.scale(m[0] * phi.sin()))
1142                    .add(axis.scale(m[1]))
1143            }
1144            (SweptTool::Prism { origin, outline, from, to, .. }, _) => {
1145                let [n, xa, ya] = self.tool_frame;
1146                let at_own_place = match source {
1147                    Source::ScrewPrismSide { piece } => Some((outline[piece].point(u), v)),
1148                    Source::ScrewPrismEdge { piece } => Some((outline[piece].point(0.0), u)),
1149                    Source::ScrewPrismRim { piece, end } => Some((outline[piece].point(u), if end { *to } else { *from })),
1150                    _ => None,
1151                };
1152                if let Some((q, h)) = at_own_place {
1153                    return origin.add(xa.scale(q[0])).add(ya.scale(q[1])).add(n.scale(h));
1154                }
1155                let (q, t) = match source {
1156                    Source::PrismFace { piece } => (outline[piece].point(u), v),
1157                    Source::PrismVertex { piece } => (outline[piece].point(0.0), u),
1158                    Source::PrismEnd { piece, end } => (
1159                        outline[piece].point(u),
1160                        if end { self.motion.to } else { self.motion.from },
1161                    ),
1162                    _ => unreachable!(),
1163                };
1164                let x = origin
1165                    .add(xa.scale(q[0]))
1166                    .add(ya.scale(q[1]))
1167                    .add(n.scale(self.prism_height));
1168                self.motion_apply(t, x)
1169            }
1170        }
1171    }
1172
1173    fn source_reduced(&self, source: Source, u: f64, v: f64) -> (f64, f64) {
1174        self.reduce(self.frame.local(self.source_point(source, u, v)))
1175    }
1176
1177    /// A face source's world point and its derivatives along its two
1178    /// parameters, where they are read exactly (a solid of revolution's face, a
1179    /// prism's side at its own place or carried through the motion); `None` for
1180    /// a bar's side, whose caller differences instead.
1181    fn source_point_jet(&self, source: Source, u: f64, v: f64) -> Option<(Vec3, Vec3, Vec3)> {
1182        if let Some(bar) = &self.bar {
1183            // A bar's side at its own place (`BREP_SWEEP_BAR_JET`, default on; `=0` differences it).
1184            return match source {
1185                Source::BarSide { piece } if bar_jet_on() => bar.side_jet(piece, u, v),
1186                _ => None,
1187            };
1188        }
1189        // A solid of revolution's face: its point as `source_point` writes it
1190        // (the same products, to the bit), the trigonometry shared with the derivatives.
1191        if let (SweptTool::Revolved { axis_origin, meridian, .. }, Source::RevolvedFace { piece }) = (self.tool, source) {
1192            let [axis, r0, r1] = self.tool_frame;
1193            let (m, dm) = match meridian[piece] {
1194                OutlinePiece::Arc { centre, radius, start, end } => {
1195                    let angle = start + (end - start) * u;
1196                    let (sa, ca) = (angle.sin(), angle.cos());
1197                    let k = radius * (end - start);
1198                    ([centre[0] + radius * ca, centre[1] + radius * sa], [-k * sa, k * ca])
1199                }
1200                ref other => (other.point(u), other.tangent(u)),
1201            };
1202            let (sin, cos) = (v.sin(), v.cos());
1203            let point = axis_origin.add(r0.scale(m[0] * cos)).add(r1.scale(m[0] * sin)).add(axis.scale(m[1]));
1204            let du = r0.scale(dm[0] * cos).add(r1.scale(dm[0] * sin)).add(axis.scale(dm[1]));
1205            let dv = r0.scale(-m[0] * sin).add(r1.scale(m[0] * cos));
1206            return Some((point, du, dv));
1207        }
1208        let point = self.source_point(source, u, v);
1209        match (self.tool, source) {
1210            (SweptTool::Prism { outline, .. }, Source::ScrewPrismSide { piece }) => {
1211                let [n, xa, ya] = self.tool_frame;
1212                let dq = outline[piece].tangent(u);
1213                Some((point, xa.scale(dq[0]).add(ya.scale(dq[1])), n))
1214            }
1215            (SweptTool::Prism { origin, outline, .. }, Source::PrismFace { piece }) => {
1216                let [n, xa, ya] = self.tool_frame;
1217                let (q, dq) = (outline[piece].point(u), outline[piece].tangent(u));
1218                // Carried step by step: each turns the point and both derivatives,
1219                // and adds its own velocity to the derivative along time.
1220                let mut x = origin.add(xa.scale(q[0])).add(ya.scale(q[1])).add(n.scale(self.prism_height));
1221                let mut du = xa.scale(dq[0]).add(ya.scale(dq[1]));
1222                let mut dv = Vec3::new(0.0, 0.0, 0.0);
1223                for (step, axis) in self.motion.steps.iter().zip(&self.axes) {
1224                    let angle = step.turn * v;
1225                    let arm = x.sub(step.axis_origin).rotate_about(*axis, angle);
1226                    du = du.rotate_about(*axis, angle);
1227                    dv = dv.rotate_about(*axis, angle).add(axis.cross(arm).scale(step.turn)).add(axis.scale(step.advance));
1228                    x = step.apply(v, x, *axis);
1229                }
1230                Some((point, du, dv))
1231            }
1232            _ => None,
1233        }
1234    }
1235
1236    /// The reduced coordinates of a face source and their derivatives along its
1237    /// two parameters: `(ℓ, (ℓᵤ, oᵤ), (ℓᵥ, oᵥ))` (the Newton's residual reads no
1238    /// `o`). The level is [`Self::source_reduced`]'s to the bit. `None` where the source is not read
1239    /// exactly, or the point lies within a hair of the clip's axis (where the
1240    /// polar coordinates have no derivative).
1241    fn source_reduced_jet(&self, source: Source, u: f64, v: f64) -> Option<(f64, (f64, f64), (f64, f64))> {
1242        let (point, du, dv) = self.source_point_jet(source, u, v)?;
1243        let p = self.frame.local(point);
1244        let level = p[0].hypot(p[1]);
1245        if !(level > 1e-9 * self.scale) {
1246            return None;
1247        }
1248        let along = |d: Vec3| -> (f64, f64) {
1249            let q = [d.dot(self.frame.ex), d.dot(self.frame.ey), d.dot(self.frame.ez)];
1250            let dl = (p[0] * q[0] + p[1] * q[1]) / level;
1251            let dangle = (p[0] * q[1] - p[1] * q[0]) / (level * level);
1252            let o = match self.class {
1253                Class::Screw(c) => dangle - q[2] / c,
1254                Class::Turn => q[2],
1255                Class::Planar => dangle,
1256            };
1257            (dl, o)
1258        };
1259        Some((level, along(du), along(dv)))
1260    }
1261
1262    fn is_face(source: Source) -> bool {
1263        matches!(source, Source::RevolvedFace { .. } | Source::PrismFace { .. } | Source::ScrewPrismSide { .. } | Source::BarSide { .. })
1264    }
1265
1266    /// Parameter domain of a source: (u range, v range, v periodic).
1267    fn domain(&self, source: Source) -> ([f64; 2], [f64; 2], bool) {
1268        let time = [self.motion.from, self.motion.to];
1269        match source {
1270            Source::RevolvedFace { .. } => ([0.0, 1.0], [0.0, TAU], true),
1271            Source::RevolvedCorner { .. } => ([0.0, TAU], [0.0, 0.0], false),
1272            Source::PrismFace { .. } => ([0.0, 1.0], time, false),
1273            Source::PrismVertex { .. } => (time, [0.0, 0.0], false),
1274            Source::PrismEnd { .. } => ([0.0, 1.0], [0.0, 0.0], false),
1275            Source::ScrewPrismSide { .. } => ([0.0, 1.0], self.prism_extent(), false),
1276            Source::ScrewPrismEdge { .. } => (self.prism_extent(), [0.0, 0.0], false),
1277            Source::ScrewPrismRim { .. } => ([0.0, 1.0], [0.0, 0.0], false),
1278            Source::BarSide { .. } => ([0.0, 1.0], self.prism_extent(), false),
1279            Source::BarEdge { .. } => (self.prism_extent(), [0.0, 0.0], false),
1280            Source::BarRim { .. } => ([0.0, 1.0], [0.0, 0.0], false),
1281        }
1282    }
1283
1284    fn prism_extent(&self) -> [f64; 2] {
1285        if let Some(bar) = &self.bar {
1286            return [bar.from, bar.to];
1287        }
1288        match self.tool {
1289            SweptTool::Bar { from, to, .. } => [*from, *to],
1290            SweptTool::Prism { from, to, .. } => [*from, *to],
1291            SweptTool::Revolved { .. } => [0.0, 0.0],
1292        }
1293    }
1294
1295    /// Is the face's first parameter periodic (a full circle in the meridian or
1296    /// outline, which has no corner to bound it)?
1297    fn u_periodic(&self, source: Source) -> bool {
1298        match (self.tool, source) {
1299            (_, Source::BarSide { .. }) => self.bar.as_ref().is_some_and(|bar| bar.periodic),
1300            (SweptTool::Revolved { meridian, .. }, Source::RevolvedFace { piece }) => meridian[piece].is_full_circle(),
1301            (SweptTool::Prism { outline, .. }, Source::PrismFace { piece } | Source::ScrewPrismSide { piece }) => outline[piece].is_full_circle(),
1302            _ => false,
1303        }
1304    }
1305
1306    /// Is an edge source a closed curve in its parameter (a revolved corner's
1307    /// circle about the tool's axis, a whole circle of a prism's outline)? A
1308    /// bar's rim is left out: its spline is not read past its ends.
1309    fn edge_periodic(&self, source: Source) -> bool {
1310        match (self.tool, source) {
1311            (_, Source::RevolvedCorner { .. }) => true,
1312            (SweptTool::Prism { outline, .. }, Source::PrismEnd { piece, .. } | Source::ScrewPrismRim { piece, .. }) => outline[piece].is_full_circle(),
1313            _ => false,
1314        }
1315    }
1316
1317    fn o_difference(&self, a: f64, b: f64) -> f64 {
1318        if self.angular {
1319            wrap_pi(a - b)
1320        } else {
1321            a - b
1322        }
1323    }
1324
1325    /// Newton on {ℓ = level, det(∇o, ∇ℓ) = 0} over a face source.
1326    fn face_extremum(&self, source: Source, level: f64, mut u: f64, mut v: f64) -> Option<(f64, f64, f64)> {
1327        let (ur, vr, periodic) = self.domain(source);
1328        let hu = 1e-6 * (ur[1] - ur[0]).max(1e-3);
1329        let hv = 1e-6 * (vr[1] - vr[0]).max(1e-3);
1330        let jet = self.jet.get();
1331        if extremum_jet_check_on() {
1332            jet_check_residual(self, source, level, u, v, hu, hv);
1333        }
1334        let residual = |u: f64, v: f64| -> [f64; 2] {
1335            if jet {
1336                if let Some((l, (lu, ou), (lv, ov))) = self.source_reduced_jet(source, u, v) {
1337                    let norm = lu.hypot(lv);
1338                    if norm >= JET_GRADIENT_FLOOR * self.scale {
1339                        return [l - level, (ou * lv - ov * lu) / norm];
1340                    }
1341                }
1342            }
1343            let (l, o) = self.source_reduced(source, u, v);
1344            let (lu1, ou1) = self.source_reduced(source, u + hu, v);
1345            let (lu0, ou0) = self.source_reduced(source, u - hu, v);
1346            let (lv1, ov1) = self.source_reduced(source, u, v + hv);
1347            let (lv0, ov0) = self.source_reduced(source, u, v - hv);
1348            let (lu, lv) = ((lu1 - lu0) / (2.0 * hu), (lv1 - lv0) / (2.0 * hv));
1349            let ou = self.o_difference(ou1, ou0) / (2.0 * hu);
1350            let ov = self.o_difference(ov1, ov0) / (2.0 * hv);
1351            // det scaled by the level's gradient so its size is that of ∇o.
1352            let norm = lu.hypot(lv).max(1e-300);
1353            let _ = o;
1354            [l - level, (ou * lv - ov * lu) / norm]
1355        };
1356        let mut f = residual(u, v);
1357        // Under `fast_levels_on`, stop once the residual is far inside what
1358        // is accepted below (1e-10 of the scale, 1e-6): past that the
1359        // differenced Jacobian is noise, and the line search only fails.
1360        let settled = |f: [f64; 2]| fast_levels_on() && f[0].abs() <= 1e-13 * self.scale && f[1].abs() <= 1e-10;
1361        for _ in 0..60 {
1362            if settled(f) {
1363                break;
1364            }
1365            let (du_step, dv_step) = (hu * 10.0, hv * 10.0);
1366            let fu1 = residual(u + du_step, v);
1367            let fu0 = residual(u - du_step, v);
1368            let fv1 = residual(u, v + dv_step);
1369            let fv0 = residual(u, v - dv_step);
1370            let j = [
1371                [(fu1[0] - fu0[0]) / (2.0 * du_step), (fv1[0] - fv0[0]) / (2.0 * dv_step)],
1372                [(fu1[1] - fu0[1]) / (2.0 * du_step), (fv1[1] - fv0[1]) / (2.0 * dv_step)],
1373            ];
1374            let det = j[0][0] * j[1][1] - j[0][1] * j[1][0];
1375            if !det.is_finite() || det.abs() < 1e-300 {
1376                return None;
1377            }
1378            let du = -(f[0] * j[1][1] - f[1] * j[0][1]) / det;
1379            let dv = -(j[0][0] * f[1] - j[1][0] * f[0]) / det;
1380            let norm0 = f[0].hypot(f[1]);
1381            let mut step = 1.0;
1382            let mut accepted = false;
1383            while step > 1e-4 {
1384                let (nu, nv) = (u + step * du, v + step * dv);
1385                let candidate = residual(nu, nv);
1386                if candidate[0].hypot(candidate[1]) < norm0 || norm0 < 1e-14 * self.scale {
1387                    u = nu;
1388                    v = nv;
1389                    f = candidate;
1390                    accepted = true;
1391                    break;
1392                }
1393                step *= 0.5;
1394            }
1395            if !accepted {
1396                break;
1397            }
1398            if (du * step).abs() < 1e-15 * (ur[1] - ur[0]) && (dv * step).abs() < 1e-15 * (vr[1] - vr[0]).max(1.0) {
1399                break;
1400            }
1401        }
1402        if periodic {
1403            v = vr[0] + (v - vr[0]).rem_euclid(vr[1] - vr[0]);
1404        }
1405        if self.u_periodic(source) {
1406            u = ur[0] + (u - ur[0]).rem_euclid(ur[1] - ur[0]);
1407        }
1408        let tolerance = 1e-9;
1409        if u < ur[0] - tolerance || u > ur[1] + tolerance || (!periodic && (v < vr[0] - tolerance || v > vr[1] + tolerance)) {
1410            return None;
1411        }
1412        if f[0].abs() > 1e-10 * self.scale || f[1].abs() > 1e-6 {
1413            return None;
1414        }
1415        let (l, o) = self.source_reduced(source, u.clamp(ur[0], ur[1]), v);
1416        Some((l, o, u))
1417    }
1418
1419    fn build_grid(&self, source: Source) -> Grid {
1420        let (u, v, v_periodic) = self.domain(source);
1421        let (nu, nv) = match source {
1422            Source::RevolvedFace { .. } => (64, 256),
1423            Source::ScrewPrismSide { .. } => (64, 64),
1424            Source::BarSide { .. } => (128, 64),
1425            _ => {
1426                let turn = self
1427                    .motion
1428                    .steps
1429                    .iter()
1430                    .map(|step| step.turn.abs())
1431                    .fold(0.0, f64::max)
1432                    * (self.motion.to - self.motion.from).abs();
1433                (48, ((turn * 128.0) as usize).clamp(256, 4096))
1434            }
1435        };
1436        let mut values = Vec::with_capacity(nu * nv);
1437        for i in 0..nu {
1438            let uu = u[0] + (u[1] - u[0]) * i as f64 / (nu - 1) as f64;
1439            for j in 0..nv {
1440                let vv = if v_periodic {
1441                    v[0] + (v[1] - v[0]) * j as f64 / nv as f64
1442                } else {
1443                    v[0] + (v[1] - v[0]) * j as f64 / (nv - 1) as f64
1444                };
1445                values.push(self.source_reduced(source, uu, vv));
1446            }
1447        }
1448        Grid { nu, nv, u, v, v_periodic, values, edges: std::cell::OnceCell::new() }
1449    }
1450
1451    fn grid_param(grid: &Grid, i: usize, j: usize) -> (f64, f64) {
1452        let u = grid.u[0] + (grid.u[1] - grid.u[0]) * i as f64 / (grid.nu - 1) as f64;
1453        let v = if grid.v_periodic {
1454            grid.v[0] + (grid.v[1] - grid.v[0]) * j as f64 / grid.nv as f64
1455        } else {
1456            grid.v[0] + (grid.v[1] - grid.v[0]) * j as f64 / (grid.nv - 1) as f64
1457        };
1458        (u, v)
1459    }
1460
1461    /// Candidates of one source at a level: (o, source index).
1462    fn source_candidates(&self, index: usize, level: f64, out: &mut Vec<(f64, usize)>) {
1463        let gated = seed_bands_on();
1464        let source = self.sources[index];
1465        if Self::is_face(source) {
1466            let grid = self.grids[index].as_ref().expect("face grid");
1467            // Crossings of the level along grid edges, then seeds where o is a
1468            // local extremum among the crossings of neighbouring cells.
1469            let at = |i: usize, j: usize| grid.values[i * grid.nv + j % grid.nv];
1470            let jmax = if grid.v_periodic { grid.nv } else { grid.nv - 1 };
1471            let mut crossings: Vec<(usize, usize, f64, f64, f64)> = Vec::new();
1472            // The crossing of the edge from node (i, j) along v, or along u.
1473            let along_v = |crossings: &mut Vec<(usize, usize, f64, f64, f64)>, i: usize, j: usize| {
1474                let a = at(i, j);
1475                let b = at(i, j + 1);
1476                if (a.0 - level) * (b.0 - level) <= 0.0 && a.0 != b.0 {
1477                    let w = (level - a.0) / (b.0 - a.0);
1478                    let o = a.1 + self.o_difference(b.1, a.1) * w;
1479                    let (u, v0) = Self::grid_param(grid, i, j);
1480                    let (_, v1) = Self::grid_param(grid, i, j + 1);
1481                    let v1 = if grid.v_periodic && j + 1 == grid.nv { grid.v[1] } else { v1 };
1482                    crossings.push((i, j, o, u, v0 + (v1 - v0) * w));
1483                }
1484            };
1485            let along_u = |crossings: &mut Vec<(usize, usize, f64, f64, f64)>, i: usize, j: usize| {
1486                let a = at(i, j);
1487                let b = at(i + 1, j);
1488                if (a.0 - level) * (b.0 - level) <= 0.0 && a.0 != b.0 {
1489                    let w = (level - a.0) / (b.0 - a.0);
1490                    let o = a.1 + self.o_difference(b.1, a.1) * w;
1491                    let (u0, v) = Self::grid_param(grid, i, j);
1492                    let (u1, _) = Self::grid_param(grid, i + 1, j);
1493                    crossings.push((i, j, o, u0 + (u1 - u0) * w, v));
1494                }
1495            };
1496            if level_edges_on() {
1497                // Only the edges whose levels span this one, in the order the
1498                // whole scan below meets them.
1499                for id in grid.edges().spanning(level) {
1500                    let id = id as usize;
1501                    if id < grid.nu * jmax {
1502                        along_v(&mut crossings, id / jmax, id % jmax);
1503                    } else {
1504                        let id = id - grid.nu * jmax;
1505                        along_u(&mut crossings, id / grid.nv, id % grid.nv);
1506                    }
1507                }
1508            } else {
1509                for i in 0..grid.nu {
1510                    for j in 0..jmax {
1511                        along_v(&mut crossings, i, j);
1512                    }
1513                }
1514                for i in 0..grid.nu.saturating_sub(1) {
1515                    for j in 0..grid.nv {
1516                        along_u(&mut crossings, i, j);
1517                    }
1518                }
1519            }
1520            let mut found: Vec<(f64, f64, f64)> = Vec::new();
1521            let push = |found: &mut Vec<(f64, f64, f64)>, result: Option<(f64, f64, f64)>| {
1522                if let Some((_, o_new, u_new)) = result {
1523                    if !found
1524                        .iter()
1525                        .any(|&(o_old, u_old, _)| self.o_difference(o_old, o_new).abs() < 1e-11 && (u_old - u_new).abs() < 1e-6)
1526                    {
1527                        found.push((o_new, u_new, 0.0));
1528                    }
1529                }
1530            };
1531            // Near a tip the contour can be smaller than a cell: seed from the
1532            // tip itself, pushed off it in four directions.
1533            if let Some(params) = self.critical_params.get(index) {
1534                let (ur, vr, _) = self.domain(source);
1535                let bands = self.critical_bands.get(index);
1536                let pad = 1e-9 * self.scale;
1537                for (k, &(u, v)) in params.iter().enumerate() {
1538                    if gated {
1539                        if let Some(Some([low, high])) = bands.and_then(|bands| bands.get(k)) {
1540                            if level < low - pad || level > high + pad {
1541                                continue;
1542                            }
1543                        }
1544                    }
1545                    for (du, dv) in [(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] {
1546                        let (su, sv) = (u + du * 1e-3 * (ur[1] - ur[0]), v + dv * 1e-3 * (vr[1] - vr[0]));
1547                        push(&mut found, self.face_extremum(source, level, su, sv));
1548                    }
1549                }
1550            }
1551            let mut buckets: std::collections::HashMap<(usize, usize), Vec<usize>> = std::collections::HashMap::new();
1552            for (k, &(i, j, _, _, _)) in crossings.iter().enumerate() {
1553                buckets.entry((i, j)).or_default().push(k);
1554            }
1555            for (k, &(i, j, o, u, v)) in crossings.iter().enumerate() {
1556                let mut is_max = true;
1557                let mut is_min = true;
1558                let mut neighbours = Vec::new();
1559                for di in [-1i64, 0, 1] {
1560                    for dj in [-1i64, 0, 1] {
1561                        let i2 = i as i64 + di;
1562                        if i2 < 0 {
1563                            continue;
1564                        }
1565                        let j2 = j as i64 + dj;
1566                        let j2 = if grid.v_periodic { j2.rem_euclid(grid.nv as i64) } else { j2 };
1567                        if j2 < 0 {
1568                            continue;
1569                        }
1570                        if let Some(list) = buckets.get(&(i2 as usize, j2 as usize)) {
1571                            neighbours.extend(list.iter().copied());
1572                        }
1573                    }
1574                }
1575                for m in neighbours {
1576                    if m == k {
1577                        continue;
1578                    }
1579                    let o2 = crossings[m].2;
1580                    {
1581                        let d = self.o_difference(o2, o);
1582                        if d > 0.0 {
1583                            is_max = false;
1584                        }
1585                        if d < 0.0 {
1586                            is_min = false;
1587                        }
1588                    }
1589                }
1590                if !(is_max || is_min) {
1591                    continue;
1592                }
1593                push(&mut found, self.face_extremum(source, level, u, v));
1594            }
1595            out.extend(found.into_iter().map(|(o, _, _)| (o, index)));
1596        } else {
1597            let (range, _, _) = self.domain(source);
1598            let periodic = matches!(source, Source::RevolvedCorner { .. });
1599            let n = match source {
1600                Source::RevolvedCorner { .. }
1601                | Source::PrismEnd { .. }
1602                | Source::ScrewPrismEdge { .. }
1603                | Source::ScrewPrismRim { .. }
1604                | Source::BarEdge { .. }
1605                | Source::BarRim { .. } => 1024,
1606                _ => self.grids_len_for_time(),
1607            };
1608            let _ = periodic;
1609            // The uniform samples, with the curve's own level extrema merged in:
1610            // near a tip the two roots of `ℓ = ℓ₀` fall either side of the extremum,
1611            // closer than any fixed step, and would be missed together.
1612            let table = || -> Vec<(f64, f64)> {
1613                let mut samples: Vec<f64> = (0..=n).map(|k| range[0] + (range[1] - range[0]) * k as f64 / n as f64).collect();
1614                if let Some(extra) = self.critical_params.get(index) {
1615                    samples.extend(extra.iter().map(|p| p.0).filter(|t| *t > range[0] && *t < range[1]));
1616                    samples.sort_by(|a, b| a.total_cmp(b));
1617                }
1618                samples.into_iter().map(|p| (p, self.source_reduced(source, p, 0.0).0)).collect()
1619            };
1620            // The samples' levels do not depend on the level read: once, where on.
1621            let table = if fast_levels_on() {
1622                let cached = self.edge_samples.borrow().get(&index).cloned();
1623                match cached {
1624                    Some(t) => t,
1625                    None => {
1626                        let t = std::rc::Rc::new(table());
1627                        self.edge_samples.borrow_mut().insert(index, t.clone());
1628                        t
1629                    }
1630                }
1631            } else {
1632                std::rc::Rc::new(table())
1633            };
1634            let samples: Vec<f64> = table.iter().map(|x| x.0).collect();
1635            let mut previous = table[0].1 - level;
1636            for k in 1..samples.len() {
1637                let p = samples[k];
1638                let value = table[k].1 - level;
1639                if previous == 0.0 {
1640                    // A root exactly on the sample (a band's end level on the
1641                    // curve's own end): bisecting from a zero walks to the far
1642                    // end of the bracket, a whole sample step away.
1643                    out.push((self.source_reduced(source, samples[k - 1], 0.0).1, index));
1644                } else if previous * value < 0.0 {
1645                    let (mut a, mut b) = (samples[k - 1], p);
1646                    let fa0 = previous;
1647                    for _ in 0..200 {
1648                        let m = 0.5 * (a + b);
1649                        let fm = self.source_reduced(source, m, 0.0).0 - level;
1650                        if (fm < 0.0) == (fa0 < 0.0) && fm != 0.0 {
1651                            a = m;
1652                        } else {
1653                            b = m;
1654                        }
1655                        if (b - a).abs() < 1e-15 * (range[1] - range[0]).abs().max(1.0) {
1656                            break;
1657                        }
1658                    }
1659                    let (_, o) = self.source_reduced(source, 0.5 * (a + b), 0.0);
1660                    out.push((o, index));
1661                }
1662                previous = value;
1663            }
1664            if previous == 0.0 {
1665                let last = *samples.last().expect("nonempty");
1666                out.push((self.source_reduced(source, last, 0.0).1, index));
1667            }
1668        }
1669    }
1670
1671    fn grids_len_for_time(&self) -> usize {
1672        let turn = self
1673            .motion
1674            .steps
1675            .iter()
1676            .map(|step| step.turn.abs())
1677            .fold(0.0, f64::max)
1678            * (self.motion.to - self.motion.from).abs();
1679        ((turn * 256.0) as usize).clamp(1024, 8192)
1680    }
1681
1682    /// The clip-frame point a reduced coordinate is tested at.
1683    fn lift(&self, level: f64, o: f64) -> [f64; 3] {
1684        let axial = 0.5 * (self.clip.axial[0] + self.clip.axial[1]);
1685        match self.class {
1686            Class::Screw(c) => {
1687                let alpha = o + axial / c;
1688                [level * alpha.cos(), level * alpha.sin(), axial]
1689            }
1690            Class::Turn => {
1691                let theta = self.clip.angle.map(|a| 0.5 * (a[0] + a[1])).unwrap_or(0.0);
1692                [level * theta.cos(), level * theta.sin(), o]
1693            }
1694            Class::Planar => [level * o.cos(), level * o.sin(), axial],
1695        }
1696    }
1697
1698    /// Is the reduced point inside the sweep: does the point's preimage under
1699    /// the motion meet the tool for some time in the range?
1700    ///
1701    /// Walked in time by the tool's signed distance: it bounds how far the
1702    /// preimage is from the tool, and the preimage moves no faster than
1703    /// `speed_bound`, so no time within `distance / speed` of the current one can
1704    /// be inside. The walk is exact for the tool's own distance (a lower bound for
1705    /// a prism, which is conservative), and the floor on the step only stops a
1706    /// grazing walk from creeping.
1707    fn removed(&self, level: f64, o: f64) -> bool {
1708        let x = self.frame.world(self.lift(level, o));
1709        let (t0, t1) = (self.motion.from, self.motion.to);
1710        let speed = self.speed_bound(x);
1711        // The floor only keeps a grazing walk from creeping; a coarse floor
1712        // jumps over a shallow pass of the tool (1e-5 of the plus wheel's range
1713        // is 0.02 mm of travel, and read a 4e-3 mm sliver of its tooth space as
1714        // material). A walk still grazing after `cap` steps is on the boundary.
1715        let floor = (t1 - t0) * 1e-8;
1716        let cap = 200_000usize;
1717        let touching = 1e-10 * self.scale;
1718        let clock = web_time::Instant::now();
1719        let mut t = t0;
1720        let mut steps = 0usize;
1721        let inside = loop {
1722            steps += 1;
1723            let distance = self.tool_signed_distance(self.motion_invert(t, x));
1724            if distance <= touching || steps > cap {
1725                break true;
1726            }
1727            if t >= t1 {
1728                break false;
1729            }
1730            t = (t + (distance / speed).max(floor)).min(t1);
1731        };
1732        let mut c = self.counters.get();
1733        c.1 += 1;
1734        c.2 += steps;
1735        c.4 += clock.elapsed().as_secs_f64();
1736        self.counters.set(c);
1737        inside
1738    }
1739
1740    /// An upper bound on how fast the preimage `M(t)⁻¹ x` moves per unit `t`.
1741    fn speed_bound(&self, x: Vec3) -> f64 {
1742        // Steps about one line commute and keep a point's distance d to it:
1743        // the preimage moves at most Σ|turn|·d + Σ|advance| (a slide along
1744        // the line carries a point no further from it).
1745        if let Some(d) = self.line_distance(x) {
1746            let turning: f64 = self.motion.steps.iter().map(|step| step.turn.abs()).sum();
1747            let sliding: f64 = self.motion.steps.iter().map(|step| step.advance.abs()).sum();
1748            return ((turning * d + sliding) * (1.0 + 1e-12)).max(1e-300);
1749        }
1750        let centre = self.frame.origin;
1751        let span = self.motion.from.abs().max(self.motion.to.abs());
1752        let mut reach = x.sub(centre).length();
1753        for step in &self.motion.steps {
1754            reach += 2.0 * step.axis_origin.sub(centre).length() + step.advance.abs() * span;
1755        }
1756        let speed: f64 = self
1757            .motion
1758            .steps
1759            .iter()
1760            .map(|step| step.turn.abs() * (reach + step.axis_origin.sub(centre).length()) + step.advance.abs())
1761            .sum();
1762        speed.max(1e-300)
1763    }
1764
1765    /// The distance from `x` to the line every step turns about and slides
1766    /// along, where there is one (behind `BREP_SWEEP_LINE_SPEED`).
1767    fn line_distance(&self, x: Vec3) -> Option<f64> {
1768        let (first, axis) = (self.motion.steps.first()?, *self.axes.first()?);
1769        let tolerance = 1e-12 * self.scale.max(1e-300);
1770        let on_line = |p: Vec3| p.sub(first.axis_origin).cross(axis).length() <= tolerance;
1771        let one = self.motion.steps.iter().zip(&self.axes).all(|(step, a)| a.cross(axis).length() <= 1e-12 && on_line(step.axis_origin));
1772        if !(one && line_speed_on()) {
1773            return None;
1774        }
1775        Some(x.sub(first.axis_origin).cross(axis).length())
1776    }
1777
1778    /// The region's intervals at a level, sorted by `lo` (angular: `lo` in
1779    /// [0, 2π), `hi` may exceed 2π).
1780    fn intervals_at(&self, level: f64) -> Result<Vec<Interval>, KernelRefusal> {
1781        if let Some(hit) = self.cache.borrow().get(&level.to_bits()) {
1782            return Ok(hit.clone());
1783        }
1784        let clock = web_time::Instant::now();
1785        let before = self.counters.get();
1786        let intervals = if extremum_jet_check_on() { self.intervals_checked(level)? } else { self.intervals_uncached(level)? };
1787        if clock.elapsed().as_secs_f64() > 0.5 && std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
1788            let after = self.counters.get();
1789            eprintln!(
1790                "  slow level {level:.12}: {:.2}s, candidates {:.2}s, oracle calls {} steps {} ({:.2}s), {} intervals",
1791                clock.elapsed().as_secs_f64(),
1792                after.3 - before.3,
1793                after.1 - before.1,
1794                after.2 - before.2,
1795                after.4 - before.4,
1796                intervals.len()
1797            );
1798        }
1799        self.cache.borrow_mut().insert(level.to_bits(), intervals.clone());
1800        Ok(intervals)
1801    }
1802
1803    /// The check mode of [`extremum_jet_on`]: the level read both ways, the
1804    /// two compared (same intervals from the same sources, ends within
1805    /// `JET_CHECK_BAR` of the scale), the differenced reading answered.
1806    fn intervals_checked(&self, level: f64) -> Result<Vec<Interval>, KernelRefusal> {
1807        let kept = self.jet.get();
1808        self.jet.set(false);
1809        let plain = self.intervals_uncached(level);
1810        self.jet.set(true);
1811        let exact = self.intervals_uncached(level);
1812        self.jet.set(kept);
1813        let (plain, exact) = match (plain, exact) {
1814            (Ok(a), Ok(b)) => (a, b),
1815            (plain, exact) => {
1816                if plain.is_ok() != exact.is_ok() {
1817                    jet_check_record(|stats| stats.mismatches += 1);
1818                    if std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
1819                        eprintln!("extremum jet check: level {level}: refusal differs ({} / {})", plain.is_ok(), exact.is_ok());
1820                    }
1821                }
1822                return plain;
1823            }
1824        };
1825        let length = |d: f64| if self.angular { d.abs() * level } else { d.abs() };
1826        // An interval narrower than the bar is a reading of the region's edge
1827        // (the rim of a cone 6e-13 inside its reach holds one 1.2e-12 wide): both
1828        // readings agree with it there or not.
1829        let wide = |list: &[Interval]| -> Vec<Interval> {
1830            list.iter().copied().filter(|x| length(self.o_difference(x.hi, x.lo)) > JET_CHECK_BAR * self.scale).collect()
1831        };
1832        let (plain_wide, exact_wide) = (wide(&plain), wide(&exact));
1833        // Ends compared by value: two sources meeting at one end (a tie the
1834        // sort settles either way) name it differently and are the same end.
1835        let worst = if plain_wide.len() == exact_wide.len() {
1836            plain_wide
1837                .iter()
1838                .zip(&exact_wide)
1839                .map(|(a, b)| length(self.o_difference(a.lo, b.lo)).max(length(self.o_difference(a.hi, b.hi))))
1840                .fold(0.0, f64::max)
1841        } else {
1842            f64::INFINITY
1843        };
1844        let bad = worst > JET_CHECK_BAR * self.scale;
1845        // The same ends, named by other sources (the events read the names).
1846        let relabelled = !bad && plain_wide.iter().zip(&exact_wide).any(|(a, b)| a.lo_source != b.lo_source || a.hi_source != b.hi_source);
1847        // Within a hair of a source's critical level a contour closes on its
1848        // tip: its ends move as the root of the level's distance there, and the
1849        // two readings part by far more than their residuals do.
1850        let near_tip = self.critical.iter().flatten().any(|c| (c.0 - level).abs() <= JET_CHECK_TIP * self.scale);
1851        jet_check_record(|stats| {
1852            stats.levels += 1;
1853            stats.relabelled += relabelled as usize;
1854            if bad {
1855                if near_tip {
1856                    stats.near_tip += 1;
1857                } else {
1858                    stats.mismatches += 1;
1859                }
1860            }
1861            if near_tip && worst.is_finite() {
1862                stats.worst_tip = stats.worst_tip.max(worst / self.scale);
1863            } else if near_tip {
1864                stats.tip_counts += 1;
1865            } else if worst.is_finite() {
1866                stats.worst_end = stats.worst_end.max(worst / self.scale);
1867            }
1868        });
1869        if bad && std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
1870            eprintln!("extremum jet check: level {level} (near a tip: {near_tip}): {plain:?} vs {exact:?}");
1871        }
1872        Ok(plain)
1873    }
1874
1875    fn intervals_uncached(&self, level: f64) -> Result<Vec<Interval>, KernelRefusal> {
1876        let clock = web_time::Instant::now();
1877        let mut candidates = Vec::new();
1878        for index in 0..self.sources.len() {
1879            self.source_candidates(index, level, &mut candidates);
1880        }
1881        let mut c = self.counters.get();
1882        c.0 += 1;
1883        c.3 += clock.elapsed().as_secs_f64();
1884        self.counters.set(c);
1885        if self.angular {
1886            for candidate in &mut candidates {
1887                candidate.0 = candidate.0.rem_euclid(TAU);
1888            }
1889        }
1890        candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
1891        candidates.dedup_by(|b, a| (b.0 - a.0).abs() < 1e-12);
1892        if candidates.is_empty() {
1893            let probes = 64;
1894            let (base, span) = if self.angular { (0.0, TAU) } else { (-self.scale * 4.0, self.scale * 8.0) };
1895            if (0..probes).all(|k| self.removed(level, base + span * (k as f64 + 0.5) / probes as f64)) {
1896                return Err(refuse(
1897                    "whole_level",
1898                    format!("{WHOLE_LEVEL} {level}, which this construction does not build"),
1899                ));
1900            }
1901            return Ok(Vec::new());
1902        }
1903        let n = candidates.len();
1904        let gaps = if self.angular { n } else { n - 1 };
1905        let mut removed = Vec::with_capacity(gaps);
1906        for k in 0..gaps {
1907            let a = candidates[k].0;
1908            let b = if k + 1 < n { candidates[k + 1].0 } else { candidates[0].0 + TAU };
1909            // A gap far below any feature is the two ends of one boundary
1910            // point; its middle is on the boundary, where the oracle can only
1911            // graze. It joins whatever is on either side.
1912            if (b - a) * level.max(1.0) < 1e-9 * self.scale {
1913                removed.push(true);
1914                continue;
1915            }
1916            removed.push(self.removed(level, 0.5 * (a + b)));
1917        }
1918        let mut intervals = Vec::new();
1919        // Below a crest some material is left, however narrow: the widest gap,
1920        // which the oracle can no longer see inside.
1921        if self.crest_gap && self.angular && removed.iter().all(|r| *r) {
1922            let width = |k: usize| if k + 1 < n { candidates[k + 1].0 - candidates[k].0 } else { candidates[0].0 + TAU - candidates[k].0 };
1923            if let Some(widest) = (0..gaps).max_by(|&a, &b| width(a).total_cmp(&width(b))) {
1924                removed[widest] = false;
1925            }
1926        }
1927        if self.angular && removed.iter().all(|r| *r) {
1928            return Err(refuse(
1929                "whole_level",
1930                format!("{WHOLE_LEVEL} {level}, which this construction does not build"),
1931            ));
1932        }
1933        // Start the walk after a material gap so a run never straddles the start.
1934        let start = if self.angular {
1935            removed.iter().position(|r| !r).map(|k| (k + 1) % n).unwrap_or(0)
1936        } else {
1937            0
1938        };
1939        let mut k = 0;
1940        while k < gaps {
1941            let g = (start + k) % n.max(1);
1942            if !removed[g] {
1943                k += 1;
1944                continue;
1945            }
1946            let first = g;
1947            let mut last = g;
1948            while k + 1 < gaps && removed[(start + k + 1) % n] {
1949                k += 1;
1950                last = (start + k) % n;
1951            }
1952            let lo = candidates[first];
1953            let hi_index = (last + 1) % n;
1954            let hi = candidates[hi_index];
1955            let mut hi_value = hi.0;
1956            if self.angular && hi_value <= lo.0 {
1957                hi_value += TAU;
1958            }
1959            intervals.push(Interval {
1960                lo: lo.0,
1961                hi: hi_value,
1962                lo_source: lo.1,
1963                hi_source: hi.1,
1964            });
1965            k += 1;
1966        }
1967        intervals.sort_by(|a, b| a.lo.total_cmp(&b.lo));
1968        Ok(intervals)
1969    }
1970
1971    /// Critical points of the level over a source (tips and plateaus).
1972    /// The face's characteristic function: `det(∇o, ∇ℓ) / |∇ℓ|`, zero where
1973    /// the face's image turns back (its envelope), and the level there.
1974    fn characteristic(&self, source: Source, u: f64, v: f64) -> (f64, f64) {
1975        let (ur, vr, _) = self.domain(source);
1976        let hu = 1e-6 * (ur[1] - ur[0]).max(1e-3);
1977        let hv = 1e-6 * (vr[1] - vr[0]).max(1e-3);
1978        let (l, _) = self.source_reduced(source, u, v);
1979        let (lu1, ou1) = self.source_reduced(source, u + hu, v);
1980        let (lu0, ou0) = self.source_reduced(source, u - hu, v);
1981        let (lv1, ov1) = self.source_reduced(source, u, v + hv);
1982        let (lv0, ov0) = self.source_reduced(source, u, v - hv);
1983        let (lu, lv) = ((lu1 - lu0) / (2.0 * hu), (lv1 - lv0) / (2.0 * hv));
1984        let ou = self.o_difference(ou1, ou0) / (2.0 * hu);
1985        let ov = self.o_difference(ov1, ov0) / (2.0 * hv);
1986        ((ou * lv - ov * lu) / lu.hypot(lv).max(1e-300), l)
1987    }
1988
1989    /// FOLDS and KINKS of a face, recorded as its critical points so events snap
1990    /// to them and band ends read them exactly:
1991    /// - a FOLD is where the level is extremal along the face's own envelope
1992    ///   (`D = 0`): two extrema of `o` on one level contour annihilate there
1993    ///   (the plus wheel's lobes merging at ρ = 20, the tip of its arm's flat
1994    ///   end). Newton on {D = 0, ℓ_u·D_v − ℓ_v·D_u = 0}, seeded where the level
1995    ///   is locally extremal among the grid's crossings of D = 0.
1996    /// - a KINK is where the envelope runs into the face's own boundary and the
1997    ///   boundary's edge takes over: roots of D along each non-periodic side.
1998    fn folds_and_kinks(&self, source: Source, grid: &Grid, out: &mut Vec<(f64, f64)>, params: &mut Vec<(f64, f64)>) {
1999        let (ur, vr, v_periodic) = self.domain(source);
2000        let u_periodic = self.u_periodic(source);
2001        let (nu, nv) = (grid.nu, grid.nv);
2002        let mut d = vec![0.0; nu * nv];
2003        for i in 0..nu {
2004            for j in 0..nv {
2005                let (u, v) = Self::grid_param(grid, i, j);
2006                d[i * nv + j] = self.characteristic(source, u, v).0;
2007            }
2008        }
2009        // Crossings of D = 0 along grid edges: (i, j, u, v, level).
2010        let mut crossings: Vec<(usize, usize, f64, f64, f64)> = Vec::new();
2011        let jmax = if v_periodic { nv } else { nv - 1 };
2012        for i in 0..nu {
2013            for j in 0..jmax {
2014                let (a, b) = (d[i * nv + j], d[i * nv + (j + 1) % nv]);
2015                if a * b < 0.0 {
2016                    let w = a / (a - b);
2017                    let (u, v0) = Self::grid_param(grid, i, j);
2018                    let (_, v1) = Self::grid_param(grid, i, j + 1);
2019                    let v1 = if v_periodic && j + 1 == nv { vr[1] } else { v1 };
2020                    let v = v0 + (v1 - v0) * w;
2021                    crossings.push((i, j, u, v, self.source_reduced(source, u, v).0));
2022                }
2023            }
2024        }
2025        for i in 0..nu - 1 {
2026            for j in 0..nv {
2027                let (a, b) = (d[i * nv + j], d[(i + 1) * nv + j]);
2028                if a * b < 0.0 {
2029                    let w = a / (a - b);
2030                    let (u0, v) = Self::grid_param(grid, i, j);
2031                    let (u1, _) = Self::grid_param(grid, i + 1, j);
2032                    let u = u0 + (u1 - u0) * w;
2033                    crossings.push((i, j, u, v, self.source_reduced(source, u, v).0));
2034                }
2035            }
2036        }
2037        let mut buckets: std::collections::HashMap<(usize, usize), Vec<usize>> = std::collections::HashMap::new();
2038        for (k, c) in crossings.iter().enumerate() {
2039            buckets.entry((c.0, c.1)).or_default().push(k);
2040        }
2041        let ku = 1e-4 * (ur[1] - ur[0]);
2042        let kv = 1e-4 * (vr[1] - vr[0]);
2043        let fold = |u: f64, v: f64| -> [f64; 2] {
2044            let (dd, _) = self.characteristic(source, u, v);
2045            let du = (self.characteristic(source, u + ku, v).0 - self.characteristic(source, u - ku, v).0) / (2.0 * ku);
2046            let dv = (self.characteristic(source, u, v + kv).0 - self.characteristic(source, u, v - kv).0) / (2.0 * kv);
2047            let lu = (self.source_reduced(source, u + ku, v).0 - self.source_reduced(source, u - ku, v).0) / (2.0 * ku);
2048            let lv = (self.source_reduced(source, u, v + kv).0 - self.source_reduced(source, u, v - kv).0) / (2.0 * kv);
2049            let norm = (lu.hypot(lv) * du.hypot(dv)).max(1e-300);
2050            [dd, (lu * dv - lv * du) / norm]
2051        };
2052        for (k, &(i, j, u0, v0, level)) in crossings.iter().enumerate() {
2053            let mut is_min = true;
2054            let mut is_max = true;
2055            for di in [-1i64, 0, 1] {
2056                for dj in [-1i64, 0, 1] {
2057                    let i2 = i as i64 + di;
2058                    let j2 = if v_periodic { (j as i64 + dj).rem_euclid(nv as i64) } else { j as i64 + dj };
2059                    if i2 < 0 || j2 < 0 {
2060                        continue;
2061                    }
2062                    if let Some(list) = buckets.get(&(i2 as usize, j2 as usize)) {
2063                        for &m in list {
2064                            if m == k {
2065                                continue;
2066                            }
2067                            if crossings[m].4 < level {
2068                                is_min = false;
2069                            }
2070                            if crossings[m].4 > level {
2071                                is_max = false;
2072                            }
2073                        }
2074                    }
2075                }
2076            }
2077            if !(is_min || is_max) {
2078                continue;
2079            }
2080            let (mut u, mut v) = (u0, v0);
2081            let mut converged = false;
2082            for _ in 0..40 {
2083                let f = fold(u, v);
2084                let (su, sv) = (ku * 10.0, kv * 10.0);
2085                let fu1 = fold(u + su, v);
2086                let fu0 = fold(u - su, v);
2087                let fv1 = fold(u, v + sv);
2088                let fv0 = fold(u, v - sv);
2089                let j00 = (fu1[0] - fu0[0]) / (2.0 * su);
2090                let j01 = (fv1[0] - fv0[0]) / (2.0 * sv);
2091                let j10 = (fu1[1] - fu0[1]) / (2.0 * su);
2092                let j11 = (fv1[1] - fv0[1]) / (2.0 * sv);
2093                let det = j00 * j11 - j01 * j10;
2094                if !det.is_finite() || det.abs() < 1e-300 {
2095                    break;
2096                }
2097                let du = -(f[0] * j11 - f[1] * j01) / det;
2098                let dv = -(j00 * f[1] - j10 * f[0]) / det;
2099                // Stay near the seed: a fold is local to its crossing.
2100                let cap = 4.0 * ((ur[1] - ur[0]) / (nu as f64)).max((vr[1] - vr[0]) / (nv as f64));
2101                let scale = (du.hypot(dv) / cap).max(1.0);
2102                u += du / scale;
2103                v += dv / scale;
2104                if du.hypot(dv) < 1e-12 * (ur[1] - ur[0]).max(vr[1] - vr[0]) {
2105                    converged = true;
2106                    break;
2107                }
2108            }
2109            let f = fold(u, v);
2110            if !(converged || (f[0].abs() < 1e-9 && f[1].abs() < 1e-5)) {
2111                continue;
2112            }
2113            if u_periodic {
2114                u = ur[0] + (u - ur[0]).rem_euclid(ur[1] - ur[0]);
2115            }
2116            if v_periodic {
2117                v = vr[0] + (v - vr[0]).rem_euclid(vr[1] - vr[0]);
2118            }
2119            if u > ur[0] && u < ur[1] && (v_periodic || (v > vr[0] && v < vr[1])) {
2120                out.push(self.source_reduced(source, u, v));
2121                params.push((u, v));
2122            }
2123        }
2124        // Kinks: roots of D along each non-periodic side of the face.
2125        let mut sides: Vec<(bool, f64)> = Vec::new(); // (along v at fixed u, the fixed value)
2126        if !u_periodic {
2127            sides.push((true, ur[0]));
2128            sides.push((true, ur[1]));
2129        }
2130        if !v_periodic {
2131            sides.push((false, vr[0]));
2132            sides.push((false, vr[1]));
2133        }
2134        for (along_v, fixed) in sides {
2135            let (range, n) = if along_v { (vr, nv * 4) } else { (ur, nu * 4) };
2136            let at = |t: f64| if along_v { (fixed, t) } else { (t, fixed) };
2137            let value = |t: f64| {
2138                let (u, v) = at(t);
2139                self.characteristic(source, u, v).0
2140            };
2141            let mut previous = value(range[0]);
2142            for k in 1..=n {
2143                let t = range[0] + (range[1] - range[0]) * k as f64 / n as f64;
2144                let current = value(t);
2145                if previous * current < 0.0 {
2146                    let (mut a, mut b) = (t - (range[1] - range[0]) / n as f64, t);
2147                    let fa = previous;
2148                    for _ in 0..100 {
2149                        let m = 0.5 * (a + b);
2150                        if (value(m) < 0.0) == (fa < 0.0) {
2151                            a = m;
2152                        } else {
2153                            b = m;
2154                        }
2155                    }
2156                    let (u, v) = at(0.5 * (a + b));
2157                    out.push(self.source_reduced(source, u, v));
2158                    params.push((u, v));
2159                }
2160                previous = current;
2161            }
2162        }
2163    }
2164
2165    fn source_critical(&self, index: usize) -> (Vec<(f64, f64)>, Vec<(f64, f64)>, Vec<Option<[f64; 2]>>) {
2166        let source = self.sources[index];
2167        let mut out = Vec::new();
2168        let mut params = Vec::new();
2169        let mut bands = Vec::new();
2170        if Self::is_face(source) {
2171            let grid = self.grids[index].as_ref().expect("face grid");
2172            let (ur, vr, periodic) = self.domain(source);
2173            let at = |i: usize, j: usize| grid.values[i * grid.nv + j].0;
2174            let u_periodic = self.u_periodic(source);
2175            // A periodic first parameter has its last row equal to its first.
2176            let rows = if u_periodic { grid.nu - 1 } else { grid.nu };
2177            for i in 0..rows {
2178                if !u_periodic && (i == 0 || i + 1 == grid.nu) {
2179                    continue;
2180                }
2181                for j in 0..grid.nv {
2182                    if !periodic && (j == 0 || j + 1 == grid.nv) {
2183                        continue;
2184                    }
2185                    let here = at(i, j);
2186                    let mut is_min = true;
2187                    let mut is_max = true;
2188                    for di in [-1i64, 0, 1] {
2189                        for dj in [-1i64, 0, 1] {
2190                            if di == 0 && dj == 0 {
2191                                continue;
2192                            }
2193                            let i2 = ((i as i64 + di).rem_euclid(rows as i64)) as usize;
2194                            let j2 = ((j as i64 + dj).rem_euclid(grid.nv as i64)) as usize;
2195                            let there = at(i2, j2);
2196                            if there < here {
2197                                is_min = false;
2198                            }
2199                            if there > here {
2200                                is_max = false;
2201                            }
2202                        }
2203                    }
2204                    if !(is_min || is_max) {
2205                        continue;
2206                    }
2207                    // Newton on ∇ℓ = 0.
2208                    let (mut u, mut v) = Self::grid_param(grid, i, j);
2209                    let hu = 1e-5 * (ur[1] - ur[0]);
2210                    let hv = 1e-5 * (vr[1] - vr[0]);
2211                    let level = |u: f64, v: f64| self.source_reduced(source, u, v).0;
2212                    for _ in 0..50 {
2213                        let f = level(u, v);
2214                        let fu = (level(u + hu, v) - level(u - hu, v)) / (2.0 * hu);
2215                        let fv = (level(u, v + hv) - level(u, v - hv)) / (2.0 * hv);
2216                        let fuu = (level(u + hu, v) - 2.0 * f + level(u - hu, v)) / (hu * hu);
2217                        let fvv = (level(u, v + hv) - 2.0 * f + level(u, v - hv)) / (hv * hv);
2218                        let fuv = (level(u + hu, v + hv) - level(u + hu, v - hv) - level(u - hu, v + hv)
2219                            + level(u - hu, v - hv))
2220                            / (4.0 * hu * hv);
2221                        let det = fuu * fvv - fuv * fuv;
2222                        if det.abs() < 1e-300 {
2223                            break;
2224                        }
2225                        let du = -(fu * fvv - fv * fuv) / det;
2226                        let dv = -(fuu * fv - fuv * fu) / det;
2227                        u += du;
2228                        v += dv;
2229                        if du.abs() < 1e-14 && dv.abs() < 1e-14 {
2230                            break;
2231                        }
2232                    }
2233                    if u_periodic {
2234                        u = ur[0] + (u - ur[0]).rem_euclid(ur[1] - ur[0]);
2235                    }
2236                    if periodic {
2237                        v = vr[0] + (v - vr[0]).rem_euclid(vr[1] - vr[0]);
2238                    }
2239                    if u >= ur[0] && u <= ur[1] && (periodic || (v >= vr[0] && v <= vr[1])) {
2240                        let tip = self.source_reduced(source, u, v);
2241                        // The grid's levels about the node the search began at
2242                        // and about the node nearest where it ended, with the tip's.
2243                        let nearest = {
2244                            let fi = ((u - ur[0]) / (ur[1] - ur[0]) * (grid.nu - 1) as f64).round();
2245                            let span = if periodic { grid.nv } else { grid.nv - 1 };
2246                            let fj = ((v - vr[0]) / (vr[1] - vr[0]) * span as f64).round();
2247                            ((fi.max(0.0) as usize).min(grid.nu - 1), (fj.max(0.0) as usize).min(grid.nv - 1))
2248                        };
2249                        let (mut low, mut high) = (tip.0, tip.0);
2250                        for (ci, cj) in [(i, j), nearest] {
2251                            for di in [-1i64, 0, 1] {
2252                                for dj in [-1i64, 0, 1] {
2253                                    let i2 = if u_periodic { (ci as i64 + di).rem_euclid(rows as i64) } else { (ci as i64 + di).clamp(0, grid.nu as i64 - 1) } as usize;
2254                                    let j2 = if periodic { (cj as i64 + dj).rem_euclid(grid.nv as i64) } else { (cj as i64 + dj).clamp(0, grid.nv as i64 - 1) } as usize;
2255                                    let level = at(i2, j2);
2256                                    low = low.min(level);
2257                                    high = high.max(level);
2258                                }
2259                            }
2260                        }
2261                        out.push(tip);
2262                        params.push((u, v));
2263                        bands.push(Some([low, high]));
2264                    }
2265                }
2266            }
2267            self.folds_and_kinks(source, grid, &mut out, &mut params);
2268            bands.resize(params.len(), None);
2269        } else {
2270            let (range, _, _) = self.domain(source);
2271            let n = 2048;
2272            let param = |k: usize| range[0] + (range[1] - range[0]) * k as f64 / n as f64;
2273            let values: Vec<f64> = (0..=n).map(|k| self.source_reduced(source, param(k), 0.0).0).collect();
2274            // A closed edge (a circle) has no ends: its seam sample is read
2275            // between its neighbours across the seam like any other.
2276            let periodic = edge_tips_on() && self.edge_periodic(source);
2277            let first = if periodic { 0 } else { 1 };
2278            for k in first..n {
2279                let (a, b, c) = if k == 0 { (values[n - 1], values[0], values[1]) } else { (values[k - 1], values[k], values[k + 1]) };
2280                if (b <= a && b <= c) || (b >= a && b >= c) {
2281                    let sign = if b <= a && b <= c { 1.0 } else { -1.0 };
2282                    let before = if k == 0 { range[0] - (range[1] - range[0]) / n as f64 } else { param(k - 1) };
2283                    let (mut lo, mut hi) = (before, param(k + 1));
2284                    let ratio = 0.618_033_988_749_894_9;
2285                    for _ in 0..100 {
2286                        let c1 = hi - ratio * (hi - lo);
2287                        let d1 = lo + ratio * (hi - lo);
2288                        if sign * self.source_reduced(source, c1, 0.0).0 < sign * self.source_reduced(source, d1, 0.0).0 {
2289                            hi = d1;
2290                        } else {
2291                            lo = c1;
2292                        }
2293                    }
2294                    let mut at = 0.5 * (lo + hi);
2295                    if periodic {
2296                        at = range[0] + (at - range[0]).rem_euclid(range[1] - range[0]);
2297                    }
2298                    out.push(self.source_reduced(source, at, 0.0));
2299                    params.push((at, 0.0));
2300                }
2301            }
2302        }
2303        (out, params, bands)
2304    }
2305}
2306
2307/// Are two sources the same boundary piece of the sweep: the same source, or
2308/// a piece and the one that continues it across a set-periodic motion's wrap?
2309/// A face handing over to the edge that bounds it is NOT the same: the V
2310/// wheel's flank meets its tip circle's image at a kink, and fitting one curve
2311/// through it read the groove 1.5e-6 off (split: 1.1e-8).
2312fn same_or_bounding(engine: &Engine, a: usize, b: usize) -> bool {
2313    if a == b {
2314        return true;
2315    }
2316    let pieces = match (&engine.bar, engine.tool) {
2317        (Some(bar), _) => bar.piece_count(),
2318        (None, SweptTool::Revolved { meridian, .. }) => meridian.len(),
2319        (None, SweptTool::Prism { outline, .. }) => outline.len(),
2320        (None, SweptTool::Bar { section, .. }) => section.len(),
2321    };
2322    // (piece of the face, piece whose start the edge is)
2323    let face = |s: Source| match s {
2324        Source::RevolvedFace { piece } | Source::PrismFace { piece } | Source::ScrewPrismSide { piece } | Source::BarSide { piece } => Some(piece),
2325        _ => None,
2326    };
2327    let edge = |s: Source| match s {
2328        Source::RevolvedCorner { piece } | Source::PrismVertex { piece } | Source::ScrewPrismEdge { piece } | Source::BarEdge { piece } => Some(piece),
2329        _ => None,
2330    };
2331    let (sa, sb) = (engine.sources[a], engine.sources[b]);
2332    // Across the wrap, piece `k` continues as `wrap[k]`.
2333    let same_piece = |x: usize, y: usize| {
2334        x == y || engine.wrap.as_ref().is_some_and(|map| map[x] == y || map[y] == x)
2335    };
2336    let bounds = |f: usize, e: usize| {
2337        same_piece(e, f) || same_piece(e, (f + 1) % pieces)
2338    };
2339    let _ = bounds;
2340    match (face(sa), edge(sa), face(sb), edge(sb)) {
2341        (Some(f), _, Some(g), _) => same_piece(f, g),
2342        (_, Some(e), _, Some(g)) => same_piece(e, g),
2343        _ => false,
2344    }
2345}
2346
2347/// Do two interval lists describe the same structure (same count, each end on
2348/// the same source or one that hands over to it smoothly, matched in order)?
2349fn compatible(engine: &Engine, a: &[Interval], b: &[Interval]) -> bool {
2350    let angular = engine.angular;
2351    if a.len() != b.len() {
2352        return false;
2353    }
2354    // Match each interval of `a` to the one of `b` nearest its middle.
2355    let mut used = vec![false; b.len()];
2356    for x in a {
2357        let mid = 0.5 * (x.lo + x.hi);
2358        let mut best = None;
2359        let mut best_distance = f64::INFINITY;
2360        for (k, y) in b.iter().enumerate() {
2361            let other = 0.5 * (y.lo + y.hi);
2362            let d = if angular { wrap_pi(mid - other).abs() } else { (mid - other).abs() };
2363            if d < best_distance {
2364                best_distance = d;
2365                best = Some(k);
2366            }
2367        }
2368        let Some(k) = best else { return false };
2369        let y = &b[k];
2370        let overlap = if angular {
2371            let shift = (wrap_pi(y.lo - x.lo)) - (y.lo - x.lo);
2372            let (ylo, yhi) = (y.lo + shift, y.hi + shift);
2373            x.hi.min(yhi) - x.lo.max(ylo)
2374        } else {
2375            x.hi.min(y.hi) - x.lo.max(y.lo)
2376        };
2377        if used[k]
2378            || overlap < 0.0
2379            || !same_or_bounding(engine, x.lo_source, y.lo_source)
2380            || !same_or_bounding(engine, x.hi_source, y.hi_source)
2381        {
2382            return false;
2383        }
2384        used[k] = true;
2385    }
2386    true
2387}
2388
2389/// A boundary piece in reduced coordinates, as a polyline of exact samples
2390/// (the first and last are the piece's ends) with their `σ`.
2391struct Piece {
2392    points: Vec<(f64, f64)>,
2393    sigma: Vec<f64>,
2394    /// A straight level segment (built exactly, not fitted).
2395    level_segment: bool,
2396}
2397
2398/// Build the sweep of `tool` along `motion` inside `clip`, as one body per
2399/// connected region of the reduced section.
2400pub fn sweep_solid_within(
2401    tool: &SweptTool,
2402    motion: &SolidMotion,
2403    clip: &SweepClip,
2404) -> Result<Vec<BrepSolid>, KernelRefusal> {
2405    sweep_solid_within_routes(tool, motion, clip, true)
2406}
2407
2408/// [`sweep_solid_within`]'s routes, the turned shadow tried when `shadow`.
2409fn sweep_solid_within_routes(
2410    tool: &SweptTool,
2411    motion: &SolidMotion,
2412    clip: &SweepClip,
2413    shadow: bool,
2414) -> Result<Vec<BrepSolid>, KernelRefusal> {
2415    // A convex polygon's prism carried round a closed planar motion (turns
2416    // about axes along its own, ending where it starts: a planet on its
2417    // carrier): the plane region its section covers, found exactly and
2418    // extruded. It is the whole sweep, so it holds whatever lies in the clip.
2419    if let SweptTool::Prism { origin, normal, x_axis, outline, from, to } = tool {
2420        if motion.steps.len() >= 2 {
2421            let steps: Vec<(Vec3, Vec3, f64, f64)> = motion.steps.iter().map(|step| (step.axis_origin, step.axis_direction, step.turn, step.advance)).collect();
2422            if let Some(body) = crate::solid_sweep_caps::closed_planar_prism(*origin, *normal, *x_axis, outline, *from, *to, &steps, motion.from, motion.to)? {
2423                return Ok(vec![body]);
2424            }
2425        }
2426    }
2427    // A solid of revolution turned about an axis crossing its own at right
2428    // angles, its ends clear of the clip's wedge: its exact turned shadow
2429    // (`solid_sweep_turn_shadow`, `BREP_SWEEP_REVOLVED_TURN_SHADOW`, default on).
2430    {
2431        use crate::solid_sweep_turn_shadow as shadow;
2432        let (on, check) = (shadow::revolved_turn_shadow_on(), shadow::revolved_turn_shadow_check_on());
2433        if shadow && (on || check) {
2434            if let Some(body) = shadow::revolved_turn_shadow(tool, motion, clip)? {
2435                if !check {
2436                    return Ok(vec![body]);
2437                }
2438                let shadow_body = body;
2439                let parts = sweep_solid_within_routes(tool, motion, clip, false)?;
2440                let within = |b: &BrepSolid| crate::solid_mass_properties(&clip_region(b, clip)?).ok().map(|m| m.volume);
2441                shadow::record_check(&shadow_body, &parts, within);
2442                return Ok(parts);
2443            }
2444        }
2445    }
2446    // A disc's prism turned partway about an axis along it, held whole by the
2447    // clip: its region of arcs, exactly, extruded (`turned_disc`,
2448    // `BREP_SWEEP_TURNED_DISC`, default on); None leaves it to the routes below.
2449    if let Some(parts) = crate::turned_disc::turned_disc(tool, motion, clip)? {
2450        return Ok(parts);
2451    }
2452    // A straight-sided prism turned about axes along it: its exact planar
2453    // region, extruded (default off).
2454    if crate::planar_region::planar_region_on() {
2455        if let Some(bodies) = crate::planar_region::sweep_prism_planar_region(tool, motion, clip)? {
2456            return Ok(bodies);
2457        }
2458    }
2459    // A prism standing along the clip's axis, turned partway about it, one end of the turn clear
2460    // of the clip's angle window: the band it passes over and its pose at the other end, exactly
2461    // (`turn_window`, `BREP_SWEEP_TURN_WINDOW`, default on); None leaves it to the engine below.
2462    if crate::turn_window::turn_window_on() {
2463        if let Some(parts) = crate::turn_window::turn_window(tool, motion, clip)? {
2464            return Ok(parts);
2465        }
2466    }
2467    // A convex prism with arcs in its outline slid in its own plane: its whole sweep, exactly
2468    // (`slide_prism`, `BREP_SWEEP_SLIDE_PRISM`, on unless =0); None leaves it to the engine below.
2469    if crate::slide_prism::slide_prism_on() {
2470        if let Some(parts) = crate::slide_prism::slide_prism(tool, motion, clip)? {
2471            return Ok(parts);
2472        }
2473    }
2474    level_sweep(tool, motion, clip, false).map(|bodies| bodies.unwrap_or_default())
2475}
2476
2477/// The clip region less the sweep of `tool` along `motion` (default on;
2478/// `BREP_SWEEP_CLIP_LESS=0` answers None, so the caller subtracts the sweep): the workpiece the clip names (a rod: radius
2479/// from 0, no angle window) with everything the tool passes through taken
2480/// out, built by the level engine directly, without a boolean. At each level
2481/// the material is what the sweep leaves; its walls are the sweep's own, and
2482/// at the clip's outer radius the boundary is the circle less the sweep's
2483/// spans there. Over a crest (`BREP_SWEEP_CLIP_LESS_CREST`, on unless =0) it is
2484/// what stays below the crest. `None` where this is not built (another class than a screw,
2485/// a crest with that switch off, a sweep that never reaches the outer radius or leaves more than
2486/// one region, or anything the level engine refuses): the caller subtracts
2487/// the sweep instead, and that route answers for its own refusals.
2488pub fn sweep_clip_less(tool: &SweptTool, motion: &SolidMotion, clip: &SweepClip) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
2489    if !clip_less_on() || clip.radius[0] != 0.0 || clip.angle.is_some() {
2490        return Ok(None);
2491    }
2492    Ok(level_sweep(tool, motion, clip, true).unwrap_or(None))
2493}
2494
2495/// The switch for [`sweep_clip_less`] (default on).
2496pub fn clip_less_on() -> bool {
2497    crate::switch!("BREP_SWEEP_CLIP_LESS", true)
2498}
2499
2500/// Whether a closed loop of curves is shown simple: no two of its pieces meet
2501/// but consecutive ones at their shared end. Each span of a spline lies in the
2502/// hull of its control points, so within `d` of its chord, `d` the farthest of
2503/// them from it; two spans whose chords stand further apart than their two `d`
2504/// cannot meet. Spans next to each other (in one curve, or the end spans of
2505/// consecutive curves at their shared point) are compared instead by the cones
2506/// their points span from the shared point, in the section's plane (`normal`):
2507/// cones apart but for it, the pieces meet only there. Each curve is read as
2508/// its Bézier pieces, whose points lie close about it and rise along its chord
2509/// (so it does not cross itself). `false` where
2510/// this does not show it, though the loop may yet be simple.
2511pub(crate) fn section_is_simple(profile: &[NurbsCurve], normal: Vec3, scale: f64) -> bool {
2512    struct Span {
2513        curve: usize,
2514        index: usize,
2515        last: bool,
2516        a: Vec3,
2517        b: Vec3,
2518        reach: f64,
2519        lo: Vec3,
2520        hi: Vec3,
2521        hull: Vec<Vec3>,
2522    }
2523    let point = |p: &crate::Vec4| -> Option<Vec3> { (p.w > 0.0).then(|| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)) };
2524    let mut spans = Vec::new();
2525    for (curve, c) in profile.iter().enumerate() {
2526        // Its Bézier pieces: each lies in the hull of its own points, and ends on them.
2527        let zero = crate::Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
2528        let blend = |a: crate::Vec4, b: crate::Vec4, alpha: f64| a.scale(alpha).add(b.scale(1.0 - alpha));
2529        let Some(pieces) = crate::curve::bezier_decompose_raw(&c.knots, &c.control_points, c.degree, zero, blend) else { return false };
2530        // A piece far from its chord (a wide arc) is halved, by de Casteljau, until it lies close.
2531        let mut close: Vec<(Vec<Vec3>, Vec3, Vec3, f64)> = Vec::new();
2532        let mut stack: Vec<(Vec<crate::Vec4>, usize)> = pieces.into_iter().rev().map(|piece| (piece, 0)).collect();
2533        while let Some((piece, depth)) = stack.pop() {
2534            let Some(hull) = piece.iter().map(point).collect::<Option<Vec<_>>>() else { return false };
2535            let (a, b) = (hull[0], hull[hull.len() - 1]);
2536            let reach = hull.iter().map(|&q| segment_distance(q, q, a, b)).fold(0.0, f64::max);
2537            // Its points rising strictly along the chord, the piece is a graph over it
2538            // (variation diminishing, weights positive): it cannot cross itself.
2539            let chord = b.sub(a);
2540            let rising = hull.windows(2).all(|w| w[1].sub(w[0]).dot(chord) > 0.0);
2541            if (reach > 0.05 * chord.length() || !rising) && depth < 8 {
2542                let (mut left, mut right, mut row) = (Vec::new(), Vec::new(), piece);
2543                while !row.is_empty() {
2544                    left.push(row[0]);
2545                    right.push(row[row.len() - 1]);
2546                    row = row.windows(2).map(|w| blend(w[0], w[1], 0.5)).collect();
2547                }
2548                right.reverse();
2549                stack.push((right, depth + 1));
2550                stack.push((left, depth + 1));
2551                continue;
2552            }
2553            if !rising {
2554                return false;
2555            }
2556            close.push((hull, a, b, reach));
2557        }
2558        let total = close.len();
2559        for (index, (hull, a, b, reach)) in close.into_iter().enumerate() {
2560            let lo = hull.iter().fold(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), |m, q| Vec3::new(m.x.min(q.x), m.y.min(q.y), m.z.min(q.z)));
2561            let hi = hull.iter().fold(Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |m, q| Vec3::new(m.x.max(q.x), m.y.max(q.y), m.z.max(q.z)));
2562            spans.push(Span { curve, index, last: index + 1 == total, a, b, reach, lo, hi, hull });
2563        }
2564    }
2565    let count = profile.len();
2566    let margin = 1e-12 * scale;
2567    // Directions in the section's plane, for neighbours' cones.
2568    let Ok(n) = normal.normalized() else { return false };
2569    let Ok(e1) = (if n.x.abs() < 0.9 { n.cross(Vec3::new(1.0, 0.0, 0.0)) } else { n.cross(Vec3::new(0.0, 1.0, 0.0)) }).normalized() else { return false };
2570    let e2 = n.cross(e1);
2571    let origin = spans.first().map(|s| s.a).unwrap_or(Vec3::new(0.0, 0.0, 0.0));
2572    // The arc of directions from `q` its points span (start, width), or None if
2573    // it is not shown narrower than a half turn or a point stands off the plane.
2574    let cone = |hull: &[Vec3], q: Vec3| -> Option<(f64, f64)> {
2575        let mut angles = Vec::new();
2576        for p in hull {
2577            let d = p.sub(q);
2578            if d.dot(n).abs() > 1e-9 * scale {
2579                return None;
2580            }
2581            if d.length() > 1e-12 * scale {
2582                angles.push(d.dot(e2).atan2(d.dot(e1)));
2583            }
2584        }
2585        let first = *angles.first()?;
2586        let wrap = |x: f64| (x - first + PI).rem_euclid(TAU) - PI;
2587        let (lo, hi) = angles.iter().fold((0.0f64, 0.0f64), |(lo, hi), &x| (lo.min(wrap(x)), hi.max(wrap(x))));
2588        (hi - lo < PI - 1e-9).then_some((first + lo, hi - lo))
2589    };
2590    let within = |x: f64, start: f64, width: f64| (x - start).rem_euclid(TAU) <= width + 1e-12;
2591    for (k, s) in spans.iter().enumerate() {
2592        for t in &spans[k + 1..] {
2593            let neighbours = if s.curve == t.curve {
2594                t.index == s.index + 1 || (count == 1 && s.index == 0 && t.last)
2595            } else {
2596                let next = |x: &Span, y: &Span| (x.curve + 1) % count == y.curve && x.last && y.index == 0;
2597                next(s, t) || next(t, s)
2598            };
2599            if neighbours {
2600                // Each lies in the cone its points span from the shared end; the
2601                // cones apart but for that point, the pieces meet only there.
2602                let q = if s.b.sub(t.a).length() <= s.a.sub(t.b).length() { s.b } else { s.a };
2603                let (Some((a0, wa)), Some((b0, wb))) = (cone(&s.hull, q), cone(&t.hull, q)) else { return false };
2604                if within(a0, b0, wb) || within(a0 + wa, b0, wb) || within(b0, a0, wa) || within(b0 + wb, a0, wa) {
2605                    return false;
2606                }
2607                continue;
2608            }
2609            // The hulls' boxes apart: they cannot meet.
2610            if s.hi.x < t.lo.x || t.hi.x < s.lo.x || s.hi.y < t.lo.y || t.hi.y < s.lo.y || s.hi.z < t.lo.z || t.hi.z < s.lo.z {
2611                continue;
2612            }
2613            let flat = |p: Vec3| [p.sub(origin).dot(e1), p.sub(origin).dot(e2)];
2614            if planar_segment_gap(flat(s.a), flat(s.b), flat(t.a), flat(t.b)) <= s.reach + t.reach + margin {
2615                return false;
2616            }
2617        }
2618    }
2619    true
2620}
2621
2622/// The least distance between the segments `a0 a1` and `b0 b1` of a plane,
2623/// zero wherever they may cross or touch: the orientation tests decide that,
2624/// a sign within roundoff of zero counted as touching; apart, the least
2625/// distance is from an end of one to the other, which nothing cancels in.
2626fn planar_segment_gap(a0: [f64; 2], a1: [f64; 2], b0: [f64; 2], b1: [f64; 2]) -> f64 {
2627    let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];
2628    let cross = |u: [f64; 2], v: [f64; 2]| u[0] * v[1] - u[1] * v[0];
2629    let norm = |u: [f64; 2]| u[0].hypot(u[1]);
2630    // The sign of the turn p q r, None within roundoff of zero.
2631    let side = |p: [f64; 2], q: [f64; 2], r: [f64; 2]| -> Option<bool> {
2632        let (u, v) = (sub(q, p), sub(r, p));
2633        let turn = cross(u, v);
2634        (turn.abs() > 1e-12 * norm(u) * norm(v)).then_some(turn > 0.0)
2635    };
2636    let straddles = |p: Option<bool>, q: Option<bool>| p.is_none() || q.is_none() || p != q;
2637    let (o1, o2, o3, o4) = (side(a0, a1, b0), side(a0, a1, b1), side(b0, b1, a0), side(b0, b1, a1));
2638    let collinear = o1.is_none() && o2.is_none() && o3.is_none() && o4.is_none();
2639    if !collinear && straddles(o1, o2) && straddles(o3, o4) {
2640        return 0.0;
2641    }
2642    let to_segment = |p: [f64; 2], q0: [f64; 2], q1: [f64; 2]| -> f64 {
2643        let (d, w) = (sub(q1, q0), sub(p, q0));
2644        let length = d[0] * d[0] + d[1] * d[1];
2645        let t = if length > 0.0 { ((w[0] * d[0] + w[1] * d[1]) / length).clamp(0.0, 1.0) } else { 0.0 };
2646        norm([w[0] - d[0] * t, w[1] - d[1] * t])
2647    };
2648    to_segment(a0, b0, b1).min(to_segment(a1, b0, b1)).min(to_segment(b0, a0, a1)).min(to_segment(b1, a0, a1))
2649}
2650
2651/// The least distance between the segments `a0 a1` and `b0 b1`.
2652fn segment_distance(a0: Vec3, a1: Vec3, b0: Vec3, b1: Vec3) -> f64 {
2653    let (u, v, w) = (a1.sub(a0), b1.sub(b0), a0.sub(b0));
2654    let (a, b, c, d, e) = (u.dot(u), u.dot(v), v.dot(v), u.dot(w), v.dot(w));
2655    let denominator = a * c - b * b;
2656    let clamp = |x: f64| x.clamp(0.0, 1.0);
2657    let (mut s, mut t);
2658    if a <= f64::MIN_POSITIVE && c <= f64::MIN_POSITIVE {
2659        return w.length();
2660    } else if a <= f64::MIN_POSITIVE {
2661        s = 0.0;
2662        t = clamp(e / c);
2663    } else if c <= f64::MIN_POSITIVE {
2664        t = 0.0;
2665        s = clamp(-d / a);
2666    } else {
2667        s = if denominator > 1e-300 { clamp((b * e - c * d) / denominator) } else { 0.0 };
2668        t = (b * s + e) / c;
2669        if t < 0.0 {
2670            t = 0.0;
2671            s = clamp(-d / a);
2672        } else if t > 1.0 {
2673            t = 1.0;
2674            s = clamp((b - d) / a);
2675        }
2676    }
2677    a0.add(u.scale(s)).sub(b0.add(v.scale(t))).length()
2678}
2679
2680/// The switch for the screw route's loft without its self-intersection scan
2681/// where the walls are carried (default on; `=0` scans as before).
2682fn screw_loft_unscanned_on() -> bool {
2683    crate::switch!("BREP_SWEEP_SCREW_LOFT_UNSCANNED", true)
2684}
2685
2686/// The switch for [`sweep_clip_less`] over a screw whose turns meet at a crest
2687/// (default on; `=0` answers None): above the crest the sweep takes all the clip holds, so the
2688/// clip less the sweep is what stays below it, which the engine builds anyway.
2689pub fn clip_less_crest_on() -> bool {
2690    crate::switch!("BREP_SWEEP_CLIP_LESS_CREST", true)
2691}
2692
2693/// The level engine: the sweep within the clip, or (`complement`) the clip
2694/// less the sweep, `None` where the complement is not built.
2695fn level_sweep(tool: &SweptTool, motion: &SolidMotion, clip: &SweepClip, complement: bool) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
2696    let narrowed: SweepClip;
2697    // --- Frame and classification.
2698    let ez = clip
2699        .axis_direction
2700        .normalized()
2701        .or_refuse(KernelStage::Collect, "clip_axis")?;
2702    let ex = clip
2703        .reference
2704        .sub(ez.scale(clip.reference.dot(ez)))
2705        .normalized()
2706        .or_refuse(KernelStage::Collect, "clip_reference")?;
2707    let frame = Frame { origin: clip.axis_origin, ex, ey: ez.cross(ex), ez };
2708    if !(motion.from.is_finite() && motion.to.is_finite() && motion.to > motion.from) {
2709        return Err(KernelRefusal::input(
2710            KernelStage::Collect,
2711            "motion_range",
2712            format!("{SOLID_SWEEP_REFUSAL}: the motion's range must run forwards"),
2713        ));
2714    }
2715    if motion.steps.is_empty() {
2716        return Err(KernelRefusal::input(KernelStage::Collect, "motion_empty", format!("{SOLID_SWEEP_REFUSAL}: no motion")));
2717    }
2718    let mut axes = Vec::with_capacity(motion.steps.len());
2719    for step in &motion.steps {
2720        axes.push(step.axis_direction.normalized().or_refuse(KernelStage::Collect, "step_axis")?);
2721    }
2722    if !(clip.radius[0] >= 0.0 && clip.radius[1] > clip.radius[0] && clip.axial[1] > clip.axial[0]) {
2723        return Err(KernelRefusal::input(
2724            KernelStage::Collect,
2725            "clip_range",
2726            format!("{SOLID_SWEEP_REFUSAL}: the clip's ranges must be increasing"),
2727        ));
2728    }
2729    let on_axis = |origin: Vec3, axis: Vec3| -> bool {
2730        let parallel = axis.cross(ez).length() < 1e-12;
2731        let offset = origin.sub(clip.axis_origin);
2732        parallel && offset.sub(ez.scale(offset.dot(ez))).length() < 1e-9 * (1.0 + clip.radius[1])
2733    };
2734    // One screw about the clip's axis, as its axial advance per radian about +ez.
2735    let screw_about_clip = || -> Option<f64> {
2736        let step = motion.steps.first()?;
2737        (motion.steps.len() == 1 && step.turn != 0.0 && step.advance != 0.0 && on_axis(step.axis_origin, axes[0])).then(|| {
2738            let sense = axes[0].dot(ez).signum();
2739            (step.advance * sense) / (step.turn * sense)
2740        })
2741    };
2742    let mut bar: Option<crate::solid_sweep_bar::Bar> = None;
2743    let class = 'class: { match tool {
2744        SweptTool::Bar { origin, normal, section, from, to, draft } => {
2745            let Some(c) = screw_about_clip() else {
2746                return Err(refuse("motion_class", "a bar is swept here only by one screw about the clip's axis".into()));
2747            };
2748            bar = Some(crate::solid_sweep_bar::Bar::new(*origin, *normal, section, *from, *to, *draft)?);
2749            Class::Screw(c)
2750        }
2751        SweptTool::Revolved { meridian, .. } => {
2752            validate_outline(meridian, "meridian")?;
2753            if motion.steps.len() != 1 || !on_axis(motion.steps[0].axis_origin, axes[0]) {
2754                return Err(refuse(
2755                    "motion_class",
2756                    "a solid of revolution is swept here only by one screw or turn about the clip's axis".into(),
2757                ));
2758            }
2759            let step = motion.steps[0];
2760            let sense = axes[0].dot(ez).signum();
2761            if step.turn == 0.0 {
2762                return Err(refuse("motion_class", "a slide of a solid of revolution is not built here".into()));
2763            }
2764            if step.advance == 0.0 {
2765                Class::Turn
2766            } else {
2767                // axial advance per radian about +ez
2768                Class::Screw((step.advance * sense) / (step.turn * sense))
2769            }
2770        }
2771        SweptTool::Prism { normal, outline, from, to, origin, x_axis } => {
2772            validate_outline(outline, "prism")?;
2773            let n = normal.normalized().or_refuse(KernelStage::Collect, "prism_normal")?;
2774            let screw = motion.steps.len() == 1
2775                && motion.steps[0].turn != 0.0
2776                && motion.steps[0].advance != 0.0
2777                && on_axis(motion.steps[0].axis_origin, axes[0])
2778                && n.cross(ez).length() <= 1e-12;
2779            if screw {
2780                // A screw carries the prism's ends along, so the clip may run past them.
2781                let step = motion.steps[0];
2782                let sense = axes[0].dot(ez).signum();
2783                break 'class Class::Screw((step.advance * sense) / (step.turn * sense));
2784            }
2785            if n.cross(ez).length() > 1e-12 {
2786                // Across the screw's axis the prism is a bar with no draft.
2787                if let Some(c) = screw_about_clip() {
2788                    let xa = x_axis.sub(n.scale(x_axis.dot(n))).normalized().or_refuse(KernelStage::Collect, "prism_x_axis")?;
2789                    let ya = n.cross(xa);
2790                    let at = |q: [f64; 2]| origin.add(xa.scale(q[0])).add(ya.scale(q[1]));
2791                    let mut section = Vec::with_capacity(outline.len());
2792                    for piece in outline {
2793                        section.push(match *piece {
2794                            OutlinePiece::Line { from, to } => make_line(at(from), at(to)),
2795                            // an arc run clockwise is one run the other way about the mirrored axis
2796                            OutlinePiece::Arc { centre, radius, start, end } if end >= start => make_arc(at(centre), xa, ya, radius, start, end),
2797                            OutlinePiece::Arc { centre, radius, start, end } => make_arc(at(centre), xa, ya.scale(-1.0), radius, -start, -end),
2798                            OutlinePiece::Ellipse { .. } => {
2799                                return Err(refuse("prism_outline", "a prism across the screw's axis takes lines and circular arcs only".into()))
2800                            }
2801                        }
2802                        .or_refuse(KernelStage::Collect, "prism_outline")?);
2803                    }
2804                    bar = Some(crate::solid_sweep_bar::Bar::new(*origin, n, &section, *from, *to, 0.0)?);
2805                    break 'class Class::Screw(c);
2806                }
2807                return Err(refuse("motion_class", "a prism is swept here only along its own direction's clip axis".into()));
2808            }
2809            for (step, axis) in motion.steps.iter().zip(&axes) {
2810                let turn_ok = step.turn == 0.0 || axis.cross(n).length() < 1e-12;
2811                let advance_ok = step.advance == 0.0 || (step.turn == 0.0 && axis.dot(n).abs() < 1e-12);
2812                if !(turn_ok && advance_ok) {
2813                    return Err(refuse(
2814                        "motion_class",
2815                        "a prism is swept here only by turns about axes along it and slides across it".into(),
2816                    ));
2817                }
2818            }
2819            // The clip's axial range must lie within the prism's extent.
2820            let base = clip.axis_origin.sub(*origin).dot(n);
2821            let sense = ez.dot(n);
2822            let h0 = base + sense * clip.axial[0];
2823            let h1 = base + sense * clip.axial[1];
2824            if h0.min(h1) < *from || h0.max(h1) > *to {
2825                return Err(refuse(
2826                    "clip_past_prism",
2827                    "the clip reaches past the prism's ends, where the sweep is not a prism".into(),
2828                ));
2829            }
2830            Class::Planar
2831        }
2832    } };
2833    // A leaning end face folds into a wall of its own, which is not built.
2834    if let (Some(bar), Class::Screw(c)) = (&bar, class) {
2835        if bar.end_folds(clip.axis_origin, ez, c, clip.radius) {
2836            return Err(refuse(
2837                "bar_end_fold",
2838                "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(),
2839            ));
2840        }
2841    }
2842    let prism_height = match tool {
2843        SweptTool::Prism { from, to, .. } => 0.5 * (from + to),
2844        _ => 0.0,
2845    };
2846
2847    // Does the motion end where it began, as a set? For a prism, every outline
2848    // vertex at the last position must sit on some vertex at the first (the plus
2849    // turns 540°, which its half-turn symmetry makes a whole period). The
2850    // permutation says which piece continues which across the wrap.
2851    let wrap: Option<Vec<usize>> = match tool {
2852        SweptTool::Bar { .. } => None,
2853        SweptTool::Prism { .. } if matches!(class, Class::Screw(_)) => None,
2854        SweptTool::Prism { origin, normal, x_axis, outline, .. } => {
2855            let probe = Engine {
2856                tool,
2857                motion,
2858                axes: axes.clone(),
2859                frame,
2860                class,
2861                clip,
2862                bar: None,
2863                crest_gap: false,
2864                sources: Vec::new(),
2865                grids: Vec::new(),
2866                critical: Vec::new(),
2867                critical_params: Vec::new(),
2868                critical_bands: Vec::new(),
2869                angular: true,
2870                prism_height,
2871                scale: 1.0,
2872                cache: std::cell::RefCell::new(std::collections::HashMap::new()),
2873                        edge_samples: std::cell::RefCell::new(std::collections::HashMap::new()),
2874                wrap: None,
2875                counters: std::cell::Cell::new((0, 0, 0, 0.0, 0.0)),
2876                jet: std::cell::Cell::new(extremum_jet_on() && !extremum_jet_check_on()),
2877                tool_frame: tool_frame(tool),
2878            };
2879            let n = normal.normalized_or(*normal);
2880            let xa = x_axis.normalized_or(*x_axis);
2881            let ya = n.cross(xa);
2882            let vertex = |k: usize, t: f64| {
2883                let q = outline[k].point(0.0);
2884                probe.motion_apply(t, origin.add(xa.scale(q[0])).add(ya.scale(q[1])).add(n.scale(prism_height)))
2885            };
2886            let size = scale_of(outline);
2887            let mut map = Vec::with_capacity(outline.len());
2888            for k in 0..outline.len() {
2889                let end = vertex(k, motion.to);
2890                match (0..outline.len()).find(|&j| vertex(j, motion.from).sub(end).length() < 1e-9 * size) {
2891                    Some(j) => map.push(j),
2892                    None => break,
2893                }
2894            }
2895            let consistent = map.len() == outline.len()
2896                && (0..outline.len()).all(|k| map[(k + 1) % outline.len()] == (map[k] + 1) % outline.len());
2897            consistent.then_some(map)
2898        }
2899        SweptTool::Revolved { .. } => None,
2900    };
2901    let periodic_motion = wrap.is_some();
2902    let mut sources = Vec::new();
2903    match tool {
2904        _ if bar.is_some() => {
2905            let bar = bar.as_ref().expect("bar");
2906            for piece in 0..bar.piece_count() {
2907                sources.push(Source::BarSide { piece });
2908                if !bar.periodic {
2909                    sources.push(Source::BarEdge { piece });
2910                }
2911                sources.push(Source::BarRim { piece, end: false });
2912                sources.push(Source::BarRim { piece, end: true });
2913            }
2914        }
2915        SweptTool::Bar { .. } => {}
2916        SweptTool::Revolved { meridian, .. } => {
2917            // A piece lying on the axis revolves into nothing, and a corner on the
2918            // axis into a point: neither bounds the tool.
2919            let on_axis = |p: [f64; 2]| p[0].abs() <= 1e-12 * scale_of(meridian);
2920            for piece in 0..meridian.len() {
2921                let lies_on_axis = matches!(meridian[piece], OutlinePiece::Line { from, to } if on_axis(from) && on_axis(to));
2922                if !lies_on_axis {
2923                    sources.push(Source::RevolvedFace { piece });
2924                }
2925                if !meridian[piece].is_full_circle() && !on_axis(meridian[piece].point(0.0)) {
2926                    sources.push(Source::RevolvedCorner { piece });
2927                }
2928            }
2929        }
2930        SweptTool::Prism { outline, .. } if matches!(class, Class::Screw(_)) => {
2931            for piece in 0..outline.len() {
2932                sources.push(Source::ScrewPrismSide { piece });
2933                if !outline[piece].is_full_circle() {
2934                    sources.push(Source::ScrewPrismEdge { piece });
2935                }
2936                sources.push(Source::ScrewPrismRim { piece, end: false });
2937                sources.push(Source::ScrewPrismRim { piece, end: true });
2938            }
2939        }
2940        SweptTool::Prism { outline, .. } => {
2941            for piece in 0..outline.len() {
2942                sources.push(Source::PrismFace { piece });
2943                if !outline[piece].is_full_circle() {
2944                    sources.push(Source::PrismVertex { piece });
2945                }
2946                if !periodic_motion {
2947                    sources.push(Source::PrismEnd { piece, end: false });
2948                    sources.push(Source::PrismEnd { piece, end: true });
2949                }
2950            }
2951        }
2952    }
2953    let scale = clip.radius[1].max(1.0);
2954    let mut engine = Engine {
2955        tool,
2956        motion,
2957        axes,
2958        frame,
2959        class,
2960        clip,
2961        bar,
2962        crest_gap: false,
2963        sources,
2964        grids: Vec::new(),
2965        critical: Vec::new(),
2966        critical_params: Vec::new(),
2967        critical_bands: Vec::new(),
2968        angular: class != Class::Turn,
2969        prism_height,
2970        scale,
2971        cache: std::cell::RefCell::new(std::collections::HashMap::new()),
2972        edge_samples: std::cell::RefCell::new(std::collections::HashMap::new()),
2973        wrap,
2974        counters: std::cell::Cell::new((0, 0, 0, 0.0, 0.0)),
2975        jet: std::cell::Cell::new(extremum_jet_on() && !extremum_jet_check_on()),
2976        tool_frame: tool_frame(tool),
2977    };
2978    engine.grids = engine
2979        .sources
2980        .iter()
2981        .map(|source| if Engine::is_face(*source) { Some(engine.build_grid(*source)) } else { None })
2982        .collect();
2983    let critical: Vec<_> = (0..engine.sources.len()).map(|k| engine.source_critical(k)).collect();
2984    engine.critical_params = critical.iter().map(|c| c.1.clone()).collect();
2985    engine.critical_bands = critical.iter().map(|c| c.2.clone()).collect();
2986    engine.critical = critical.into_iter().map(|c| c.0).collect();
2987    // The levels of the tool's points on its own axis (a cone's apex): the
2988    // envelope turns a corner there.
2989    let mut apex_levels: Vec<f64> = Vec::new();
2990    if let (SweptTool::Revolved { axis_origin, axis_direction, meridian, .. }, true) = (tool, apex_tip_on()) {
2991        let axis = axis_direction.normalized_or(*axis_direction);
2992        let count = meridian.len();
2993        for piece in 0..count {
2994            let corner = meridian[piece].point(0.0);
2995            if corner[0].abs() > 1e-12 * scale_of(meridian) {
2996                continue;
2997            }
2998            let apex = engine.reduce(engine.frame.local(axis_origin.add(axis.scale(corner[1]))));
2999            apex_levels.push(apex.0);
3000            // the faces on either side of the corner
3001            for neighbour in [piece, (piece + count - 1) % count] {
3002                if let Some(index) = engine.sources.iter().position(|source| matches!(source, Source::RevolvedFace { piece } if *piece == neighbour)) {
3003                    engine.critical[index].push(apex);
3004                }
3005            }
3006        }
3007    }
3008
3009    // --- Ends: a screw or turn must not reach the clip at either end.
3010    //     A turn through a whole revolution or more is the exception: it
3011    //     carries the tool round onto itself, so its sweep is invariant
3012    //     under the turn wherever its ends lie.
3013    let whole_turn = class == Class::Turn
3014        && whole_turn_on()
3015        && (motion.steps[0].turn * (motion.to - motion.from)).abs() >= TAU * (1.0 - 1e-12);
3016    if matches!(class, Class::Screw(_) | Class::Turn) && !whole_turn {
3017        check_ends_clear(&engine)?;
3018    }
3019
3020    // The clip less the sweep is built for a screw only.
3021    if complement && !matches!(class, Class::Screw(_)) {
3022        return Ok(None);
3023    }
3024
3025    // --- A screw whose grooves meet: above a crest level nothing stays. Build
3026    //     what stays below it, and take that from the clip at the end.
3027    //     The clip less the sweep is then what stays itself (on unless =0).
3028    let mut crest = None;
3029    let mut kept_only = false;
3030    if matches!(class, Class::Screw(_)) && clip.radius[0] == 0.0 && clip.angle.is_none() && whole_level_on() {
3031        crest = crest_level(&engine)?;
3032        if complement && crest.is_some() {
3033            if !clip_less_crest_on() {
3034                return Ok(None);
3035            }
3036            kept_only = true;
3037        }
3038        if let Some(level) = crest {
3039            narrowed = SweepClip { radius: [0.0, level], ..clip.clone() };
3040            engine.clip = &narrowed;
3041            engine.crest_gap = true;
3042        }
3043    }
3044    // What stays below a crest is built as for the sweep; only the answer differs.
3045    let complement = complement && !kept_only;
3046
3047    // --- A straight-sided prism along a screw's axis: its reduced section
3048    //     exactly (default off), built as the levels' pieces would be.
3049    if let (Class::Screw(c), None, None, true, SweptTool::Prism { origin, normal, x_axis, outline, from, to }) =
3050        (class, crest, engine.bar.as_ref(), crate::planar_region::screw_section_on() && !complement, tool)
3051    {
3052        let n = normal.normalized_or(*normal);
3053        let xa = x_axis.sub(n.scale(x_axis.dot(n))).normalized_or(*x_axis);
3054        let ya = n.cross(xa);
3055        let lines = outline.iter().all(|p| matches!(p, OutlinePiece::Line { .. }));
3056        if lines && clip.angle.is_none() {
3057            let corners: Vec<[f64; 2]> = outline
3058                .iter()
3059                .map(|p| {
3060                    let OutlinePiece::Line { from: q, .. } = p else { unreachable!() };
3061                    let l = engine.frame.local(origin.add(xa.scale(q[0])).add(ya.scale(q[1])));
3062                    [l[0], l[1]]
3063                })
3064                .collect();
3065            let (za, zb) = (engine.frame.local(origin.add(n.scale(*from)))[2], engine.frame.local(origin.add(n.scale(*to)))[2]);
3066            if let Some(loops) = crate::planar_region::screw_section_loops(corners, [za.min(zb), za.max(zb)], c, clip.radius)? {
3067                let mut bodies = Vec::with_capacity(loops.len());
3068                for arcs in loops {
3069                    let pieces: Vec<Piece> = arcs
3070                        .into_iter()
3071                        .map(|(points, level)| {
3072                            // (level, o): the reduced plane's polar coordinates, o unwrapped along the piece.
3073                            let mut out: Vec<(f64, f64)> = Vec::with_capacity(points.len());
3074                            for q in points {
3075                                let raw = q[1].atan2(q[0]);
3076                                let o = match out.last() {
3077                                    Some(&(_, previous)) => previous + wrap_pi(raw - previous),
3078                                    None => raw,
3079                                };
3080                                out.push((q[0].hypot(q[1]), o));
3081                            }
3082                            let m = out.len();
3083                            Piece { points: out, sigma: (0..m).map(|k| k as f64 / (m - 1) as f64).collect(), level_segment: level }
3084                        })
3085                        .collect();
3086                    bodies.push(build_body(&engine, &pieces)?);
3087                }
3088                return Ok(Some(bodies));
3089            }
3090        }
3091    }
3092
3093    // --- Scan the levels for events.
3094    let (l0, l1) = (engine.clip.radius[0], engine.clip.radius[1]);
3095    let scan = 192;
3096    let mut levels: Vec<f64> = (0..=scan).map(|k| l0 + (l1 - l0) * k as f64 / scan as f64).collect();
3097    // Never sample exactly on a critical level: nudge the scan off them.
3098    for level in &mut levels {
3099        for critical in engine.critical.iter().flatten() {
3100            if (critical.0 - *level).abs() < 1e-9 * scale {
3101                *level += 1e-7 * (l1 - l0);
3102            }
3103        }
3104    }
3105    let mut structure = Vec::with_capacity(levels.len());
3106    for &level in &levels {
3107        structure.push(engine.intervals_at(level)?);
3108    }
3109    let debug = std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok();
3110    let scan_events = |shortcut: bool| -> Result<Vec<f64>, KernelRefusal> {
3111        let mut breaks = vec![l0];
3112        for k in 0..scan {
3113            let (a, b) = (levels[k], levels[k + 1]);
3114            if shortcut && !compatible(&engine, &structure[k], &structure[k + 1]) {
3115                if let Some(c) = lone_critical_inside(&engine, a, b, scale) {
3116                    let step = CRITICAL_EVENT_STEP * scale;
3117                    let (below, above) = (c - step, c + step);
3118                    if below > a && above < b {
3119                        let (s_below, s_above) = (engine.intervals_at(below)?, engine.intervals_at(above)?);
3120                        // A birth or death: the count of intervals changes
3121                        // across the level (an interval merely sliding is
3122                        // incompatible too, but subdivision would smooth it
3123                        // away and name no event).
3124                        if s_below.len() != s_above.len() {
3125                            find_events(&engine, a, &structure[k], below, &s_below, &mut breaks, 0)?;
3126                            breaks.push(c);
3127                            critical_events_record(0, 0, 1);
3128                            find_events(&engine, above, &s_above, b, &structure[k + 1], &mut breaks, 0)?;
3129                            continue;
3130                        }
3131                    }
3132                }
3133            }
3134            find_events(&engine, a, &structure[k], b, &structure[k + 1], &mut breaks, 0)?;
3135        }
3136        breaks.push(l1);
3137        // Snap each event to a critical level of a source when one is that close.
3138        // A birth or death is found by bisection only to where the seeding first
3139        // sees the level's contour, which near a tip is a √ away from it: the
3140        // critical level is the exact one.
3141        let last = breaks.len() - 1;
3142        for level in breaks[1..last].iter_mut() {
3143            let mut nearest = *level;
3144            let mut distance = 1e-5 * scale;
3145            for critical in engine.critical.iter().flatten() {
3146                if (critical.0 - *level).abs() < distance {
3147                    distance = (critical.0 - *level).abs();
3148                    nearest = critical.0;
3149                }
3150            }
3151            *level = nearest;
3152        }
3153        Ok(breaks)
3154    };
3155    let mut breaks = if critical_events_check_on() {
3156        // The bisection's answer is kept; a shortcut that refuses where it
3157        // answered counts as a difference.
3158        let plain = scan_events(false)?;
3159        let short = scan_events(true);
3160        let same = match &short {
3161            Ok(short) => plain.len() == short.len() && plain.iter().zip(short).all(|(x, y)| (x - y).abs() <= 1e-12 * scale),
3162            Err(_) => false,
3163        };
3164        critical_events_record(1, u64::from(!same), 0);
3165        if !same && debug {
3166            eprintln!("critical events check: bisection {plain:?} against shortcut {:?}", short.as_ref().map_err(|e| e.to_string()));
3167        }
3168        plain
3169    } else {
3170        scan_events(critical_events_on())?
3171    };
3172    // An apex's level is a break even where no source hands over there: the
3173    // face's own contour turns a corner at the apex, and one band through it
3174    // could not be fitted (an upright cone turned in a window was refused).
3175    if apex_breaks_on() {
3176        for &level in &apex_levels {
3177            if level > l0 + 1e-9 * scale && level < l1 - 1e-9 * scale && !breaks.iter().any(|b| (b - level).abs() < 1e-9 * scale) {
3178                breaks.push(level);
3179            }
3180        }
3181    }
3182    breaks.sort_by(|a, b| a.total_cmp(b));
3183    // A source handing over to the next one at an edge can flicker over a few
3184    // bisection steps (the face's extremum sits a hair inside its domain); the
3185    // bands that leaves are far below any feature. Keep the first break of each
3186    // cluster, and the clip's own ends.
3187    let mut kept: Vec<f64> = Vec::with_capacity(breaks.len());
3188    for (index, &level) in breaks.iter().enumerate() {
3189        let is_end = index == 0 || index + 1 == breaks.len();
3190        match kept.last() {
3191            Some(&previous) if level - previous < 1e-5 * scale => {
3192                if is_end {
3193                    kept.pop();
3194                    kept.push(level);
3195                }
3196            }
3197            _ => kept.push(level),
3198        }
3199    }
3200    let mut breaks = kept;
3201
3202    // --- Merges no critical point explains: a FOLD the face's own Newton cannot
3203    //     reach (the plus wheel's arm tip: its level varies by 1e-4 along the
3204    //     envelope there). The gap between the two merging ends closes as
3205    //     √(ℓf − ℓ), so gap² is smooth in ℓ: fit it as a quadratic through three
3206    //     levels below the event, outside the band where the extremum Newton
3207    //     flickers, and take its root as the merge level; the gap's middle,
3208    //     extrapolated the same way, is the merge point. Both ends' sources
3209    //     record it as a critical point, and the bands keep their samples away
3210    //     from it (`fold_ends`).
3211    let mut fold_ends: Vec<f64> = Vec::new();
3212    for index in 1..breaks.len().saturating_sub(1) {
3213        let level = breaks[index];
3214        let snapped = engine.critical.iter().flatten().any(|c| (c.0 - level).abs() < 1e-9 * scale);
3215        if snapped {
3216            continue;
3217        }
3218        let room = (level - breaks[index - 1]).min(breaks[index + 1] - level);
3219        // Close enough that the √ law holds to the fit's order, far enough to be
3220        // clear of the flicker (the plus wheel: 2e-4 out, flicker inside 1e-5).
3221        let delta = (5e-6 * scale).min(room / 8.0);
3222        let below = engine.intervals_at(level - delta)?;
3223        let above = engine.intervals_at(level + delta)?;
3224        if below.len() <= above.len() {
3225            continue;
3226        }
3227        // Adjacent intervals below whose facing ends close into one above.
3228        let mut refined: Vec<(f64, f64, usize, usize)> = Vec::new();
3229        for k in 0..below.len() {
3230            let (x, y) = (below[k], below[(k + 1) % below.len()]);
3231            if !engine.angular && k + 1 == below.len() {
3232                break;
3233            }
3234            let gap_at = |intervals: &[Interval]| -> Option<(f64, f64)> {
3235                // the pair nearest (x.hi, y.lo) at this level
3236                let mut best: Option<(f64, f64, f64)> = None;
3237                for i in 0..intervals.len() {
3238                    let (p, q) = (intervals[i], intervals[(i + 1) % intervals.len()]);
3239                    let d = engine.o_difference(p.hi, x.hi).abs() + engine.o_difference(q.lo, y.lo).abs();
3240                    if best.map_or(true, |b| d < b.2) {
3241                        let gap = engine.o_difference(q.lo, p.hi);
3242                        best = Some((gap, p.hi + 0.5 * gap, d));
3243                    }
3244                }
3245                best.map(|b| (b.0, b.1))
3246            };
3247            let mut samples = Vec::new();
3248            for factor in [1.0, 2.0, 4.0] {
3249                let l = level - delta * factor;
3250                let intervals = engine.intervals_at(l)?;
3251                if intervals.len() != below.len() {
3252                    break;
3253                }
3254                if let Some((gap, middle)) = gap_at(&intervals) {
3255                    samples.push((l, gap, middle));
3256                }
3257            }
3258            if samples.len() < 3 || samples.iter().any(|s| s.1 <= 0.0 || s.1 > 0.5) {
3259                continue;
3260            }
3261            // Quadratic through (l, gap²); its root above the samples.
3262            let quad = |values: [f64; 3]| -> (f64, f64, f64) {
3263                let (x0, x1, x2) = (samples[0].0, samples[1].0, samples[2].0);
3264                let (y0, y1, y2) = (values[0], values[1], values[2]);
3265                let d01 = (y0 - y1) / (x0 - x1);
3266                let d12 = (y1 - y2) / (x1 - x2);
3267                let a2 = (d01 - d12) / (x0 - x2);
3268                let a1 = d01 - a2 * (x0 + x1);
3269                let a0 = y0 - a1 * x0 - a2 * x0 * x0;
3270                (a0, a1, a2)
3271            };
3272            let (c0, c1, c2) = quad([samples[0].1.powi(2), samples[1].1.powi(2), samples[2].1.powi(2)]);
3273            let root = if c2.abs() < 1e-300 {
3274                -c0 / c1
3275            } else {
3276                let disc = c1 * c1 - 4.0 * c2 * c0;
3277                if disc < 0.0 {
3278                    continue;
3279                }
3280                let r1 = (-c1 + disc.sqrt()) / (2.0 * c2);
3281                let r2 = (-c1 - disc.sqrt()) / (2.0 * c2);
3282                if (r1 - level).abs() < (r2 - level).abs() { r1 } else { r2 }
3283            };
3284            if !(root > samples[0].0 && (root - level).abs() < delta) {
3285                continue;
3286            }
3287            let (m0, m1, m2) = quad([samples[0].2, samples[1].2, samples[2].2]);
3288            let middle = m0 + m1 * root + m2 * root * root;
3289            refined.push((root, middle, x.hi_source, y.lo_source));
3290        }
3291        if !refined.is_empty() {
3292            // Every merging pair records its own point; the break is their mean
3293            // level (equal to round-off where the spaces are copies of one).
3294            let root = refined.iter().map(|r| r.0).sum::<f64>() / refined.len() as f64;
3295            for &(own, middle, a_source, b_source) in &refined {
3296                if debug {
3297                    eprintln!("  fold: break {level:.12} -> {own:.12} at o {middle:.12}");
3298                }
3299                engine.critical[a_source].push((root, middle));
3300                engine.critical[b_source].push((root, middle));
3301            }
3302            breaks[index] = root;
3303            fold_ends.push(root);
3304        }
3305    }
3306
3307    if debug {
3308        eprintln!("solid sweep: after events {:?} breaks {}", engine.counters.get(), breaks.len());
3309    }
3310    // --- Sample each band's interval ends.
3311    let mut pieces: Vec<Piece> = Vec::new();
3312    // Per band: the intervals at its bottom and top (for the level segments).
3313    let mut band_ends: Vec<(f64, f64, Vec<(usize, usize)>)> = Vec::new();
3314    for window in breaks.windows(2) {
3315        let (a, b) = (window[0], window[1]);
3316        if b - a < 1e-12 * scale {
3317            continue;
3318        }
3319        let mid = engine.intervals_at(0.5 * (a + b))?;
3320        if mid.is_empty() {
3321            continue;
3322        }
3323        let (band_pieces, _, _) = sample_band(&engine, a, b, &mid, &fold_ends)?;
3324        let first = pieces.len();
3325        let pairs = (0..band_pieces.len() / 2).map(|i| (first + 2 * i, first + 2 * i + 1)).collect();
3326        pieces.extend(band_pieces);
3327        band_ends.push((a, b, pairs));
3328    }
3329    if pieces.is_empty() {
3330        return Ok(if complement { None } else { Some(Vec::new()) });
3331    }
3332    // The clip less the sweep: the sweep must reach the clip's outer radius,
3333    // where the material's boundary is the circle less the sweep's spans.
3334    let top = engine.clip.radius[1];
3335    if complement && !band_ends.iter().any(|(_, b, pairs)| !pairs.is_empty() && (b - top).abs() < 1e-12 * scale) {
3336        return Ok(None);
3337    }
3338    if debug {
3339        eprintln!("solid sweep: after bands {:?}", engine.counters.get());
3340        for (k, critical) in engine.critical.iter().enumerate() {
3341            eprintln!("  source {k} {:?}: critical {:?}", engine.sources[k], critical);
3342        }
3343    }
3344
3345    // --- One value per interval end at each break. The band below and the band
3346    //     above read an end that continues across a break from their own
3347    //     sources, at a level found only to the flicker cluster; the two agree to
3348    //     far below any feature but not to the bit, and a sliver of level segment
3349    //     between them is an edge no solid should carry. Snap every end at a level
3350    //     to its cluster's first value (ends of one interval meeting at a tip
3351    //     included).
3352    let snap_length = 1e-5 * scale;
3353    let mut break_levels: Vec<f64> = band_ends.iter().flat_map(|e| [e.0, e.1]).collect();
3354    break_levels.sort_by(|a, b| a.total_cmp(b));
3355    break_levels.dedup_by(|b, a| (*b - *a).abs() < 1e-12 * scale);
3356    for &level in &break_levels {
3357        let tolerance = if engine.angular { snap_length / level.max(1e-12) } else { snap_length };
3358        let mut ends: Vec<(usize, bool)> = Vec::new();
3359        for (index, piece) in pieces.iter().enumerate() {
3360            if (piece.points[0].0 - level).abs() < 1e-12 * scale {
3361                ends.push((index, false));
3362            }
3363            if (piece.points.last().expect("nonempty").0 - level).abs() < 1e-12 * scale {
3364                ends.push((index, true));
3365            }
3366        }
3367        let value = |pieces: &Vec<Piece>, (index, last): (usize, bool)| {
3368            if last { pieces[index].points.last().expect("nonempty").1 } else { pieces[index].points[0].1 }
3369        };
3370        for i in 0..ends.len() {
3371            let anchor = value(&pieces, ends[i]);
3372            for j in i + 1..ends.len() {
3373                let other = value(&pieces, ends[j]);
3374                let d = engine.o_difference(other, anchor);
3375                if d.abs() < tolerance && d != 0.0 {
3376                    let (index, last) = ends[j];
3377                    let target = other - d;
3378                    let points = &mut pieces[index].points;
3379                    if last {
3380                        points.last_mut().expect("nonempty").1 = target;
3381                    } else {
3382                        points[0].1 = target;
3383                    }
3384                }
3385            }
3386        }
3387    }
3388
3389    // --- Level segments: where the intervals above and below a level differ.
3390    let mut all_levels: Vec<f64> = band_ends.iter().flat_map(|e| [e.0, e.1]).collect();
3391    all_levels.sort_by(|a, b| a.total_cmp(b));
3392    all_levels.dedup_by(|b, a| (*b - *a).abs() < 1e-12 * scale);
3393    for &level in &all_levels {
3394        let mut below: Vec<(f64, f64)> = Vec::new();
3395        let mut above: Vec<(f64, f64)> = Vec::new();
3396        for (a, b, pairs) in &band_ends {
3397            for &(lo, hi) in pairs {
3398                let (lo, hi) = (&pieces[lo].points, &pieces[hi].points);
3399                if (b - level).abs() < 1e-12 * scale {
3400                    below.push((lo.last().expect("nonempty").1, hi.last().expect("nonempty").1));
3401                }
3402                if (a - level).abs() < 1e-12 * scale {
3403                    above.push((lo[0].1, hi[0].1));
3404                }
3405            }
3406        }
3407        let tolerance = if engine.angular { 1e-9 * scale / level.max(1e-12) } else { 1e-9 * scale };
3408        // At the outer radius the material is the circle less the sweep's
3409        // spans (the symmetric difference with the whole circle above).
3410        if complement && (level - top).abs() < 1e-12 * scale {
3411            above = vec![(0.0, TAU)];
3412        }
3413        for (lo, hi) in symmetric_difference(&below, &above, engine.angular, tolerance) {
3414            let steps = 2;
3415            pieces.push(Piece {
3416                points: (0..=steps)
3417                    .map(|k| (level, lo + (hi - lo) * k as f64 / steps as f64))
3418                    .collect(),
3419                sigma: (0..=steps).map(|k| k as f64 / steps as f64).collect(),
3420                level_segment: true,
3421            });
3422        }
3423    }
3424
3425    if std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
3426        eprintln!("solid sweep: breaks {breaks:?}");
3427        for piece in &pieces {
3428            let a = piece.points[0];
3429            let b = *piece.points.last().expect("nonempty");
3430            eprintln!(
3431                "  piece {} ({:.9}, {:.9}) -> ({:.9}, {:.9}) n={}",
3432                if piece.level_segment { "LEVEL" } else { "edge " },
3433                a.0, a.1, b.0, b.1, piece.points.len()
3434            );
3435            if std::env::var("BREP_DEBUG_SOLID_SWEEP").as_deref() == Ok("2") {
3436                for p in piece.points.iter().take(6) {
3437                    eprintln!("      {:.12} {:.12}", p.0, p.1);
3438                }
3439            }
3440        }
3441    }
3442    // --- At a crest the walls have met: the top arc is no boundary of what stays.
3443    if let Some(level) = crest {
3444        pieces.retain(|piece| !(piece.level_segment && (piece.points[0].0 - level).abs() < 1e-9 * scale));
3445    }
3446    // --- Assemble loops and build the bodies.
3447    let loops = assemble_loops(&engine, pieces)?;
3448    // The material is one region round the axis, or it is not built here.
3449    if complement && loops.len() != 1 {
3450        return Ok(None);
3451    }
3452    let mut bodies = Vec::new();
3453    for pieces in loops {
3454        bodies.push(build_body(&engine, &pieces)?);
3455    }
3456    if crest.is_some() {
3457        let [kept] = bodies.as_slice() else {
3458            return Err(refuse("whole_level", "what stays below the crest is not one body".into()));
3459        };
3460        if kept_only {
3461            return Ok(Some(bodies));
3462        }
3463        return clip_less(clip, frame_base(&engine), kept).map(Some);
3464    }
3465    Ok(Some(bodies))
3466}
3467
3468/// Replace a screw loft's side surfaces and helical edges by quintic splines
3469/// through the exact screw and its first two derivatives. A cubic interpolant
3470/// through `segments + 1` sections misses a turn by h⁴; these by h⁶, which is
3471/// what lets a long fine thread be built with few spans. Sections, caps and
3472/// parameters are the loft's, so the trims stay as they are.
3473/// What the screw carry reads of its sweep: the screw's axis, the sweep's scale, and the order
3474/// of the lean carry.
3475struct ScrewAxis {
3476    origin: Vec3,
3477    ez: Vec3,
3478    scale: f64,
3479    order: usize,
3480    /// A profile drawn in a half-plane through the axis (`screw_profile_brep`): the half-plane's
3481    /// radial direction and the profile's heights along the axis, where a row's end sections lie
3482    /// (the level engine's sections lie square to the axis instead).
3483    meridian: Option<(Vec3, [f64; 2])>,
3484}
3485
3486impl ScrewAxis {
3487    fn of(engine: &Engine) -> ScrewAxis {
3488        ScrewAxis { origin: engine.clip.axis_origin, ez: engine.frame.ez, scale: engine.scale, order: lean_carry_order(engine), meridian: None }
3489    }
3490}
3491
3492/// The solid a closed profile sweeps when screwed about an axis it lies beside: the profile,
3493/// drawn in a plane through the axis, turned right-handed about `axis_direction` through `angle`
3494/// (radians, positive) while it rises `rise` along it per radian (a thread; `rise` 0 is the
3495/// revolution). The walls are the profile carried along the screw, lofted through its sections and
3496/// re-carried to high order (the threads' own construction); a long screw is built a few turns at a
3497/// time and stacked. Refused where the profile reaches the axis, leaves the plane through it, or
3498/// meets its own next turn (its height along the axis at least the rise of a turn) when the screw
3499/// turns more than once.
3500pub fn screw_profile_brep(profile: &[NurbsCurve], axis_origin: Vec3, axis_direction: Vec3, rise: f64, angle: f64) -> Result<BrepSolid, KernelRefusal> {
3501    let bad = |what: &'static str, message: &str| KernelRefusal::input(KernelStage::Collect, what, format!("screwProfile: {message}"));
3502    let ez = axis_direction.normalized().map_err(|_| bad("screw_axis", "the axis has no direction"))?;
3503    if !(angle.is_finite() && angle > 0.0 && rise.is_finite()) {
3504        return Err(bad("screw_motion", "the angle must be positive and the rise finite"));
3505    }
3506    if angle > 1e4 * TAU {
3507        return Err(bad("screw_motion", "more than ten thousand turns"));
3508    }
3509    if profile.is_empty() {
3510        return Err(bad("screw_profile", "no profile"));
3511    }
3512    if rise == 0.0 {
3513        return revolve_profile_brep(profile, axis_origin, ez, angle).map_err(|e| bad("screw_revolve", &e));
3514    }
3515    // A profile of one closed curve (a circle) is lofted as its two halves.
3516    let halves;
3517    let profile = if let [closed] = profile {
3518        let [t0, t1] = closed.domain().map_err(|e| bad("screw_profile", &e))?;
3519        let (a, b) = closed.split(0.5 * (t0 + t1)).map_err(|e| bad("screw_profile", &e))?;
3520        halves = [a, b];
3521        &halves[..]
3522    } else {
3523        profile
3524    };
3525    // The profile's reach: its distance from the axis, its height along it, its plane.
3526    let mut samples = Vec::new();
3527    for curve in profile {
3528        let [t0, t1] = curve.domain().map_err(|e| bad("screw_profile", &e))?;
3529        for k in 0..=64 {
3530            samples.push(curve.evaluate(t0 + (t1 - t0) * k as f64 / 64.0).map_err(|e| bad("screw_profile", &e))?);
3531        }
3532    }
3533    let local = |x: Vec3| {
3534        let d = x.sub(axis_origin);
3535        let h = d.dot(ez);
3536        (d.sub(ez.scale(h)), h)
3537    };
3538    // The scale is the profile's own: its farthest reach from the axis and its height, not
3539    // where along the axis its origin was given.
3540    let (mut rho_min, mut rho_max, mut h0, mut h1) = (f64::INFINITY, 0.0f64, f64::INFINITY, f64::NEG_INFINITY);
3541    for &x in &samples {
3542        let (radial, h) = local(x);
3543        rho_min = rho_min.min(radial.length());
3544        rho_max = rho_max.max(radial.length());
3545        h0 = h0.min(h);
3546        h1 = h1.max(h);
3547    }
3548    let scale = rho_max.max(h1 - h0).max(1e-300);
3549    let radial_dir = samples.iter().map(|&x| local(x).0).find(|radial| radial.length() > 1e-6 * scale).and_then(|radial| radial.normalized().ok());
3550    if !(rho_min > 1e-9 * scale) {
3551        return Err(bad("screw_profile_axis", "the profile reaches the screw's axis"));
3552    }
3553    let normal = ez.cross(radial_dir.ok_or_else(|| bad("screw_profile", "the profile has no extent"))?);
3554    if samples.iter().any(|&x| { let (radial, _) = local(x); radial.dot(normal).abs() > 1e-9 * scale || radial.dot(normal.cross(ez)) < 0.0 }) {
3555        return Err(bad("screw_profile_plane", "the profile does not lie in one half-plane through the axis"));
3556    }
3557    if angle > TAU * (1.0 + 1e-12) && (h1 - h0) >= TAU * rise.abs() * (1.0 - 1e-12) {
3558        return Err(bad("screw_turns_collide", "the profile meets its own next turn: it is at least as tall as the rise of one turn"));
3559    }
3560    let axis = ScrewAxis { origin: axis_origin, ez, scale, order: LEAN_CARRY_ORDER, meridian: Some((radial_dir.expect("checked above"), [h0, h1])) };
3561    let per_turn = if lean_walls_on() { LEAN_CARRY_PER_TURN } else { 48.0 };
3562    let rows = (angle / TAU / TURNS_PER_ROW).round().max(1.0) as usize;
3563    let span = angle / rows as f64;
3564    let sections = ((span / TAU * per_turn).ceil() as usize).max(8) + 1;
3565    let mut lofted = Vec::with_capacity(sections);
3566    for k in 0..sections {
3567        let turn = span * k as f64 / (sections - 1) as f64;
3568        let lift = ez.scale(rise * turn);
3569        let moved: Vec<NurbsCurve> = profile.iter().map(|curve| transform_curve(curve, |x| rotate(x, axis_origin, ez, turn).add(lift))).collect::<Result<_, _>>()?;
3570        lofted.push(moved);
3571    }
3572    // (A screw so steep that its sections barely leave their own planes, a lead angle past some
3573    // 84°, is refused by the loft's own test of each section's advance, by name.)
3574    let mut body = loft_profile_brep(&lofted)?;
3575    carry_along_screw(&mut body, &axis, rise, span, sections - 1)?;
3576    if rows > 1 {
3577        body = stack_screw_rows(&body, &axis, rise, span, sections - 1, rows)?;
3578    }
3579    if let Some(issue) = body.validate().first() {
3580        return Err(KernelRefusal::unsupported(KernelStage::Fragment, "screw_profile_invalid", format!("screwProfile: the screwed profile is not valid: {issue:?}")));
3581    }
3582    Ok(body)
3583}
3584
3585/// Whether the edge from `from` to `to` of a screw loft is carried along the screw (and then
3586/// whether it runs with it), or lies in a cap (`None`). A level section's carried edges rise the
3587/// whole height and its caps none; a meridian profile's caps can rise the whole height too, so
3588/// there a carried edge is the one whose end is its start carried through the span.
3589#[allow(clippy::too_many_arguments)]
3590fn carried_edge(axis: &ScrewAxis, c: f64, span: f64, from: Vec3, to: Vec3, rise: f64, height: f64, tolerance: f64) -> Option<bool> {
3591    if axis.meridian.is_some() {
3592        let carried = |a: Vec3, b: Vec3| rotate(a, axis.origin, axis.ez, span).add(axis.ez.scale(c * span)).sub(b).length() <= tolerance;
3593        return if carried(from, to) {
3594            Some(true)
3595        } else if carried(to, from) {
3596            Some(false)
3597        } else {
3598            None
3599        };
3600    }
3601    if (rise.abs() - height.abs()).abs() > tolerance.min(0.25 * height.abs()) {
3602        return None;
3603    }
3604    Some(rise * height > 0.0)
3605}
3606
3607fn carry_along_screw(body: &mut BrepSolid, axis: &ScrewAxis, c: f64, span: f64, segments: usize) -> Result<(), KernelRefusal> {
3608    if lean_walls_on() {
3609        return carry_along_screw_to_order(body, axis, c, span, segments, axis.order);
3610    }
3611    let origin = axis.origin;
3612    let ez = axis.ez;
3613    // The six Bézier points of each span collapse to three a span, C² at the joints.
3614    let carry = |start: Vec3| -> Vec<Vec3> {
3615        let h = span / segments as f64;
3616        let axial = ez.scale(start.sub(origin).dot(ez));
3617        let radial = start.sub(origin).sub(axial);
3618        let at = |k: usize| {
3619            let angle = h * k as f64;
3620            let r = radial.rotate_about(ez, angle);
3621            let value = origin.add(axial).add(r).add(ez.scale(c * angle));
3622            (value, ez.cross(r).add(ez.scale(c)), r.scale(-1.0))
3623        };
3624        let piece = |k: usize| {
3625            let ((f0, d0, a0), (f1, d1, a1)) = (at(k), at(k + 1));
3626            [
3627                f0,
3628                f0.add(d0.scale(h / 5.0)),
3629                f0.add(d0.scale(2.0 * h / 5.0)).add(a0.scale(h * h / 20.0)),
3630                f1.sub(d1.scale(2.0 * h / 5.0)).add(a1.scale(h * h / 20.0)),
3631                f1.sub(d1.scale(h / 5.0)),
3632                f1,
3633            ]
3634        };
3635        let mut points = Vec::with_capacity(3 * segments + 3);
3636        let first = piece(0);
3637        points.extend_from_slice(&first[..3]);
3638        for k in 0..segments - 1 {
3639            let (here, next) = (piece(k), piece(k + 1));
3640            points.push(here[3]);
3641            points.push(here[4].scale(2.0).sub(here[3]));
3642            points.push(next[2]);
3643        }
3644        let last = piece(segments - 1);
3645        points.extend_from_slice(&last[3..]);
3646        points
3647    };
3648    let knots = |lo: f64, hi: f64| -> Vec<f64> {
3649        let mut knots = vec![lo; 6];
3650        for k in 1..segments {
3651            knots.extend([lo + (hi - lo) * k as f64 / segments as f64; 3]);
3652        }
3653        knots.extend([hi; 6]);
3654        knots
3655    };
3656    let point = |p: &crate::Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
3657    let moved = |p: &crate::Vec4, angle: f64| -> Vec3 {
3658        rotate(point(p), origin, ez, angle).add(ez.scale(c * angle))
3659    };
3660    let tolerance = 1e-7 * axis.scale;
3661    for face in body.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
3662        let rows = &face.surface.control_points;
3663        if rows[0].len() != segments + 1 {
3664            continue; // a cap
3665        }
3666        // The loft's columns must already be this screw, from section to section.
3667        if rows.iter().any(|row| moved(&row[0], span).sub(point(&row[segments])).length() > tolerance) {
3668            return Err(refuse("screw_loft", "a lofted wall does not follow the screw".into()));
3669        }
3670        let lifted: Vec<Vec<crate::Vec4>> = rows
3671            .iter()
3672            .map(|row| {
3673                let w = row[0].w;
3674                carry(point(&row[0])).into_iter().map(|q| crate::Vec4::from_point(q, w)).collect()
3675            })
3676            .collect();
3677        let v = &face.surface.knots_v;
3678        let (lo, hi) = (v[0], *v.last().expect("knots"));
3679        face.surface = crate::NurbsSurface::new(face.surface.degree_u, 5, face.surface.knots_u.clone(), knots(lo, hi), lifted)
3680            .or_refuse(KernelStage::Fragment, "screw_surface")?;
3681    }
3682    let height = c * span;
3683    let points: rustc_hash::FxHashMap<u64, Vec3> = body.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
3684    for edge in &mut body.edges {
3685        let (from, to) = (points[&edge.start_vertex_id], points[&edge.end_vertex_id]);
3686        let rise = to.sub(from).dot(ez);
3687        // An edge in a cap rises nothing, a carried one the whole height: told apart
3688        // well inside the height itself, however short the clip against its radius.
3689        // A meridian profile's cap can rise the whole height too: there a carried edge is
3690        // the one whose end is its start carried the whole span.
3691        let Some(forward) = carried_edge(axis, c, span, from, to, rise, height, tolerance) else {
3692            continue; // lies in a cap
3693        };
3694        let domain = edge.curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
3695        let mut path = carry(if forward { from } else { to });
3696        if !forward {
3697            path.reverse();
3698        }
3699        edge.curve = NurbsCurve::new(5, knots(domain[0], domain[1]), path.into_iter().map(|q| crate::Vec4::from_point(q, 1.0)).collect())
3700            .or_refuse(KernelStage::Fragment, "screw_edge")?;
3701    }
3702    Ok(())
3703}
3704
3705/// `rows` copies of `row` along the screw, each the image of the last, sharing
3706/// the section edges and vertices between neighbours; only the first bottom cap
3707/// and the last top cap stay.
3708/// Knots of the carry of order `m` (degree 2m + 1, C^m) over [lo, hi] in
3709/// `segments` even spans.
3710fn carry_knots_of_order(lo: f64, hi: f64, segments: usize, m: usize) -> Vec<f64> {
3711    let degree = 2 * m + 1;
3712    let mut knots = vec![lo; degree + 1];
3713    for k in 1..segments {
3714        knots.extend(std::iter::repeat_n(lo + (hi - lo) * k as f64 / segments as f64, m + 1));
3715    }
3716    knots.extend(std::iter::repeat_n(hi, degree + 1));
3717    knots
3718}
3719
3720/// The polar form of the Bézier curve `b` at `ts` (de Casteljau with a
3721/// parameter of its own at each level).
3722fn bezier_blossom(b: &[Vec3], ts: &[f64]) -> Vec3 {
3723    let mut p = b.to_vec();
3724    for (level, &t) in ts.iter().enumerate() {
3725        for i in 0..p.len() - 1 - level {
3726            p[i] = p[i].scale(1.0 - t).add(p[i + 1].scale(t));
3727        }
3728    }
3729    p[0]
3730}
3731
3732/// Control points of the C^m spline of degree 2m + 1 that matches a path and
3733/// its first m derivatives at `segments + 1` even steps of [0, h·segments]:
3734/// `jet(k)` is the path's derivatives 0..=m at step k (per unit parameter).
3735/// Each span is the Hermite interpolant of its two ends' jets; the spline's
3736/// points are the spans' polar forms at its knots (`carry_knots_of_order`), which
3737/// adjacent spans share where they meet to order m.
3738fn carry_points_of_order(jet: impl Fn(usize) -> Vec<Vec3>, h: f64, segments: usize, m: usize) -> Vec<Vec3> {
3739    let degree = 2 * m + 1;
3740    let binomial = |n: usize, k: usize| -> f64 { (0..k).fold(1.0, |acc, i| acc * (n - i) as f64 / (i + 1) as f64) };
3741    // (n - k)!/n!, the factor from a k-th derivative to a k-th difference.
3742    let falling = |k: usize| -> f64 { (0..k).fold(1.0, |acc, i| acc / (degree - i) as f64) };
3743    let bezier = |k: usize| -> Vec<Vec3> {
3744        let (start, end) = (jet(k), jet(k + 1));
3745        let mut b = vec![Vec3::new(0.0, 0.0, 0.0); degree + 1];
3746        for j in 0..=m {
3747            let scale = h.powi(j as i32) * falling(j);
3748            // Δ^j b_0 = start_j·scale, so b_j = Σ_i C(j, i) Δ^i b_0.
3749            let mut front = start[j].scale(scale);
3750            for i in 0..j {
3751                // Δ^j b_0 = Σ_i (-1)^(j-i) C(j, i) b_i
3752                let sign = if (j - i) % 2 == 0 { 1.0 } else { -1.0 };
3753                front = front.sub(b[i].scale(sign * binomial(j, i)));
3754            }
3755            b[j] = front;
3756            // ∇^j b_n = Σ_i (-1)^i C(j, i) b_(n-i) = end_j·scale.
3757            let mut back = end[j].scale(scale);
3758            for i in 0..j {
3759                let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
3760                back = back.sub(b[degree - i].scale(sign * binomial(j, i)));
3761            }
3762            b[degree - j] = back.scale(if j % 2 == 0 { 1.0 } else { -1.0 });
3763        }
3764        b
3765    };
3766    let spans: Vec<Vec<Vec3>> = (0..segments).map(bezier).collect();
3767    // Knots in units of a span.
3768    let knots = carry_knots_of_order(0.0, segments as f64, segments, m);
3769    let count = knots.len() - degree - 1;
3770    (0..count)
3771        .map(|i| {
3772            let args = &knots[i + 1..=i + degree];
3773            let k = (args[0].floor() as usize).min(segments - 1);
3774            let local: Vec<f64> = args.iter().map(|t| t - k as f64).collect();
3775            bezier_blossom(&spans[k], &local)
3776        })
3777        .collect()
3778}
3779
3780/// `carry_along_screw` to order `m`: each wall's columns and each carried edge
3781/// as the C^m spline of degree 2m + 1 through the exact screw and m of its
3782/// derivatives at `segments + 1` turns.
3783fn carry_along_screw_to_order(body: &mut BrepSolid, axis: &ScrewAxis, c: f64, span: f64, segments: usize, m: usize) -> Result<(), KernelRefusal> {
3784    let origin = axis.origin;
3785    let ez = axis.ez;
3786    let degree = 2 * m + 1;
3787    let h = span / segments as f64;
3788    let carry = |start: Vec3| -> Vec<Vec3> {
3789        let axial = ez.scale(start.sub(origin).dot(ez));
3790        let radial = start.sub(origin).sub(axial);
3791        let jet = |k: usize| -> Vec<Vec3> {
3792            let angle = h * k as f64;
3793            let mut out = Vec::with_capacity(m + 1);
3794            out.push(origin.add(axial).add(radial.rotate_about(ez, angle)).add(ez.scale(c * angle)));
3795            for j in 1..=m {
3796                // The j-th derivative of the turned radius is the radius turned a further j quarter turns.
3797                let turned = radial.rotate_about(ez, angle + j as f64 * std::f64::consts::FRAC_PI_2);
3798                out.push(if j == 1 { turned.add(ez.scale(c)) } else { turned });
3799            }
3800            out
3801        };
3802        carry_points_of_order(jet, h, segments, m)
3803    };
3804    let point = |p: &crate::Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
3805    let moved = |p: &crate::Vec4, angle: f64| -> Vec3 { rotate(point(p), origin, ez, angle).add(ez.scale(c * angle)) };
3806    let tolerance = 1e-7 * axis.scale;
3807    for face in body.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
3808        let rows = &face.surface.control_points;
3809        if rows[0].len() != segments + 1 {
3810            continue; // a cap
3811        }
3812        if rows.iter().any(|row| moved(&row[0], span).sub(point(&row[segments])).length() > tolerance) {
3813            return Err(refuse("screw_loft", "a lofted wall does not follow the screw".into()));
3814        }
3815        let lifted: Vec<Vec<crate::Vec4>> = rows
3816            .iter()
3817            .map(|row| {
3818                let w = row[0].w;
3819                carry(point(&row[0])).into_iter().map(|q| crate::Vec4::from_point(q, w)).collect()
3820            })
3821            .collect();
3822        let v = &face.surface.knots_v;
3823        let (lo, hi) = (v[0], *v.last().expect("knots"));
3824        face.surface = crate::NurbsSurface::new(face.surface.degree_u, degree, face.surface.knots_u.clone(), carry_knots_of_order(lo, hi, segments, m), lifted)
3825            .or_refuse(KernelStage::Fragment, "screw_surface")?;
3826    }
3827    let height = c * span;
3828    let points: rustc_hash::FxHashMap<u64, Vec3> = body.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
3829    for edge in &mut body.edges {
3830        let (from, to) = (points[&edge.start_vertex_id], points[&edge.end_vertex_id]);
3831        let rise = to.sub(from).dot(ez);
3832        let Some(forward) = carried_edge(axis, c, span, from, to, rise, height, tolerance) else {
3833            continue; // lies in a cap
3834        };
3835        let domain = edge.curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
3836        let mut path = carry(if forward { from } else { to });
3837        if !forward {
3838            path.reverse();
3839        }
3840        edge.curve = NurbsCurve::new(
3841            degree,
3842            carry_knots_of_order(domain[0], domain[1], segments, m),
3843            path.into_iter().map(|q| crate::Vec4::from_point(q, 1.0)).collect(),
3844        )
3845        .or_refuse(KernelStage::Fragment, "screw_edge")?;
3846    }
3847    Ok(())
3848}
3849
3850/// Control points a carried wall has along the screw, in `segments` spans.
3851fn carried_columns(axis: &ScrewAxis, segments: usize) -> usize {
3852    if lean_walls_on() {
3853        (axis.order + 1) * (segments + 1)
3854    } else {
3855        3 * segments + 3
3856    }
3857}
3858
3859fn stack_screw_rows(
3860    row: &BrepSolid,
3861    axis: &ScrewAxis,
3862    c: f64,
3863    span: f64,
3864    segments: usize,
3865    rows: usize,
3866) -> Result<BrepSolid, KernelRefusal> {
3867    let origin = axis.origin;
3868    let ez = axis.ez;
3869    let moved = |x: Vec3, copy: usize| -> Vec3 {
3870        let angle = span * copy as f64;
3871        rotate(x, origin, ez, angle).add(ez.scale(c * angle))
3872    };
3873    let tolerance = 1e-7 * axis.scale;
3874    let height = |x: Vec3| x.sub(origin).dot(ez);
3875    let points: rustc_hash::FxHashMap<u64, Vec3> = row.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
3876    let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
3877    for vertex in &row.vertices {
3878        low = low.min(height(vertex.point));
3879        high = high.max(height(vertex.point));
3880    }
3881    let (bottom, top) = if c * span > 0.0 { (low, high) } else { (high, low) };
3882    // Where a row's end sections lie: at its lowest and highest level, or (a meridian profile)
3883    // in the half-plane it starts in and the one it ends in, within the profile's heights there.
3884    let on_end = |x: Vec3, level: f64| -> bool {
3885        match axis.meridian {
3886            None => (height(x) - level).abs() <= tolerance,
3887            Some((radial, [h0, h1])) => {
3888                let (turn, rise) = if level == bottom { (0.0, 0.0) } else { (span, c * span) };
3889                let r = radial.rotate_about(ez, turn);
3890                let across = ez.cross(r);
3891                let d = x.sub(origin);
3892                let h = height(x) - rise;
3893                d.dot(across).abs() <= tolerance && d.dot(r) > 0.0 && h >= h0 - tolerance && h <= h1 + tolerance
3894            }
3895        }
3896    };
3897    let at = |id: u64, level: f64| on_end(points[&id], level);
3898    let in_level = |edge: &crate::topology::EdgeRecord, level: f64| at(edge.start_vertex_id, level) && at(edge.end_vertex_id, level);
3899    // Each bottom vertex and edge of a copy is a top one of the copy before.
3900    let mut vertex_below: rustc_hash::FxHashMap<u64, u64> = Default::default();
3901    for vertex in row.vertices.iter().filter(|vertex| at(vertex.id, bottom)) {
3902        let up = moved(vertex.point, 1);
3903        let below = row.vertices.iter().find(|other| at(other.id, top) && other.point.sub(up).length() <= tolerance);
3904        let Some(below) = below else { return Err(refuse("screw_rows", "a row's section does not meet the next".into())) };
3905        vertex_below.insert(vertex.id, below.id);
3906    }
3907    let mut edge_below: rustc_hash::FxHashMap<u64, u64> = Default::default();
3908    for edge in row.edges.iter().filter(|edge| in_level(edge, bottom)) {
3909        let ends = (vertex_below[&edge.start_vertex_id], vertex_below[&edge.end_vertex_id]);
3910        let below = row.edges.iter().find(|other| in_level(other, top) && (other.start_vertex_id, other.end_vertex_id) == ends);
3911        let Some(below) = below else { return Err(refuse("screw_rows", "a row's section edge does not meet the next".into())) };
3912        edge_below.insert(edge.id, below.id);
3913    }
3914    let face_ids = row.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| {
3915        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))))
3916    });
3917    let stride = row
3918        .vertices
3919        .iter()
3920        .map(|v| v.id)
3921        .chain(row.edges.iter().map(|e| e.id))
3922        .chain(face_ids)
3923        .max()
3924        .unwrap_or(0)
3925        + 1;
3926    let vertex_id = |id: u64, copy: usize| match vertex_below.get(&id) {
3927        Some(&below) if copy > 0 => below + stride * (copy as u64 - 1),
3928        _ => id + stride * copy as u64,
3929    };
3930    let edge_id = |id: u64, copy: usize| match edge_below.get(&id) {
3931        Some(&below) if copy > 0 => below + stride * (copy as u64 - 1),
3932        _ => id + stride * copy as u64,
3933    };
3934    let is_cap = |face: &crate::FaceRecord| face.surface.control_points[0].len() != carried_columns(axis, segments);
3935    let cap_level = |face: &crate::FaceRecord, level: f64| {
3936        face.loops.iter().flat_map(|l| &l.coedges).all(|coedge| {
3937            row.edges.iter().find(|edge| edge.id == coedge.edge_id).is_some_and(|edge| in_level(edge, level))
3938        })
3939    };
3940    let mut stacked = row.clone();
3941    stacked.mass_properties_cache = Default::default();
3942    stacked.vertices.clear();
3943    stacked.edges.clear();
3944    for shell in &mut stacked.shells {
3945        shell.faces.clear();
3946    }
3947    for copy in 0..rows {
3948        for vertex in &row.vertices {
3949            if copy == 0 || !vertex_below.contains_key(&vertex.id) {
3950                stacked.vertices.push(crate::topology::VertexRecord { id: vertex_id(vertex.id, copy), point: moved(vertex.point, copy) });
3951            }
3952        }
3953        for edge in &row.edges {
3954            if copy == 0 || !edge_below.contains_key(&edge.id) {
3955                stacked.edges.push(crate::topology::EdgeRecord {
3956                    id: edge_id(edge.id, copy),
3957                    curve: transform_curve(&edge.curve, |x| moved(x, copy))?,
3958                    t0: edge.t0,
3959                    t1: edge.t1,
3960                    start_vertex_id: vertex_id(edge.start_vertex_id, copy),
3961                    end_vertex_id: vertex_id(edge.end_vertex_id, copy),
3962                    degenerate: edge.degenerate,
3963                    name: edge.name.clone(),
3964                });
3965            }
3966        }
3967        for (target, shell) in stacked.shells.iter_mut().zip(&row.shells) {
3968            for face in &shell.faces {
3969                if is_cap(face) && !((copy == 0 && cap_level(face, bottom)) || (copy + 1 == rows && cap_level(face, top))) {
3970                    continue;
3971                }
3972                let control_points = face
3973                    .surface
3974                    .control_points
3975                    .iter()
3976                    .map(|line| {
3977                        line.iter()
3978                            .map(|p| {
3979                                let w = p.w;
3980                                crate::Vec4::from_point(moved(Vec3::new(p.x / w, p.y / w, p.z / w), copy), w)
3981                            })
3982                            .collect()
3983                    })
3984                    .collect();
3985                let surface = crate::NurbsSurface::new(
3986                    face.surface.degree_u,
3987                    face.surface.degree_v,
3988                    face.surface.knots_u.clone(),
3989                    face.surface.knots_v.clone(),
3990                    control_points,
3991                )
3992                .or_refuse(KernelStage::Fragment, "screw_rows")?;
3993                let mut copied = face.clone();
3994                copied.surface = surface;
3995                copied.id += stride * copy as u64;
3996                for loop_record in &mut copied.loops {
3997                    loop_record.id += stride * copy as u64;
3998                    for coedge in &mut loop_record.coedges {
3999                        coedge.id += stride * copy as u64;
4000                        coedge.edge_id = edge_id(coedge.edge_id, copy);
4001                    }
4002                }
4003                target.faces.push(copied);
4004            }
4005        }
4006    }
4007    let issues = stacked.validate();
4008    if issues.iter().any(|issue| issue.severity == "error") {
4009        return Err(refuse("screw_rows", format!("the stacked thread is invalid: {issues:?}")));
4010    }
4011    Ok(stacked)
4012}
4013
4014/// Where the clip's solid starts, on its axis.
4015fn frame_base(engine: &Engine) -> Vec3 {
4016    engine.frame.world([0.0, 0.0, engine.clip.axial[0]])
4017}
4018
4019/// The whole clip cylinder with `kept` taken out of it.
4020fn clip_less(clip: &SweepClip, base: Vec3, kept: &BrepSolid) -> Result<Vec<BrepSolid>, KernelRefusal> {
4021    let direction = clip.axis_direction.normalized().or_refuse(KernelStage::Collect, "clip_axis")?;
4022    let cylinder = crate::make_cylinder_brep(base, direction, clip.radius[1], clip.axial[1] - clip.axial[0])
4023        .or_refuse(KernelStage::Fragment, "clip_cylinder")?;
4024    if thread_rows_on() {
4025        if let Some(direct) = clip_less_direct(&cylinder, base, direction, kept)? {
4026            return Ok(vec![direct]);
4027        }
4028    }
4029    let r = crate::boolean_operation(&cylinder, kept, crate::BooleanOperation::Subtract, &Default::default())?;
4030    Ok(vec![r])
4031}
4032
4033/// `cylinder` with `kept` taken out, where `kept` runs from cap to cap inside
4034/// the wall: nothing crosses, so the result is written down: `kept`'s end loops
4035/// become holes in the caps and its sides turn inside out. `None` when the
4036/// bodies are not that shape; the caller takes the boolean then.
4037fn clip_less_direct(
4038    cylinder: &BrepSolid,
4039    base: Vec3,
4040    direction: Vec3,
4041    kept: &BrepSolid,
4042) -> Result<Option<BrepSolid>, KernelRefusal> {
4043    if kept.shells.len() != 1 || cylinder.shells.len() != 1 {
4044        return Ok(None);
4045    }
4046    let mut stride = 0;
4047    for shell in &cylinder.shells {
4048        for face in &shell.faces {
4049            stride = stride.max(face.id);
4050            for loop_record in &face.loops {
4051                stride = stride.max(loop_record.id);
4052                stride = loop_record.coedges.iter().fold(stride, |m, c| m.max(c.id));
4053            }
4054        }
4055    }
4056    stride = cylinder.vertices.iter().fold(stride, |m, v| m.max(v.id));
4057    stride = cylinder.edges.iter().fold(stride, |m, e| m.max(e.id)) + 1;
4058    let corners = |surface: &crate::NurbsSurface| -> Result<([f64; 4], [Vec3; 3]), String> {
4059        let (u0, u1) = (surface.knots_u[0], *surface.knots_u.last().ok_or("knots")?);
4060        let (v0, v1) = (surface.knots_v[0], *surface.knots_v.last().ok_or("knots")?);
4061        Ok(([u0, u1, v0, v1], [surface.evaluate(u0, v0)?, surface.evaluate(u1, v0)?, surface.evaluate(u0, v1)?]))
4062    };
4063    let mut result = cylinder.clone();
4064    result.mass_properties_cache = Default::default();
4065    result.genus = 1;
4066    result.vertices.extend(kept.vertices.iter().map(|v| crate::topology::VertexRecord { id: v.id + stride, point: v.point }));
4067    for edge in &kept.edges {
4068        let mut edge = edge.clone();
4069        edge.id += stride;
4070        edge.start_vertex_id += stride;
4071        edge.end_vertex_id += stride;
4072        result.edges.push(edge);
4073    }
4074    let mut holes = 0;
4075    let turned = |loop_record: &crate::topology::LoopRecord| -> Result<crate::topology::LoopRecord, KernelRefusal> {
4076        let mut coedges = Vec::with_capacity(loop_record.coedges.len());
4077        for coedge in loop_record.coedges.iter().rev() {
4078            coedges.push(crate::topology::CoedgeRecord {
4079                id: coedge.id + stride,
4080                edge_id: coedge.edge_id + stride,
4081                forward: !coedge.forward,
4082                pcurve: coedge.pcurve.reversed().or_refuse(KernelStage::Fragment, "clip_less_pcurve")?,
4083            });
4084        }
4085        Ok(crate::topology::LoopRecord { id: loop_record.id + stride, coedges })
4086    };
4087    for face in &kept.shells[0].faces {
4088        let mut loops = Vec::with_capacity(face.loops.len());
4089        for loop_record in &face.loops {
4090            loops.push(turned(loop_record)?);
4091        }
4092        if !face.surface.is_affine().unwrap_or(false) {
4093            result.shells[0].faces.push(crate::FaceRecord {
4094                id: face.id + stride,
4095                surface: face.surface.clone(),
4096                same_sense: !face.same_sense,
4097                loops,
4098                name: face.name.clone(),
4099            });
4100            continue;
4101        }
4102        // An end: its loops are holes in the cap at its height, read in that cap's chart.
4103        let (from_box, from) = corners(&face.surface).or_refuse(KernelStage::Fragment, "clip_less_chart")?;
4104        let height = from[0].sub(base).dot(direction);
4105        let mut caps = result.shells[0].faces.iter_mut().filter(|cap| {
4106            cap.surface.is_affine().unwrap_or(false)
4107                && 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()))
4108        });
4109        let (Some(cap), None) = (caps.next(), caps.next()) else { return Ok(None) };
4110        let (to_box, to) = corners(&cap.surface).or_refuse(KernelStage::Fragment, "clip_less_chart")?;
4111        let (eu, ev) = (to[1].sub(to[0]), to[2].sub(to[0]));
4112        if eu.dot(ev).abs() > 1e-9 * eu.length() * ev.length() {
4113            return Ok(None);
4114        }
4115        let chart = |p: Vec3| {
4116            let d = p.sub(to[0]);
4117            [
4118                to_box[0] + (to_box[1] - to_box[0]) * d.dot(eu) / eu.dot(eu),
4119                to_box[2] + (to_box[3] - to_box[2]) * d.dot(ev) / ev.dot(ev),
4120            ]
4121        };
4122        let source = |a: f64, b: f64| from[0].add(from[1].sub(from[0]).scale(a)).add(from[2].sub(from[0]).scale(b));
4123        let (origin, across, up) = (chart(source(0.0, 0.0)), chart(source(1.0, 0.0)), chart(source(0.0, 1.0)));
4124        for loop_record in &mut loops {
4125            for coedge in &mut loop_record.coedges {
4126                let curve = &coedge.pcurve;
4127                let control_points = curve
4128                    .control_points
4129                    .iter()
4130                    .map(|p| {
4131                        let a = (p.x / p.w - from_box[0]) / (from_box[1] - from_box[0]);
4132                        let b = (p.y / p.w - from_box[2]) / (from_box[3] - from_box[2]);
4133                        let x = origin[0] + a * (across[0] - origin[0]) + b * (up[0] - origin[0]);
4134                        let y = origin[1] + a * (across[1] - origin[1]) + b * (up[1] - origin[1]);
4135                        crate::Vec4 { x: x * p.w, y: y * p.w, z: p.z, w: p.w }
4136                    })
4137                    .collect();
4138                coedge.pcurve = NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
4139                    .or_refuse(KernelStage::Fragment, "clip_less_pcurve")?;
4140            }
4141        }
4142        cap.loops.extend(loops);
4143        holes += 1;
4144    }
4145    if holes != 2 || result.validate().iter().any(|issue| issue.severity == "error") {
4146        return Ok(None);
4147    }
4148    Ok(Some(result))
4149}
4150
4151/// The level above which a screw's sweep covers every angle, up to the clip,
4152/// when the material between its turns narrows to nothing there; `None` when
4153/// the sweep leaves something at the clip's edge.
4154fn crest_level(engine: &Engine) -> Result<Option<f64>, KernelRefusal> {
4155    let whole = |level: f64| -> Result<bool, KernelRefusal> {
4156        match engine.intervals_at(level) {
4157            Ok(_) => Ok(false),
4158            Err(error) if error.message.contains(WHOLE_LEVEL) => Ok(true),
4159            Err(error) => Err(error),
4160        }
4161    };
4162    let [l0, l1] = engine.clip.radius;
4163    let scan = 64;
4164    let level_at = |k: usize| l0 + (l1 - l0) * k as f64 / scan as f64;
4165    if !whole(l1)? {
4166        return Ok(None);
4167    }
4168    let mut first = scan;
4169    while first > 0 && whole(level_at(first - 1))? {
4170        first -= 1;
4171    }
4172    if first == 0 {
4173        return Ok(None);
4174    }
4175    let (mut below, mut above) = (level_at(first - 1), level_at(first));
4176    for _ in 0..60 {
4177        let middle = 0.5 * (below + above);
4178        if whole(middle)? {
4179            above = middle;
4180        } else {
4181            below = middle;
4182        }
4183    }
4184    // The material must narrow to nothing there, not stop at some width. Near
4185    // the end the walls have already crossed unseen (the oracle stops seeing the
4186    // gap a little past the crest), so the crest is where the gap, measured
4187    // well below, extrapolates to zero.
4188    let gap = |level: f64| -> Result<f64, KernelRefusal> {
4189        Ok(TAU - engine.intervals_at(level)?.iter().map(|interval| interval.hi - interval.lo).sum::<f64>())
4190    };
4191    let step = 4e-5 * (l1 - l0);
4192    let (x0, x1, x2) = (below - 3.0 * step, below - 2.0 * step, below - step);
4193    let (g0, g1, g2) = (gap(x0)?, gap(x1)?, gap(x2)?);
4194    if !(g2 > 0.0 && g1 > g2 && g0 > g1) || g2 > 16.0 * (g1 - g2) {
4195        return Ok(None);
4196    }
4197    let curve = |x: f64| {
4198        g0 * (x - x1) * (x - x2) / ((x0 - x1) * (x0 - x2))
4199            + g1 * (x - x0) * (x - x2) / ((x1 - x0) * (x1 - x2))
4200            + g2 * (x - x0) * (x - x1) / ((x2 - x0) * (x2 - x1))
4201    };
4202    let (mut lo, mut hi) = (x2, below + step);
4203    if curve(hi) > 0.0 {
4204        return Ok(None);
4205    }
4206    for _ in 0..80 {
4207        let middle = 0.5 * (lo + hi);
4208        if curve(middle) > 0.0 {
4209            lo = middle;
4210        } else {
4211            hi = middle;
4212        }
4213    }
4214    Ok(Some(0.5 * (lo + hi)))
4215}
4216
4217/// The one critical level of any source strictly inside (a, b), when no
4218/// other critical lies within twice the snap's reach of it (so the snap would
4219/// name it and no other).
4220fn lone_critical_inside(engine: &Engine, a: f64, b: f64, scale: f64) -> Option<f64> {
4221    let mut inside = engine.critical.iter().flatten().map(|critical| critical.0).filter(|&level| level > a && level < b);
4222    let c = inside.next()?;
4223    if engine.critical.iter().flatten().any(|critical| critical.0 != c && (critical.0 - c).abs() < 2e-5 * scale) {
4224        return None;
4225    }
4226    if inside.any(|level| level != c) {
4227        return None;
4228    }
4229    Some(c)
4230}
4231
4232fn find_events(
4233    engine: &Engine,
4234    a: f64,
4235    sa: &[Interval],
4236    b: f64,
4237    sb: &[Interval],
4238    breaks: &mut Vec<f64>,
4239    depth: usize,
4240) -> Result<(), KernelRefusal> {
4241    if compatible(engine, sa, sb) {
4242        return Ok(());
4243    }
4244    if depth <= 2 && std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
4245        let summary = |s: &[Interval]| -> Vec<(usize, usize, f64, f64)> {
4246            s.iter().map(|x| (x.lo_source, x.hi_source, (x.lo * 1e4).round() / 1e4, (x.hi * 1e4).round() / 1e4)).collect()
4247        };
4248        eprintln!("  find_events depth {depth} [{a:.9}, {b:.9}] {:?}\n      -> {:?} counters {:?}", summary(sa), summary(sb), engine.counters.get());
4249    }
4250    if b - a < 1e-13 * engine.scale || depth > 60 {
4251        breaks.push(0.5 * (a + b));
4252        return Ok(());
4253    }
4254    let m = 0.5 * (a + b);
4255    let sm = engine.intervals_at(m)?;
4256    // Both halves stay incompatible only where the reading flickers; follow the
4257    // half that changes first and let the other be found from the scan above.
4258    if !compatible(engine, sa, &sm) && !compatible(engine, &sm, sb) && depth > 8 {
4259        breaks.push(m);
4260        return Ok(());
4261    }
4262    find_events(engine, a, sa, m, &sm, breaks, depth + 1)?;
4263    find_events(engine, m, &sm, b, sb, breaks, depth + 1)
4264}
4265
4266/// The candidate of `source` at `level` nearest `guess` (or its critical point
4267/// at that level); `fallback` when the source has none there.
4268fn end_value(engine: &Engine, source: usize, level: f64, guess: f64, fallback: f64) -> f64 {
4269    let mut candidates = Vec::new();
4270    engine.source_candidates(source, level, &mut candidates);
4271    let mut options: Vec<f64> = candidates.iter().map(|c| c.0).collect();
4272    for critical in &engine.critical[source] {
4273        if (critical.0 - level).abs() < 1e-7 * engine.scale {
4274            options.push(critical.1);
4275        }
4276    }
4277    let mut best = fallback;
4278    let mut distance = f64::INFINITY;
4279    for option in options {
4280        let d = engine.o_difference(option, guess).abs();
4281        if d < distance {
4282            distance = d;
4283            best = guess + engine.o_difference(option, guess);
4284        }
4285    }
4286    best
4287}
4288
4289/// Sample a band (a, b) of constant structure; return its end pieces and the
4290/// intervals at its bottom and top.
4291#[allow(clippy::type_complexity)]
4292fn sample_band(
4293    engine: &Engine,
4294    a: f64,
4295    b: f64,
4296    mid: &[Interval],
4297    fold_ends: &[f64],
4298) -> Result<(Vec<Piece>, Vec<(f64, f64)>, Vec<(f64, f64)>), KernelRefusal> {
4299    let count = mid.len();
4300    let n = 24usize;
4301    // Next to a fold the extremum Newton flickers; keep every sample at least
4302    // this far from a fold end (the end itself reads the fold's critical point).
4303    let near_fold = fold_ends.iter().any(|f| (f - a).abs() < 1e-12 * engine.scale || (f - b).abs() < 1e-12 * engine.scale);
4304    let n_cap = if near_fold {
4305        let keep = (1e-4 * engine.scale).min((b - a) / 50.0);
4306        // smallest σ step: (b − a)(1 − cos(π/n))/2 ≥ keep
4307        let ratio = (1.0 - 2.0 * keep / (b - a)).clamp(-1.0, 1.0);
4308        ((PI / ratio.acos()).floor() as usize).max(8)
4309    } else {
4310        192
4311    };
4312    let mut n = n.min(n_cap);
4313    loop {
4314        let sigma: Vec<f64> = (0..=n).map(|k| k as f64 / n as f64).collect();
4315        let level_at = |s: f64| a + (b - a) * (1.0 - (PI * s).cos()) / 2.0;
4316        // Track every interval from the middle sample outward.
4317        let mut lo = vec![vec![f64::NAN; n + 1]; count];
4318        let mut hi = vec![vec![f64::NAN; n + 1]; count];
4319        let mut lo_src = vec![vec![0usize; n + 1]; count];
4320        let mut hi_src = vec![vec![0usize; n + 1]; count];
4321        let mid_index = n / 2;
4322        let mid_intervals = engine.intervals_at(level_at(sigma[mid_index]))?;
4323        if mid_intervals.len() != count {
4324            return Err(refuse("band_structure", format!("the structure changes inside the band {a}..{b}")));
4325        }
4326        for (i, interval) in mid_intervals.iter().enumerate() {
4327            lo[i][mid_index] = interval.lo;
4328            hi[i][mid_index] = interval.hi;
4329            lo_src[i][mid_index] = interval.lo_source;
4330            hi_src[i][mid_index] = interval.hi_source;
4331        }
4332        for direction in [-1i64, 1] {
4333            let mut k = mid_index as i64 + direction;
4334            while k > 0 && (k as usize) < n {
4335                let ku = k as usize;
4336                let previous = (ku as i64 - direction) as usize;
4337                let intervals = engine.intervals_at(level_at(sigma[ku]))?;
4338                if intervals.len() != count {
4339                    return Err(refuse("band_structure", format!("the structure changes inside the band {a}..{b}")));
4340                }
4341                for i in 0..count {
4342                    let centre = 0.5 * (lo[i][previous] + hi[i][previous]);
4343                    let nearest = intervals
4344                        .iter()
4345                        .min_by(|x, y| {
4346                            let dx = engine.o_difference(0.5 * (x.lo + x.hi), centre).abs();
4347                            let dy = engine.o_difference(0.5 * (y.lo + y.hi), centre).abs();
4348                            dx.total_cmp(&dy)
4349                        })
4350                        .expect("nonempty");
4351                    let shift = engine.o_difference(nearest.lo, lo[i][previous]) - (nearest.lo - lo[i][previous]);
4352                    lo[i][ku] = nearest.lo + shift;
4353                    hi[i][ku] = nearest.hi + shift;
4354                    lo_src[i][ku] = nearest.lo_source;
4355                    hi_src[i][ku] = nearest.hi_source;
4356                }
4357                k += direction;
4358            }
4359        }
4360        // Ends: the same source's value at exactly the band's end levels,
4361        // nearest the linear extrapolation of the two nearest samples.
4362        for i in 0..count {
4363            for (end, inner, inner2, inner3, level) in [(0usize, 1usize, 2usize, 3usize, a), (n, n - 1, n - 2, n - 3, b)] {
4364                // A quadratic in the sample index through the three nearest samples.
4365                // The levels cluster as σ² at the ends, so a regular end is quadratic
4366                // in σ and a √ end (a tip) linear: this is exact for both, where
4367                // `2v₁ − v₂` misses the first by the slope times a sample spacing. A
4368                // source whose domain ends at this level has no candidate there, so
4369                // the estimate IS the end value (1e-3 on the bar swung on its edge).
4370                let near = |values: &Vec<f64>| 2.0 * values[inner] - values[inner2];
4371                let quadratic = |values: &Vec<f64>| 3.0 * values[inner] - 3.0 * values[inner2] + values[inner3];
4372                lo[i][end] = end_value(engine, lo_src[i][inner], level, near(&lo[i]), quadratic(&lo[i]));
4373                hi[i][end] = end_value(engine, hi_src[i][inner], level, near(&hi[i]), quadratic(&hi[i]));
4374            }
4375        }
4376        // Accuracy: compare the fitted ends at the σ mid-points with exact values.
4377        let mut worst = 0.0f64;
4378        let mut worst_at = (0usize, 0usize, 0usize, 0.0f64, 0.0f64);
4379        for i in 0..count {
4380            for (side, values) in [&lo[i], &hi[i]].into_iter().enumerate() {
4381                let points: Vec<Vec3> = (0..=n)
4382                    .map(|k| reduced_to_plane(engine, level_at(sigma[k]), values[k]))
4383                    .collect();
4384                let curve = fit_piece(&points)?;
4385                let parameters = chord_parameters(&points);
4386                // The end spans too: an end value is read differently from the samples.
4387                for k in (1..n - 1).step_by((n / 8).max(1)).chain([0, n - 1]) {
4388                    let s = 0.5 * (sigma[k] + sigma[k + 1]);
4389                    let level = level_at(s);
4390                    let intervals = engine.intervals_at(level)?;
4391                    let guess = 0.5 * (values[k] + values[k + 1]);
4392                    let exact = intervals
4393                        .iter()
4394                        .flat_map(|x| [x.lo, x.hi])
4395                        .map(|o| guess + engine.o_difference(o, guess))
4396                        .min_by(|x, y| (x - guess).abs().total_cmp(&(y - guess).abs()))
4397                        .unwrap_or(guess);
4398                    let truth = reduced_to_plane(engine, level, exact);
4399                    let bracket = (parameters[k.saturating_sub(1)], parameters[(k + 2).min(n)]);
4400                    let off = distance_in_bracket(&curve, truth, bracket.0, bracket.1)?;
4401                    if off > worst {
4402                        worst = off;
4403                        worst_at = (i, side, k, level, exact);
4404                    }
4405                }
4406            }
4407        }
4408        if std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok() {
4409            eprintln!("  band {a:.9}..{b:.9} n {n} worst {worst:.3e} at {worst_at:?}");
4410        }
4411        if n >= n_cap && worst > 1e-6 * engine.scale {
4412            return Err(refuse(
4413                "fit_tolerance",
4414                format!(
4415                    "a boundary piece of the band {a}..{b} stays {worst:.3e} off its envelope at {n} samples \
4416                     (interval {}, {}, sample {}, level {}, o {})",
4417                    worst_at.0,
4418                    if worst_at.1 == 0 { "lo" } else { "hi" },
4419                    worst_at.2,
4420                    worst_at.3,
4421                    worst_at.4
4422                ),
4423            ));
4424        }
4425        if worst <= 1e-8 * engine.scale || n >= n_cap {
4426            let mut pieces = Vec::new();
4427            for i in 0..count {
4428                for values in [&lo[i], &hi[i]] {
4429                    pieces.push(Piece {
4430                        points: (0..=n).map(|k| (level_at(sigma[k]), values[k])).collect(),
4431                        sigma: sigma.clone(),
4432                        level_segment: false,
4433                    });
4434                }
4435            }
4436            let bottoms = (0..count).map(|i| (lo[i][0], hi[i][0])).collect();
4437            let tops = (0..count).map(|i| (lo[i][n], hi[i][n])).collect();
4438            return Ok((pieces, bottoms, tops));
4439        }
4440        n = (n * 2).min(n_cap);
4441    }
4442}
4443
4444/// Chord-length parameters for interpolating `points`, normalised to [0, 1].
4445/// Not the sampling's own `σ`: the levels cluster at both ends of a band, which
4446/// near a tip is what keeps a √ end smooth, but at a regular end it makes the
4447/// curve's speed vanish there, and an interpolant through a zero-speed end
4448/// cusps (the screw groove's wall folded where it met the closing arc).
4449fn chord_parameters(points: &[Vec3]) -> Vec<f64> {
4450    let mut parameters = vec![0.0; points.len()];
4451    for k in 1..points.len() {
4452        parameters[k] = parameters[k - 1] + points[k].sub(points[k - 1]).length();
4453    }
4454    let total = parameters[points.len() - 1].max(1e-300);
4455    for parameter in &mut parameters {
4456        *parameter /= total;
4457    }
4458    let last = points.len() - 1;
4459    parameters[last] = 1.0;
4460    parameters
4461}
4462
4463fn fit_piece(points: &[Vec3]) -> Result<NurbsCurve, KernelRefusal> {
4464    interpolate_curve(points, 3, &chord_parameters(points)).or_refuse(KernelStage::Fragment, "piece_fit")
4465}
4466
4467/// A boundary piece in few spans: the least-squares quintic through its exact
4468/// samples `points` (`reduced`, the same in reduced coordinates), its ends
4469/// held, in the fewest spans whose curve stands within the larger of
4470/// `LEAN_FIT_TOLERANCE` of the scale and the cubic `fit_piece`'s own worst
4471/// miss of the exact envelope at every mid-point between samples (the points
4472/// `sample_band` judges the cubic at, here every one): never further from the
4473/// envelope than the cubic it replaces. Else that cubic. The knots sit at the
4474/// chord parameters of evenly spaced samples (which gather where the samples
4475/// do, by the piece's ends, its critical levels), with a ramp of them by each
4476/// end, where it turns fastest.
4477fn lean_fit_piece(engine: &Engine, reduced: &[(f64, f64)], points: &[Vec3]) -> Result<NurbsCurve, KernelRefusal> {
4478    const DEGREE: usize = 5;
4479    let last = points.len() - 1;
4480    let parameters = chord_parameters(points);
4481    let cubic = fit_piece(points)?;
4482    // The exact envelope between each two samples, at the mid-point of their
4483    // σ (the levels run a + (b − a)(1 − cos πσ)/2 along a band's piece).
4484    let (a, b) = (reduced[0].0, reduced[last].0);
4485    if (b - a).abs() <= 1e-12 * engine.scale {
4486        return Ok(cubic);
4487    }
4488    let sigma = |level: f64| (1.0 - 2.0 * (level - a) / (b - a)).clamp(-1.0, 1.0).acos() / PI;
4489    let mut truths = Vec::with_capacity(last);
4490    for k in 0..last {
4491        let s = 0.5 * (sigma(reduced[k].0) + sigma(reduced[k + 1].0));
4492        let level = a + (b - a) * (1.0 - (PI * s).cos()) / 2.0;
4493        let guess = 0.5 * (reduced[k].1 + reduced[k + 1].1);
4494        let exact = engine
4495            .intervals_at(level)?
4496            .iter()
4497            .flat_map(|x| [x.lo, x.hi])
4498            .map(|o| guess + engine.o_difference(o, guess))
4499            .min_by(|x, y| (x - guess).abs().total_cmp(&(y - guess).abs()));
4500        let Some(exact) = exact else { return Ok(cubic) };
4501        truths.push(reduced_to_plane(engine, level, exact));
4502    }
4503    let miss = |curve: &NurbsCurve| -> Result<f64, KernelRefusal> {
4504        let mut worst = 0.0f64;
4505        for (k, truth) in truths.iter().enumerate() {
4506            let bracket = (parameters[k.saturating_sub(1)], parameters[(k + 2).min(last)]);
4507            worst = worst.max(distance_in_bracket(curve, *truth, bracket.0, bracket.1)?);
4508        }
4509        Ok(worst)
4510    };
4511    let tolerance = (LEAN_FIT_TOLERANCE * engine.scale).max(miss(&cubic)?);
4512    let debug = std::env::var("BREP_DEBUG_SOLID_SWEEP").is_ok();
4513    for even in [4usize, 6, 8, 12, 16, 24, 32, 48, 64] {
4514        let mut at: Vec<usize> = (1..even).map(|k| (k * last + even / 2) / even).collect();
4515        for ramp in [1usize, 2, 4] {
4516            if 4 * ramp < last {
4517                at.extend([ramp, last - ramp]);
4518            }
4519        }
4520        at.sort_unstable();
4521        at.dedup();
4522        let spans = at.len() + 1;
4523        let count = spans + DEGREE;
4524        if 3 * count > 2 * points.len() {
4525            break;
4526        }
4527        let mut knots = vec![0.0; DEGREE + 1];
4528        knots.extend(at.iter().map(|&k| parameters[k]));
4529        knots.extend([1.0; DEGREE + 1]);
4530        if (DEGREE..DEGREE + spans).any(|k| knots[k + 1] <= knots[k]) {
4531            continue;
4532        }
4533        let Some(controls) = least_squares_controls(points, &parameters, &knots, DEGREE, count) else { continue };
4534        let Ok(curve) = NurbsCurve::new(DEGREE, knots, controls.iter().map(|p| crate::Vec4::from_point(*p, 1.0)).collect()) else {
4535            continue;
4536        };
4537        let worst = miss(&curve)?;
4538        if debug {
4539            eprintln!("  lean fit {} samples {spans} spans: worst mid-point {worst:.3e} (tolerance {tolerance:.3e})", points.len());
4540        }
4541        if worst <= tolerance {
4542            return Ok(curve);
4543        }
4544    }
4545    Ok(cubic)
4546}
4547
4548/// The B-spline basis of `degree` on `knots` at `t`: (first index, values).
4549fn bspline_basis(knots: &[f64], degree: usize, count: usize, t: f64) -> (usize, Vec<f64>) {
4550    let mut span = degree;
4551    while span + 1 < count && knots[span + 1] <= t {
4552        span += 1;
4553    }
4554    let mut values = vec![0.0; degree + 1];
4555    values[0] = 1.0;
4556    let (mut left, mut right) = (vec![0.0; degree + 1], vec![0.0; degree + 1]);
4557    for j in 1..=degree {
4558        left[j] = t - knots[span + 1 - j];
4559        right[j] = knots[span + j] - t;
4560        let mut saved = 0.0;
4561        for r in 0..j {
4562            let temp = values[r] / (right[r + 1] + left[j - r]);
4563            values[r] = saved + right[r + 1] * temp;
4564            saved = left[j - r] * temp;
4565        }
4566        values[j] = saved;
4567    }
4568    (span - degree, values)
4569}
4570
4571/// Control points of the B-spline on `knots` nearest `points` at `parameters`
4572/// in least squares, its first and last points held at the first and last
4573/// sample.
4574fn least_squares_controls(points: &[Vec3], parameters: &[f64], knots: &[f64], degree: usize, count: usize) -> Option<Vec<Vec3>> {
4575    let (first, last) = (points[0], points[points.len() - 1]);
4576    let unknowns = count - 2;
4577    let mut normal = vec![vec![0.0; unknowns]; unknowns];
4578    let mut rhs = vec![[0.0; 3]; unknowns];
4579    for (point, &t) in points.iter().zip(parameters).skip(1).take(points.len() - 2) {
4580        let (start, values) = bspline_basis(knots, degree, count, t);
4581        // What the held ends contribute here moves to the right side.
4582        let mut target = *point;
4583        for (offset, value) in values.iter().enumerate() {
4584            let index = start + offset;
4585            if index == 0 {
4586                target = target.sub(first.scale(*value));
4587            } else if index == count - 1 {
4588                target = target.sub(last.scale(*value));
4589            }
4590        }
4591        for (a, va) in values.iter().enumerate() {
4592            let row = start + a;
4593            if row == 0 || row == count - 1 {
4594                continue;
4595            }
4596            for (b, vb) in values.iter().enumerate() {
4597                let column = start + b;
4598                if column == 0 || column == count - 1 {
4599                    continue;
4600                }
4601                normal[row - 1][column - 1] += va * vb;
4602            }
4603            rhs[row - 1][0] += va * target.x;
4604            rhs[row - 1][1] += va * target.y;
4605            rhs[row - 1][2] += va * target.z;
4606        }
4607    }
4608    // Gaussian elimination with partial pivoting (symmetric positive definite, small).
4609    for column in 0..unknowns {
4610        let pivot = (column..unknowns).max_by(|a, b| normal[*a][column].abs().total_cmp(&normal[*b][column].abs()))?;
4611        if normal[pivot][column].abs() < 1e-300 {
4612            return None;
4613        }
4614        normal.swap(column, pivot);
4615        rhs.swap(column, pivot);
4616        for row in column + 1..unknowns {
4617            let factor = normal[row][column] / normal[column][column];
4618            if factor == 0.0 {
4619                continue;
4620            }
4621            for k in column..unknowns {
4622                normal[row][k] -= factor * normal[column][k];
4623            }
4624            for axis in 0..3 {
4625                rhs[row][axis] -= factor * rhs[column][axis];
4626            }
4627        }
4628    }
4629    let mut solved = vec![[0.0; 3]; unknowns];
4630    for row in (0..unknowns).rev() {
4631        for axis in 0..3 {
4632            let mut value = rhs[row][axis];
4633            for k in row + 1..unknowns {
4634                value -= normal[row][k] * solved[k][axis];
4635            }
4636            solved[row][axis] = value / normal[row][row];
4637        }
4638    }
4639    let mut controls = Vec::with_capacity(count);
4640    controls.push(first);
4641    controls.extend(solved.iter().map(|p| Vec3::new(p[0], p[1], p[2])));
4642    controls.push(last);
4643    controls.iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).then_some(controls)
4644}
4645
4646/// Distance from `target` to `curve` over the parameter bracket [a, b].
4647fn distance_in_bracket(curve: &NurbsCurve, target: Vec3, a: f64, b: f64) -> Result<f64, KernelRefusal> {
4648    let distance = |t: f64| -> Result<f64, KernelRefusal> {
4649        Ok(curve.evaluate(t).or_refuse(KernelStage::Fragment, "piece_eval")?.sub(target).length())
4650    };
4651    let ratio = 0.618_033_988_749_894_9;
4652    let (mut lo, mut hi) = (a, b);
4653    for _ in 0..80 {
4654        let c = hi - ratio * (hi - lo);
4655        let d = lo + ratio * (hi - lo);
4656        if distance(c)? < distance(d)? {
4657            hi = d;
4658        } else {
4659            lo = c;
4660        }
4661    }
4662    distance(0.5 * (lo + hi))
4663}
4664
4665/// `below Δ above` as intervals of `o` (both lists at one level).
4666fn symmetric_difference(below: &[(f64, f64)], above: &[(f64, f64)], angular: bool, tolerance: f64) -> Vec<(f64, f64)> {
4667    // Normalise to [base, base + 2π) for angular values, splitting wrapped ones.
4668    let normalise = |list: &[(f64, f64)]| -> Vec<(f64, f64)> {
4669        let mut out = Vec::new();
4670        for &(lo, hi) in list {
4671            if angular {
4672                let shift = lo.rem_euclid(TAU) - lo;
4673                let (lo, hi) = (lo + shift, hi + shift);
4674                if hi > TAU {
4675                    out.push((lo, TAU));
4676                    out.push((0.0, hi - TAU));
4677                } else {
4678                    out.push((lo, hi));
4679                }
4680            } else {
4681                out.push((lo, hi));
4682            }
4683        }
4684        out
4685    };
4686    let a = normalise(below);
4687    let b = normalise(above);
4688    let mut cuts: Vec<f64> = a.iter().chain(&b).flat_map(|&(lo, hi)| [lo, hi]).collect();
4689    cuts.sort_by(|x, y| x.total_cmp(y));
4690    cuts.dedup_by(|y, x| (*y - *x).abs() < tolerance);
4691    let inside = |list: &Vec<(f64, f64)>, x: f64| list.iter().any(|&(lo, hi)| x > lo && x < hi);
4692    let mut out: Vec<(f64, f64)> = Vec::new();
4693    for w in cuts.windows(2) {
4694        let m = 0.5 * (w[0] + w[1]);
4695        if inside(&a, m) != inside(&b, m) && w[1] - w[0] > tolerance {
4696            if let Some(last) = out.last_mut() {
4697                if (last.1 - w[0]).abs() < tolerance {
4698                    last.1 = w[1];
4699                    continue;
4700                }
4701            }
4702            out.push((w[0], w[1]));
4703        }
4704    }
4705    if angular && out.len() > 1 {
4706        let first = out[0];
4707        let last = *out.last().expect("nonempty");
4708        if first.0.abs() < tolerance && (last.1 - TAU).abs() < tolerance {
4709            out.pop();
4710            out[0] = (last.0 - TAU, first.1);
4711        }
4712    }
4713    out
4714}
4715
4716/// A reduced point on the section plane the body is built from.
4717fn reduced_to_plane(engine: &Engine, level: f64, o: f64) -> Vec3 {
4718    let clip = engine.clip;
4719    match engine.class {
4720        Class::Screw(c) => {
4721            let z = clip.axial[0];
4722            let alpha = o + z / c;
4723            engine.frame.world([level * alpha.cos(), level * alpha.sin(), z])
4724        }
4725        Class::Turn => {
4726            let theta = clip.angle.map(|a| a[0]).unwrap_or(0.0);
4727            engine.frame.world([level * theta.cos(), level * theta.sin(), o])
4728        }
4729        Class::Planar => engine.frame.world([level * o.cos(), level * o.sin(), clip.axial[0]]),
4730    }
4731}
4732
4733/// Join pieces end to end into closed loops (in the section plane).
4734fn assemble_loops(engine: &Engine, pieces: Vec<Piece>) -> Result<Vec<Vec<Piece>>, KernelRefusal> {
4735    let tolerance = 1e-6 * engine.scale;
4736    let ends: Vec<(Vec3, Vec3)> = pieces
4737        .iter()
4738        .map(|piece| {
4739            let first = piece.points[0];
4740            let last = *piece.points.last().expect("nonempty");
4741            (reduced_to_plane(engine, first.0, first.1), reduced_to_plane(engine, last.0, last.1))
4742        })
4743        .collect();
4744    let mut used = vec![false; pieces.len()];
4745    let mut orders: Vec<Vec<(usize, bool)>> = Vec::new();
4746    for start in 0..pieces.len() {
4747        if used[start] {
4748            continue;
4749        }
4750        used[start] = true;
4751        let mut order = vec![(start, false)];
4752        let origin = ends[start].0;
4753        let mut cursor = ends[start].1;
4754        let mut guard = 0;
4755        while cursor.sub(origin).length() > tolerance {
4756            guard += 1;
4757            if guard > pieces.len() {
4758                return Err(refuse("loop_open", "the section's boundary does not close".into()));
4759            }
4760            let mut next = None;
4761            let mut best = tolerance;
4762            for k in 0..pieces.len() {
4763                if used[k] {
4764                    continue;
4765                }
4766                for (reversed, end) in [(false, ends[k].0), (true, ends[k].1)] {
4767                    let d = end.sub(cursor).length();
4768                    if d < best {
4769                        best = d;
4770                        next = Some((k, reversed));
4771                    }
4772                }
4773            }
4774            let Some((k, reversed)) = next else {
4775                return Err(refuse(
4776                    "loop_open",
4777                    format!("the section's boundary does not close (a gap at {:?})", cursor),
4778                ));
4779            };
4780            used[k] = true;
4781            order.push((k, reversed));
4782            cursor = if reversed { ends[k].0 } else { ends[k].1 };
4783        }
4784        orders.push(order);
4785    }
4786    if orders.len() > 1 {
4787        // A loop inside another is a hole; not built here.
4788        let polygon = |order: &Vec<(usize, bool)>| -> Vec<Vec3> {
4789            order
4790                .iter()
4791                .flat_map(|&(k, _)| pieces[k].points.iter().map(|p| reduced_to_plane(engine, p.0, p.1)))
4792                .collect()
4793        };
4794        let polygons: Vec<Vec<Vec3>> = orders.iter().map(polygon).collect();
4795        for (i, a) in polygons.iter().enumerate() {
4796            for (j, b) in polygons.iter().enumerate() {
4797                if i != j && point_in_polygon(engine, a[0], b) {
4798                    return Err(refuse("section_hole", "the section has a hole, which is not built here".into()));
4799                }
4800            }
4801        }
4802    }
4803    let mut slots: Vec<Option<Piece>> = pieces.into_iter().map(Some).collect();
4804    Ok(orders
4805        .into_iter()
4806        .map(|order| {
4807            order
4808                .into_iter()
4809                .map(|(k, reversed)| {
4810                    let mut piece = slots[k].take().expect("each piece once");
4811                    if reversed {
4812                        piece.points.reverse();
4813                        piece.sigma = piece.sigma.iter().rev().map(|s| 1.0 - s).collect();
4814                    }
4815                    piece
4816                })
4817                .collect()
4818        })
4819        .collect())
4820}
4821
4822pub fn point_in_polygon(engine: &Engine, p: Vec3, polygon: &[Vec3]) -> bool {
4823    let local = |x: Vec3| -> [f64; 2] {
4824        let l = engine.frame.local(x);
4825        match engine.class {
4826            Class::Turn => [l[0].hypot(l[1]), l[2]],
4827            _ => [l[0], l[1]],
4828        }
4829    };
4830    let q = local(p);
4831    let mut inside = false;
4832    for k in 0..polygon.len() {
4833        let a = local(polygon[k]);
4834        let b = local(polygon[(k + 1) % polygon.len()]);
4835        if (a[1] > q[1]) != (b[1] > q[1]) {
4836            let x = a[0] + (q[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);
4837            if x > q[0] {
4838                inside = !inside;
4839            }
4840        }
4841    }
4842    inside
4843}
4844
4845/// Fit each piece and build the body for one loop.
4846fn build_body(engine: &Engine, pieces: &[Piece]) -> Result<BrepSolid, KernelRefusal> {
4847    let clip = engine.clip;
4848    let mut profile: Vec<NurbsCurve> = Vec::new();
4849    // Snap shared ends so consecutive curves meet exactly.
4850    let count = pieces.len();
4851    let mut start_points: Vec<Vec3> = pieces
4852        .iter()
4853        .map(|p| reduced_to_plane(engine, p.points[0].0, p.points[0].1))
4854        .collect();
4855    // A level segment is built exactly from its own ends, so the piece after
4856    // it starts where it ends.
4857    for (index, piece) in pieces.iter().enumerate() {
4858        if piece.level_segment && engine.class != Class::Turn {
4859            let (level, o1) = *piece.points.last().expect("nonempty");
4860            start_points[(index + 1) % count] = reduced_to_plane(engine, level, o1);
4861        }
4862    }
4863    for (index, piece) in pieces.iter().enumerate() {
4864        let start = start_points[index];
4865        let end = start_points[(index + 1) % count];
4866        if piece.level_segment {
4867            let (level, o0) = piece.points[0];
4868            let o1 = piece.points.last().expect("nonempty").1;
4869            let curve = match engine.class {
4870                Class::Turn => make_line(start, end),
4871                Class::Screw(c) => {
4872                    let shift = clip.axial[0] / c;
4873                    level_arc(engine, level, o0 + shift, o1 + shift)
4874                }
4875                Class::Planar => level_arc(engine, level, o0, o1),
4876            }
4877            .or_refuse(KernelStage::Fragment, "level_segment")?;
4878            profile.push(curve);
4879            continue;
4880        }
4881        let mut points: Vec<Vec3> = piece
4882            .points
4883            .iter()
4884            .map(|p| reduced_to_plane(engine, p.0, p.1))
4885            .collect();
4886        points[0] = start;
4887        let last = points.len() - 1;
4888        points[last] = end;
4889        profile.push(if lean_walls_on() && matches!(engine.class, Class::Screw(_)) {
4890            lean_fit_piece(engine, &piece.points, &points)?
4891        } else {
4892            fit_piece(&points)?
4893        });
4894    }
4895    match engine.class {
4896        Class::Screw(c) => {
4897            let span = (clip.axial[1] - clip.axial[0]) / c; // radians of screw
4898            // Over a crest the walls are re-carried below to high order, so 12 a turn is enough.
4899            // A bar's walls are carried to high order too: a cubic through 64
4900            // sections a turn stands r·h⁴/384 off the screw (1e-6 at a groove's
4901            // floor), the quintic through 48 below 1e-9.
4902            let carried = engine.crest_gap || engine.bar.is_some() || screw_carry_on();
4903            let per_turn = if engine.crest_gap {
4904                12.0
4905            } else if carried && lean_walls_on() {
4906                LEAN_CARRY_PER_TURN
4907            } else if carried {
4908                48.0
4909            } else {
4910                64.0
4911            };
4912            // Every turn is the screw image of the first: build one and stack
4913            // copies, so no surface or edge runs the thread's whole length.
4914            let rows = if carried && thread_rows_on() { (span.abs() / TAU / TURNS_PER_ROW).round().max(1.0) as usize } else { 1 };
4915            let span = span / rows as f64;
4916            let sections = ((span.abs() / TAU * per_turn).ceil() as usize).max(8) + 1;
4917            let mut lofted = Vec::with_capacity(sections);
4918            for k in 0..sections {
4919                let angle = span * k as f64 / (sections - 1) as f64;
4920                let lift = engine.frame.ez.scale(c * angle);
4921                let moved: Vec<NurbsCurve> = profile
4922                    .iter()
4923                    .map(|curve| transform_curve(curve, |x| rotate(x, clip.axis_origin, engine.frame.ez, angle).add(lift)))
4924                    .collect::<Result<_, _>>()?;
4925                lofted.push(moved);
4926            }
4927            // Carried, every level is the section turned (its pieces disjoint,
4928            // the engine's intervals), so the loft's self-intersection scan finds
4929            // nothing the carry keeps (`BREP_SWEEP_SCREW_LOFT_UNSCANNED`, on unless =0).
4930            let mut body = if carried && screw_loft_unscanned_on() && section_is_simple(&profile, engine.frame.ez, engine.scale) {
4931                crate::loft_topology::loft_profile_brep_unscanned(&lofted)?
4932            } else {
4933                loft_profile_brep(&lofted)?
4934            };
4935            if carried {
4936                carry_along_screw(&mut body, &ScrewAxis::of(engine), c, span, sections - 1)?;
4937            }
4938            if rows > 1 {
4939                body = stack_screw_rows(&body, &ScrewAxis::of(engine), c, span, sections - 1, rows)?;
4940            }
4941            Ok(body)
4942        }
4943        Class::Turn => {
4944            let angle = clip.angle.map(|a| a[1] - a[0]).unwrap_or(TAU);
4945            revolve_profile_brep(&profile, clip.axis_origin, engine.frame.ez, angle)
4946                .or_refuse(KernelStage::Fragment, "revolve")
4947        }
4948        Class::Planar => extrude_profile_brep(&profile, engine.frame.ez, clip.axial[1] - clip.axial[0]),
4949    }
4950}
4951
4952fn level_arc(engine: &Engine, level: f64, a0: f64, a1: f64) -> Result<NurbsCurve, String> {
4953    let centre = engine.frame.world([0.0, 0.0, match engine.class {
4954        Class::Screw(_) | Class::Planar => engine.clip.axial[0],
4955        Class::Turn => 0.0,
4956    }]);
4957    let (start, end) = if a1 >= a0 { (a0, a1) } else { (a1, a0) };
4958    let arc = make_arc(centre, engine.frame.ex, engine.frame.ey, level, start, end)?;
4959    if a1 >= a0 {
4960        Ok(arc)
4961    } else {
4962        arc.reversed()
4963    }
4964}
4965
4966fn transform_curve(curve: &NurbsCurve, map: impl Fn(Vec3) -> Vec3) -> Result<NurbsCurve, KernelRefusal> {
4967    let control_points = curve
4968        .control_points
4969        .iter()
4970        .map(|p| {
4971            let w = p.w;
4972            let x = map(Vec3::new(p.x / w, p.y / w, p.z / w));
4973            crate::Vec4 { x: x.x * w, y: x.y * w, z: x.z * w, w }
4974        })
4975        .collect();
4976    NurbsCurve::new(curve.degree, curve.knots.clone(), control_points).or_refuse(KernelStage::Fragment, "curve_new")
4977}
4978
4979/// Refuse a screw or turn whose first or last position reaches the clip.
4980fn check_ends_clear(engine: &Engine) -> Result<(), KernelRefusal> {
4981    let clip = engine.clip;
4982    // Tool boundary samples at its own place (clip frame).
4983    let mut samples: Vec<[f64; 3]> = Vec::new();
4984    for (index, source) in engine.sources.iter().enumerate() {
4985        if let Some(grid) = &engine.grids[index] {
4986            for i in 0..grid.nu {
4987                for j in 0..grid.nv {
4988                    let (u, v) = Engine::grid_param(grid, i, j);
4989                    samples.push(engine.frame.local(engine.source_point(*source, u, v)));
4990                }
4991            }
4992        }
4993    }
4994    let margin = 1e-6 * engine.scale;
4995    for t in [engine.motion.from, engine.motion.to] {
4996        for p in &samples {
4997            let x = engine.frame.local(engine.motion_apply(t, engine.frame.world(*p)));
4998            let level = x[0].hypot(x[1]);
4999            if level > clip.radius[1] + margin || level < clip.radius[0] - margin {
5000                continue;
5001            }
5002            if x[2] < clip.axial[0] - margin || x[2] > clip.axial[1] + margin {
5003                continue;
5004            }
5005            if let Some([a0, a1]) = clip.angle {
5006                let angle = x[1].atan2(x[0]);
5007                let mid = 0.5 * (a0 + a1);
5008                let rel = wrap_pi(angle - mid);
5009                if rel.abs() > 0.5 * (a1 - a0) + 1e-9 {
5010                    continue;
5011                }
5012            }
5013            return Err(refuse(
5014                "ends_reach_clip",
5015                format!(
5016                    "the tool reaches the clip region at the motion's {} (t = {t}); the sweep is \
5017                     not invariant there, so the region would be wrong",
5018                    if t == engine.motion.from { "start" } else { "end" }
5019                ),
5020            ));
5021        }
5022    }
5023    Ok(())
5024}
5025
5026
5027
5028/// `body` within `clip`'s region (its wedge between its radii and heights),
5029/// for comparing two answers on what the caller keeps of them.
5030fn clip_region(body: &BrepSolid, clip: &SweepClip) -> Option<BrepSolid> {
5031    let ez = clip.axis_direction.normalized().ok()?;
5032    let ex = clip.reference.sub(ez.scale(clip.reference.dot(ez))).normalized().ok()?;
5033    let ey = ez.cross(ex);
5034    let wedge = clip.angle?;
5035    let ex_w = ex.scale(wedge[0].cos()).add(ey.scale(wedge[0].sin()));
5036    let at = |rho: f64, z: f64| clip.axis_origin.add(ez.scale(z)).add(ex_w.scale(rho));
5037    let ([r0, r1], [z0, z1]) = (clip.radius, clip.axial);
5038    let corners = [at(r0, z0), at(r1, z0), at(r1, z1), at(r0, z1)];
5039    let profile: Vec<NurbsCurve> = (0..4).map(|k| crate::make_line(corners[k], corners[(k + 1) % 4]).ok()).collect::<Option<_>>()?;
5040    let region = crate::revolve_profile_brep(&profile, clip.axis_origin, ez, wedge[1] - wedge[0]).ok()?;
5041    crate::boolean_operation(body, &region, crate::BooleanOperation::Intersect, &crate::BooleanOptions::default()).ok()
5042}
5043