Skip to main content

brep_construction/construction/sweep_topology/
sweep.rs

1use super::*;
2use super::path::{stationary_limit, PathSide, StationaryFault};
3pub use super::stations::{
4    StationBudget, StationParam, SweepStationReport, SWEEP_DEFAULT_TOLERANCE, SWEEP_MAX_STATIONS,
5    SWEEP_REFINEMENT_ROUNDS,
6};
7
8/// Sweep a CLOSED PLANAR profile loop along a path curve (§3.3/§5.7),
9/// TRANSPLANTING the profile onto the path — see [`SectionPlacement`] for the
10/// other reading, and for why the choice changes the solid.
11///
12/// Reuses the loft builder rather than a bespoke swept surface: the path is
13/// sampled at `STATIONS` uniform stations, a rotation-minimizing frame is
14/// propagated along it (double-reflection RMF, Wang et al. 2008 — the frame
15/// does NOT spin at inflections the way raw Frenet does), a rigidly
16/// transformed copy of the profile is placed at each station (identical
17/// degree/knots/weights, only the control points moved — which guarantees
18/// loft's per-section compatibility), and the stations are lofted through
19/// to produce the tube plus planar end caps.
20///
21/// Guards return a clear `Err` on an open/non-planar profile, a degenerate
22/// path tangent, or a loft failure. A path that bends TIGHTER than the section
23/// reaches is refused by name before the loft (`ρκ ≥ 1`, §4c of
24/// `sweep_sections_through_samples`); it used to be out of scope and the
25/// caller's problem, and what the caller got instead was a wall that passed
26/// through itself.
27pub fn sweep_profile_along_path(
28    profile: &[NurbsCurve],
29    path: &NurbsCurve,
30    name: Option<&str>,
31) -> Result<BrepSolid, KernelRefusal> {
32    // 32 stations is the original fixed sampling — golden parity pins the
33    // emitted geometry to it — and it stays the count for every path whose
34    // tangent turns through at most a full turn. A path that turns further
35    // (a coil) gets the helix builder's density; see [`path_turning_stations`].
36    sweep_profile_along_path_stations(
37        profile,
38        path,
39        name,
40        path_turning_stations(path),
41        0.0,
42        None,
43        SectionPlacement::Transplant,
44        SWEEP_DEFAULT_TOLERANCE,
45        false, // This solid-only API does not return station diagnostics.
46    )
47    .map(|swept| swept.solid)
48}
49
50/// Twisted path sweep (§5.7): identical to [`sweep_profile_along_path`], but
51/// the profile additionally ROTATES about the path tangent, linearly in ARC
52/// LENGTH, from 0 at the sweep start to `twist_angle` radians (right-handed
53/// about the tangent) at the end.  The arc-length fraction comes from the
54/// sampled station polyline, not the raw path parameter, so a non-uniformly
55/// parameterized path still twists uniformly in space.
56///
57/// STATION LAW: 16 stations per quarter turn of twist, floored at the path
58/// sweep's 32 and capped at 1024 (the loft's dense interpolation solve is
59/// O(stations³) per control column — the same cap the helix uses).  At
60/// 16/quarter-turn the inter-station twist step is Δφ ≈ 5.6°, so the cubic
61/// v-interpolation error on a profile point circling at radius r is
62/// ≈ r·Δφ⁴/384 ≈ 2.4·10⁻¹⁰·r — far below any geometric tolerance.  The cap
63/// holds that density up to 16 full turns (|twist| = 32π = 1024/16 quarter
64/// turns); a larger twist would silently alias under the cap, so it is
65/// REJECTED with an honest error instead.  Everything else the path sweep
66/// documents (profile validity, the tight-bend refusal) applies unchanged, and
67/// the tight-bend guard measures the TWISTED section's reach because it reads
68/// the axes the sections were actually placed on; twisting about the profile's
69/// own centroid adds no new radial extent of its own.
70pub fn sweep_profile_twisted(
71    profile: &[NurbsCurve],
72    path: &NurbsCurve,
73    twist_angle: f64,
74    name: Option<&str>,
75) -> Result<BrepSolid, KernelRefusal> {
76    use std::f64::consts::{FRAC_PI_2, TAU};
77
78    if !twist_angle.is_finite() {
79        return Err(KernelRefusal::input(
80            KernelStage::Collect,
81            "twist_finite",
82            "sweep_profile_twisted: twist angle must be finite",
83        ));
84    }
85    // 16 turns is where the 1024-station cap meets 16 stations/quarter-turn;
86    // beyond it the cap would degrade the twist sampling density silently.
87    const MAX_TURNS: f64 = 16.0;
88    if twist_angle.abs() > MAX_TURNS * TAU {
89        return Err(KernelRefusal::unsupported(
90            KernelStage::Collect,
91            "twist_cap",
92            format!(
93            "sweep_profile_twisted: twist of {:.3} turns exceeds the {MAX_TURNS}-turn \
94             limit the 1024-station cap can resolve at 16 stations per quarter turn; \
95             split the sweep or reduce the twist",
96            twist_angle.abs() / TAU
97            ),
98        ));
99    }
100    let quarter_turns = (twist_angle.abs() / FRAC_PI_2).ceil() as usize;
101    let stations = (quarter_turns * 16).clamp(32, 1024).max(path_turning_stations(path));
102    sweep_profile_along_path_stations(
103        profile,
104        path,
105        name,
106        stations,
107        twist_angle,
108        None,
109        SectionPlacement::Transplant,
110        SWEEP_DEFAULT_TOLERANCE,
111        true,
112    )
113    .map(|swept| swept.solid)
114    .map_err(|error| error.with_message(|error| format!("sweep_profile_twisted: {error}")))
115}
116
117/// Twisted path sweep with a SCALING LAW: [`sweep_profile_twisted`], with the
118/// section also scaled about its anchor origin (the profile's centroid, which
119/// the sweep lands on the path) linearly in the same sampled arc-length
120/// fraction as the twist, from 1 at the start to `end_scale` at the end.
121///
122/// So a square drawn at the foot of a straight path, swept with `twist_angle`
123/// and `end_scale`, is the column whose section at fraction `f` of the way is
124/// that square scaled by `1 + (end_scale − 1)·f` and turned by `twist_angle·f`:
125/// its corners run along conical spirals and each wall is the twisted RULED
126/// surface its side sweeps. Like every station sweep the wall is lofted through
127/// sampled sections, at TWICE the twisted builder's station density (32 per
128/// quarter turn, floored at 64, so at most 8 turns under the 1024 cap): the
129/// tapering column of the brep-bench case (half a turn, a third the size at
130/// the top) read 1.2e-7 relative in volume at 32 stations and holds 1e-7 with
131/// margin at 64, the Δφ⁴ law of the cubic interpolation.
132///
133/// With `end_scale == 1.0` it places the same sections [`sweep_profile_twisted`]
134/// does (each axis multiplied by exactly 1). A non-positive
135/// or non-finite scale is refused, and so is every twist the twisted sweep
136/// refuses.
137pub fn sweep_profile_twisted_scaled(
138    profile: &[NurbsCurve],
139    path: &NurbsCurve,
140    twist_angle: f64,
141    end_scale: f64,
142    name: Option<&str>,
143) -> Result<BrepSolid, KernelRefusal> {
144    use std::f64::consts::{FRAC_PI_2, TAU};
145
146    if !twist_angle.is_finite() {
147        return Err(KernelRefusal::input(
148            KernelStage::Collect,
149            "twist_finite",
150            "sweep_profile_twisted_scaled: twist angle must be finite",
151        ));
152    }
153    const MAX_TURNS: f64 = 8.0;
154    if twist_angle.abs() > MAX_TURNS * TAU {
155        return Err(KernelRefusal::unsupported(
156            KernelStage::Collect,
157            "twist_cap",
158            format!(
159                "sweep_profile_twisted_scaled: twist of {:.3} turns exceeds the {MAX_TURNS}-turn \
160                 limit the 1024-station cap can resolve at 32 stations per quarter turn; \
161                 split the sweep or reduce the twist",
162                twist_angle.abs() / TAU
163            ),
164        ));
165    }
166    let quarter_turns = (twist_angle.abs() / FRAC_PI_2).ceil() as usize;
167    let stations = (quarter_turns * 32).clamp(64, 1024).max(path_turning_stations(path));
168    sweep_profile_along_path_stations_scaled(
169        profile,
170        path,
171        name,
172        stations,
173        twist_angle,
174        None,
175        SectionPlacement::Transplant,
176        SWEEP_DEFAULT_TOLERANCE,
177        true,
178        Some(end_scale),
179    )
180    .map(|swept| swept.solid)
181    .map_err(|error| error.with_message(|error| format!("sweep_profile_twisted_scaled: {error}")))
182}
183
184/// The station budget of a single-curve path sweep, from how far the path's
185/// TANGENT turns: 8 stations per quarter turn of tangent — the 32 per turn
186/// [`sweep_profile_helix`] lofts a coil with — floored at the original 32 and
187/// capped at the loft's 1024.
188///
189/// A fixed 32 was a budget for a path that bends once. Along a coil it is
190/// FOUR stations a turn (an 8-turn helix edge, 2026-09-25), and a loft through
191/// sections a quarter turn apart does not follow the path between them: the
192/// wall cut its own corner and folded through itself, and the Tube and Path
193/// Sweep features refused the edge. The floor keeps every path that turns
194/// through at most a full turn on exactly the geometry it always had.
195///
196/// The turning is [`segment_turning`]'s — the chain sampler's own reading —
197/// independent of the station count it decides. A path it cannot read is
198/// reported by the sampler itself, in its own words, after the profile has been
199/// checked; here it only leaves the budget on the floor.
200fn path_turning_stations(path: &NurbsCurve) -> usize {
201    use std::f64::consts::FRAC_PI_2;
202    let turning = path
203        .domain()
204        .and_then(|domain| segment_turning(path, domain))
205        .unwrap_or(0.0);
206    // The slack keeps a path of EXACTLY a full turn (a circle) on the floor
207    // rather than one quarter over it from sampling round-off.
208    let quarter_turns = (turning / FRAC_PI_2 - 1e-3).ceil().max(0.0) as usize;
209    (quarter_turns * 8).clamp(32, 1024)
210}
211
212/// HOW a section is placed at each station — the two things "sweep a profile
213/// along a path" can mean, and the reason they are not the same shape.
214///
215/// `Transplant` MOVES the profile onto the path: the anchor origin lands on the
216/// station point and the profile plane becomes the station's NORMAL plane. The
217/// profile's own position and its angle to the path are both discarded — every
218/// sweep comes out centred on the path and square to it. That is the classic
219/// swept-surface reading, and it is what `SWP` builds.
220///
221/// `Rigid` CARRIES the profile: the section at station `k` is the profile moved
222/// by the same rigid motion the PATH undergoes between its start and station
223/// `k`,
224///
225/// ```text
226///     section_k(x) = P_k + R_k · (x − P_0)
227/// ```
228///
229/// where `R_k` is the rotation taking the start frame `(T_0, r_0, s_0)` to the
230/// station's `(T_k, r_k, s_k)`. The profile keeps its drawn POSITION and its
231/// drawn ANGLE to the path; what changes along the sweep is only what the path
232/// itself does. Two consequences are the whole point of the mode:
233///   - a STRAIGHT path makes every `R_k` the identity, so the section merely
234///     translates and the result is the oblique prism `extrude_profile_brep`
235///     builds from the same profile and vector — `pathAlign` and `translate`
236///     agree on a straight path rather than merely having the same volume;
237///   - a circular ARC makes `R_k` the rotation about the ARC'S OWN CENTRE AXIS
238///     (for a planar path the RMF's transport rotation IS that rotation), so
239///     the profile is carried round the pivot and the end cap arrives at the
240///     angle the start cap had to the tangent. A full-circle path degenerates
241///     to exactly a revolve of the profile about that axis;
242///   - a HELIX makes `R_k` the SCREW about the helix's own axis — but only when
243///     the path says it is one ([`SweepPath::screw_axes`]), because the frame
244///     that realizes it is not the RMF. A helix is carried into itself by the
245///     screw, which spins the tangent frame at the helix's torsion; the RMF has
246///     no spin about the tangent by construction, so it rolls away from the
247///     screw by `∫τ ds` (169.75° over three turns of a radius-5, pitch-5 coil).
248///     A helix segment's stations are therefore framed off its axis
249///     (`screw_reference`), and every other segment keeps the RMF — which on a
250///     chain of lines and arcs in ANY planes is still exactly each arc's turn
251///     about its own centre, composed. The two hand over at a joint without a
252///     roll.
253///
254/// Why not one frame for every curve: the Frenet frame is the screw on a helix
255/// but spins where a spatial curve nearly straightens (a planar S-cubic lifted
256/// 1e-3 out of its plane carries a 180° roll through the inflection, which 32
257/// stations read as 0.4°), and one axis fitted to the whole run is the screw on
258/// a helix but rolls a two-arc spatial chain by up to 256° against its arcs.
259///
260/// `R_k = F_k · F_0ᵀ` does NOT depend on which perpendicular `r_0` the RMF was
261/// seeded with: re-seeding rolls `F_0` and every `F_k` by the same angle about
262/// the tangent, and the two rolls cancel in the product. That matters because
263/// `Transplant` maps `pu → r_k` directly, so under IT the profile's roll about
264/// the path is whatever `tangents[0].perpendicular()` happened to return — an
265/// arbitrary orientation no caller can predict. `Rigid` has no such freedom.
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum SectionPlacement {
268    /// Move the profile onto the path, square to it (the classic sweep).
269    Transplant,
270    /// Carry the profile by the path's own rigid motion (see above).
271    Rigid,
272}
273
274/// The placement anchor a path sweep transplants its profile with: the plane
275/// frame `(origin = boundary-sample centroid, normal, pu, pv)` the station
276/// loop maps profile points through (`local = p − origin` → `station + ri·(local
277/// ·pu) + si·(local·pv)`). Extracted as data so a HOLE loop can sweep with its
278/// OUTER loop's anchor — sweeping each loop with its OWN centroid would
279/// re-center every loop onto the path and lose the hole's in-plane offset.
280#[derive(Debug, Clone, Copy)]
281pub struct ProfileAnchor {
282    pub origin: Vec3,
283    pub normal: Vec3,
284    pub pu: Vec3,
285    pub pv: Vec3,
286}
287
288/// [`sweep_profile_along_path`] with an explicit placement anchor (see
289/// [`ProfileAnchor`]) — the hole-loop cutter path: the swept loop is validated
290/// as usual but PLACED in its outer loop's frame.
291pub fn sweep_profile_along_path_anchored(
292    profile: &[NurbsCurve],
293    path: &NurbsCurve,
294    name: Option<&str>,
295    anchor: ProfileAnchor,
296) -> Result<BrepSolid, KernelRefusal> {
297    sweep_profile_along_path_stations(
298        profile,
299        path,
300        name,
301        path_turning_stations(path),
302        0.0,
303        Some(anchor),
304        SectionPlacement::Transplant,
305        SWEEP_DEFAULT_TOLERANCE,
306        true,
307    )
308    .map(|swept| swept.solid)
309}
310
311/// [`sweep_profile_twisted`] with an explicit placement anchor: the hole loop
312/// twists about the SAME path axis as its outer loop (shared anchor), so the
313/// cutter stays registered with the outer wall through the whole twist.
314pub fn sweep_profile_twisted_anchored(
315    profile: &[NurbsCurve],
316    path: &NurbsCurve,
317    twist_angle: f64,
318    name: Option<&str>,
319    anchor: ProfileAnchor,
320) -> Result<BrepSolid, KernelRefusal> {
321    sweep_profile_twisted_within(profile, path, twist_angle, name, SectionPlacement::Transplant, Some(anchor), None).map(|swept| swept.solid)
322}
323
324/// [`sweep_profile_twisted`] with the section's PLACEMENT, an optional
325/// placement anchor (`None`: the profile's own, its centroid landed on the
326/// path) and the TOLERANCE its stations are refined to (mm; `None` for
327/// [`SWEEP_DEFAULT_TOLERANCE`]), with the build's station report.
328///
329/// The tolerance is the one every station sweep takes: the stations' fit
330/// through the PATH's own points refined to it against the path
331/// (`chain_stations`). Nothing else is driven by it: a section carried off
332/// the path (its centre on a track of its own, a helix under a twist), the
333/// twist and the wall are not refined to it, and the report reads them (its
334/// `spine_deviation` is the carried section's centre track, its
335/// `wall_deviation` the build's sampled measure of the wall's standoff from
336/// the kinematic sweep at each span's quarter points), for the caller to
337/// weigh. A tolerance looser than the default builds as the default (the
338/// build also reads it as its noise floor).
339///
340/// [`SectionPlacement::Rigid`] carries the profile as drawn, square to the
341/// path at its start: a section drawn off the path stays off it by the same
342/// offset in the rotation-minimizing frame, and the twist turns it about the
343/// path itself. [`SectionPlacement::Transplant`] lands it on the path in a
344/// roll of its own choosing (see [`SectionPlacement`]).
345pub fn sweep_profile_twisted_within(
346    profile: &[NurbsCurve],
347    path: &NurbsCurve,
348    twist_angle: f64,
349    name: Option<&str>,
350    placement: SectionPlacement,
351    anchor: Option<ProfileAnchor>,
352    tolerance: Option<f64>,
353) -> Result<SweptChain, KernelRefusal> {
354    use std::f64::consts::{FRAC_PI_2, TAU};
355
356    if !twist_angle.is_finite() {
357        return Err(KernelRefusal::input(
358            KernelStage::Collect,
359            "twist_finite",
360            "sweep_profile_twisted: twist angle must be finite",
361        ));
362    }
363    const MAX_TURNS: f64 = 16.0;
364    if twist_angle.abs() > MAX_TURNS * TAU {
365        return Err(KernelRefusal::unsupported(
366            KernelStage::Collect,
367            "twist_cap",
368            format!(
369            "sweep_profile_twisted: twist of {:.3} turns exceeds the {MAX_TURNS}-turn \
370             limit the 1024-station cap can resolve at 16 stations per quarter turn; \
371             split the sweep or reduce the twist",
372            twist_angle.abs() / TAU
373            ),
374        ));
375    }
376    let tolerance = sweep_tolerance(tolerance)?.min(SWEEP_DEFAULT_TOLERANCE);
377    let quarter_turns = (twist_angle.abs() / FRAC_PI_2).ceil() as usize;
378    let stations = (quarter_turns * 16).clamp(32, 1024).max(path_turning_stations(path));
379    sweep_profile_along_path_stations(profile, path, name, stations, twist_angle, anchor, placement, tolerance, true)
380        .map_err(|error| error.with_message(|error| format!("sweep_profile_twisted: {error}")))
381}
382
383/// Sweep a CLOSED PLANAR profile along a CHAIN of path curves joined
384/// head-to-tail — the multi-segment entry point, with the twist and anchor
385/// options the single-curve family exposes as separate functions folded into
386/// one signature (the feature layer picks all three per loop, so splitting them
387/// four ways here would only push the same match into the caller).
388///
389/// `path` carries the chain AND its classification ([`SweepPath`]): the segment
390/// names for the joint refusal (a short or empty name list degrades to
391/// `<unnamed>` rather than failing), whether the run is CLOSED, the plane it lies
392/// in if it lies in one, and the continuity of every joint. The refusals below
393/// READ that classification rather than each re-deriving it — the corner gate no
394/// longer measures its own tangent break while sampling, and closure is a
395/// property of the path rather than something the sampler notices about its first
396/// and last station.
397///
398/// `corner_advice` is appended to the cornered-joint refusal and is the CALLER's
399/// to write, because the builder has two callers with different answers: path
400/// sweep sends the user to SW (a different feature), while SW's own `pathAlign`
401/// sends them to its `translate` mode. A builder that named one feature would be
402/// telling half its users to switch to the feature they are already in.
403///
404/// A ONE-segment OPEN chain delegates to the single-curve builders unchanged, so
405/// the geometry every existing path sweep emits is untouched by this entry point
406/// existing — the multi-segment sampler is reached only by a path that actually
407/// has a joint. A one-segment CLOSED chain (a resident circular edge) does NOT
408/// delegate: the single-curve samplers cap both ends, which is exactly what a
409/// ring must not do.
410///
411/// A CORNER (a joint past [`MAX_JOINT_TANGENT_BREAK`]) selects the MITRE lane
412/// when every segment is straight — see `sweep_topology/miter.rs` for the
413/// construction and `CornerPolicy` for why this entry mitres while
414/// [`sweep_profile_along_chain_with_stations`] refuses. A CLOSED cornered
415/// polyline is a picture FRAME: its closing joint is a mitre like the rest and
416/// the result has no caps. A corner at a CURVED segment is refused by name.
417pub fn sweep_profile_along_chain(
418    profile: &[NurbsCurve],
419    path: &SweepPath,
420    twist_angle: f64,
421    name: Option<&str>,
422    anchor: Option<ProfileAnchor>,
423    placement_mode: SectionPlacement,
424    corner_advice: &str,
425) -> Result<BrepSolid, KernelRefusal> {
426    sweep_profile_along_chain_reported_core(
427        profile,
428        path,
429        twist_angle,
430        name,
431        anchor,
432        placement_mode,
433        corner_advice,
434        None,
435        false, // This solid-only API does not return station diagnostics.
436    )
437    .map(|swept| swept.solid)
438}
439
440/// A swept solid with the MEASURED BOUND of its construction
441/// ([`SweepStationReport`]): `None` where the construction is exact — the
442/// mitre lane (exact pieces on bisector planes) and the envelope lane (a
443/// revolve) — and the station lane's report otherwise.
444#[derive(Debug)]
445pub struct SweptChain {
446    pub solid: BrepSolid,
447    pub report: Option<SweepStationReport>,
448}
449
450impl SweptChain {
451    fn exact(solid: BrepSolid) -> Self {
452        Self {
453            solid,
454            report: None,
455        }
456    }
457}
458
459/// [`sweep_profile_along_chain`] with the requested wall TOLERANCE (mm;
460/// `None` for [`SWEEP_DEFAULT_TOLERANCE`]) and the measured bound the build
461/// reached, for a caller that carries it on (the sweep features put it in
462/// `FeatureResult::approximations`). The station lane refines its stations
463/// until the loft's own interpolant stands within `tolerance` of the kinematic
464/// sweep's wall, or the station cap stops it; the report says which.
465#[allow(clippy::too_many_arguments)]
466pub fn sweep_profile_along_chain_reported(
467    profile: &[NurbsCurve],
468    path: &SweepPath,
469    twist_angle: f64,
470    name: Option<&str>,
471    anchor: Option<ProfileAnchor>,
472    placement_mode: SectionPlacement,
473    corner_advice: &str,
474    tolerance: Option<f64>,
475) -> Result<SweptChain, KernelRefusal> {
476    sweep_profile_along_chain_reported_core(profile, path, twist_angle, name, anchor,
477        placement_mode, corner_advice, tolerance, true)
478}
479
480#[allow(clippy::too_many_arguments)]
481fn sweep_profile_along_chain_reported_core(
482    profile: &[NurbsCurve],
483    path: &SweepPath,
484    twist_angle: f64,
485    name: Option<&str>,
486    anchor: Option<ProfileAnchor>,
487    placement_mode: SectionPlacement,
488    corner_advice: &str,
489    tolerance: Option<f64>,
490    measure_report: bool,
491) -> Result<SweptChain, KernelRefusal> {
492    use std::f64::consts::{FRAC_PI_2, TAU};
493    let tolerance = sweep_tolerance(tolerance)?;
494
495    if path.is_empty() {
496        return Err(KernelRefusal::input(
497            KernelStage::Collect,
498            "chain_empty",
499            "sweepSolid: path chain is empty",
500        ));
501    }
502    // A bend TIGHTER than the section is the envelope lane's, not the loft's, and
503    // it is asked BEFORE the single-curve shortcut below — that shortcut lands in
504    // the same skinning builder, so taking it first would hide the one path shape
505    // this lane exists for (one circular arc) behind it.
506    let envelope_lane = super::envelope::recognize_swept_envelope(profile, path, placement_mode)?
507        .is_ok();
508
509    if !twist_angle.is_finite() {
510        return Err(KernelRefusal::input(
511            KernelStage::Collect,
512            "twist_finite",
513            if path.curves.len() == 1 && placement_mode == SectionPlacement::Transplant {
514                "sweep_profile_twisted: twist angle must be finite"
515            } else {
516                "sweep_profile_along_chain: twist angle must be finite"
517            },
518        ));
519    }
520    const MAX_TURNS: f64 = 16.0;
521    if twist_angle.abs() > MAX_TURNS * TAU {
522        let who = if path.curves.len() == 1 && placement_mode == SectionPlacement::Transplant {
523            "sweep_profile_twisted"
524        } else {
525            "sweep_profile_along_chain"
526        };
527        return Err(KernelRefusal::unsupported(
528            KernelStage::Collect,
529            "twist_cap",
530            format!(
531            "{who}: twist of {:.3} turns exceeds the {MAX_TURNS}-turn \
532             limit the 1024-station cap can resolve at 16 stations per quarter turn; \
533             split the sweep or reduce the twist",
534            twist_angle.abs() / TAU
535            ),
536        ));
537    }
538    // Single segment under `Transplant`: the single-curve sampler's own budget
539    // on the single-curve lane, so an ordinary one-edge path sweep emits the
540    // geometry it always has wherever it reads inside the tolerance. `Rigid`
541    // has no single-curve budget and falls through to the chain sampler, which
542    // samples a 1-element chain over exactly the domain the single-curve
543    // sampler would (no joints, the whole budget on one segment). A CLOSED
544    // single segment falls through too — the single-curve lane ends in a capped
545    // loft, and a ring has no caps.
546    if let ([single], SectionPlacement::Transplant, false, false) =
547        (path.curves.as_slice(), placement_mode, path.closed, envelope_lane)
548    {
549        // The single-curve builders' own budgets ([`path_turning_stations`],
550        // the twisted law), on the single-curve lane, at this tolerance.
551        let stations = if twist_angle == 0.0 {
552            path_turning_stations(single)
553        } else {
554            let quarter_turns = (twist_angle.abs() / FRAC_PI_2).ceil() as usize;
555            (quarter_turns * 16).clamp(32, 1024).max(path_turning_stations(single))
556        };
557        return sweep_profile_along_path_stations(
558            profile,
559            single,
560            name,
561            stations,
562            twist_angle,
563            anchor,
564            SectionPlacement::Transplant,
565            tolerance,
566            measure_report,
567        )
568        .map_err(|error| {
569            if twist_angle == 0.0 {
570                error
571            } else {
572                error.with_message(|error| format!("sweep_profile_twisted: {error}"))
573            }
574        });
575    }
576
577    // Everything else — any multi-segment chain, and a single segment under
578    // `Rigid` — takes the same station law the single-curve twisted builder
579    // uses, so density scales with twist identically on a chained path.
580    // A CLOSED SPATIAL path lays its counter-twist down on top of the requested
581    // twist, which adds up to half a turn, so the density is set for the most the
582    // lap can roll.
583    let stations = if twist_angle == 0.0 {
584        32
585    } else {
586        let counter = if path.closed && path.planar.is_none() {
587            std::f64::consts::PI
588        } else {
589            0.0
590        };
591        let quarter_turns = ((twist_angle.abs() + counter) / FRAC_PI_2).ceil() as usize;
592        (quarter_turns * 16).clamp(32, 1024)
593    };
594    let _ = name;
595    sweep_profile_along_chain_stations(
596        profile,
597        path,
598        stations,
599        twist_angle,
600        anchor,
601        placement_mode,
602        corner_advice,
603        CornerPolicy::Mitre,
604        tolerance,
605        measure_report,
606    )
607}
608
609/// The wall tolerance a sweep is refined to: the caller's, or the default;
610/// refused when it is not a positive finite length.
611fn sweep_tolerance(tolerance: Option<f64>) -> Result<f64, KernelRefusal> {
612    let tolerance = tolerance.unwrap_or(SWEEP_DEFAULT_TOLERANCE);
613    if !(tolerance.is_finite() && tolerance > 0.0) {
614        return Err(KernelRefusal::input(
615            KernelStage::Collect,
616            "sweep_tolerance",
617            format!("sweepSolid: the requested wall tolerance must be a positive length, not {tolerance}"),
618        ));
619    }
620    Ok(tolerance)
621}
622
623/// [`sweep_profile_along_chain`] with an explicit STATION budget and no twist
624/// — the entry a caller with a long, smooth chain uses when the default 32
625/// stations would under-sample it (a wire-harness bundle along a many-anchor
626/// spline: three pieces per span, so a handful of spans already starves each
627/// piece of stations). The budget is spread over the chain by arc length
628/// exactly as the twisted builder's law spreads its own; the 1024-station cap
629/// and the tangent-continuity refusal apply unchanged.
630pub fn sweep_profile_along_chain_with_stations(
631    profile: &[NurbsCurve],
632    path: &SweepPath,
633    stations: usize,
634    corner_advice: &str,
635) -> Result<BrepSolid, KernelRefusal> {
636    sweep_profile_along_chain_with_stations_reported(profile, path, stations, corner_advice, None)
637        .map(|swept| swept.solid)
638}
639
640/// [`sweep_profile_along_chain_with_stations`] with the requested wall
641/// tolerance (`None` for the default) and the measured bound: the caller's
642/// budget is the FLOOR, refined where the measured deviation is over the
643/// tolerance.
644pub fn sweep_profile_along_chain_with_stations_reported(
645    profile: &[NurbsCurve],
646    path: &SweepPath,
647    stations: usize,
648    corner_advice: &str,
649    tolerance: Option<f64>,
650) -> Result<SweptChain, KernelRefusal> {
651    let tolerance = sweep_tolerance(tolerance)?;
652    sweep_profile_along_chain_stations(
653        profile,
654        path,
655        stations.clamp(2, 1024),
656        0.0,
657        None,
658        SectionPlacement::Transplant,
659        corner_advice,
660        CornerPolicy::Refuse,
661        tolerance,
662        true,
663    )
664}
665
666/// Validate a closed planar profile loop and derive its placement anchor —
667/// the path sweep's §1 block, extracted bit-identically: 16 samples per curve,
668/// closure at `tolerance`, Newell normal, boundary-sample-mean origin,
669/// planarity at `tolerance * 100`, `pu = np.perpendicular()`, `pv = np × pu`.
670pub fn profile_anchor(profile: &[NurbsCurve]) -> Result<ProfileAnchor, KernelRefusal> {
671    let tolerance = 1e-6;
672    if profile.len() < 2 {
673        return Err(KernelRefusal::input(
674            KernelStage::Collect,
675            "profile_count",
676            "sweepSolid: profile needs at least 2 curves forming a closed loop",
677        ));
678    }
679    let mut samples = Vec::new();
680    for (index, curve) in profile.iter().enumerate() {
681        let [start, end] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
682        let next = &profile[(index + 1) % profile.len()];
683        let next_start = next.domain().or_refuse(KernelStage::Collect, "domain")?[0];
684        if curve
685            .evaluate(end).or_refuse(KernelStage::Collect, "evaluate")?
686            .sub(next.evaluate(next_start).or_refuse(KernelStage::Collect, "evaluate")?)
687            .length()
688            > tolerance
689        {
690            return Err(KernelRefusal::input(
691                KernelStage::Collect,
692                "profile_closed",
693                format!("sweepSolid: profile is not closed at curve {index}"),
694            ));
695        }
696        for sample in 0..16 {
697            samples.push(curve.evaluate(start + (end - start) * sample as f64 / 16.0).or_refuse(KernelStage::Collect, "evaluate")?);
698        }
699    }
700    let normal = crate::polygon::newell_normal(&samples);
701    let centroid = samples.iter().fold(Vec3::default(), |sum, &point| sum.add(point));
702    let np = normal.normalized().map_err(|_| {
703        KernelRefusal::input(
704            KernelStage::Collect,
705            "profile_area",
706            "sweepSolid: profile is degenerate (zero enclosed area)",
707        )
708    })?;
709    let origin = centroid.scale(1.0 / samples.len() as f64);
710    if samples
711        .iter()
712        .any(|point| point.sub(origin).dot(np).abs() > tolerance * 100.0)
713    {
714        return Err(KernelRefusal::input(
715            KernelStage::Collect,
716            "profile_planar",
717            "sweepSolid: profile is not planar",
718        ));
719    }
720    let pu = np.perpendicular().or_refuse(KernelStage::Collect, "perpendicular")?;
721    let pv = np.cross(pu).normalized().or_refuse(KernelStage::Collect, "normalized")?;
722    Ok(ProfileAnchor {
723        origin,
724        normal: np,
725        pu,
726        pv,
727    })
728}
729
730/// Core of the path sweep with an explicit station count.  Every consumer of
731/// the station count (path sampling, RMF propagation, section placement)
732/// derives from the one `stations` argument so the density scales as a unit.
733/// `twist_angle` (radians; 0 for the untwisted variants) rotates the placed
734/// profile about the path tangent linearly in sampled arc length — the
735/// `twist_angle == 0.0` fast path leaves the RMF axes bit-identical, so the
736/// untwisted callers keep golden parity.
737fn sweep_profile_along_path_stations(
738    profile: &[NurbsCurve],
739    path: &NurbsCurve,
740    name: Option<&str>,
741    stations: usize,
742    twist_angle: f64,
743    anchor: Option<ProfileAnchor>,
744    placement_mode: SectionPlacement,
745    tolerance: f64,
746    measure_report: bool,
747) -> Result<SweptChain, KernelRefusal> {
748    sweep_profile_along_path_stations_scaled(
749        profile,
750        path,
751        name,
752        stations,
753        twist_angle,
754        anchor,
755        placement_mode,
756        tolerance,
757        measure_report,
758        None,
759    )
760}
761
762/// [`sweep_profile_along_path_stations`] with a scaling law: `end_scale` is the
763/// section's scale at the path's end (see [`StationRun::end_scale`]).
764#[allow(clippy::too_many_arguments)]
765fn sweep_profile_along_path_stations_scaled(
766    profile: &[NurbsCurve],
767    path: &NurbsCurve,
768    name: Option<&str>,
769    stations: usize,
770    twist_angle: f64,
771    anchor: Option<ProfileAnchor>,
772    placement_mode: SectionPlacement,
773    tolerance: f64,
774    measure_report: bool,
775    end_scale: Option<f64>,
776) -> Result<SweptChain, KernelRefusal> {
777    // Loft carries no face names; the app stamps them onto the emitted face
778    // order.  Accept `name` for ABI symmetry with the other builders.
779    let _ = name;
780    let mut timing = crate::loft_topology::ConstructionProfile::new("sweep_path");
781    if stations < 2 {
782        return Err(KernelRefusal::input(
783            KernelStage::Collect,
784            "stations",
785            "sweepSolid: need at least 2 stations",
786        ));
787    }
788
789    // --- 1. Validate the profile: closed + planar; derive (origin, np, pu, pv).
790    //        A caller-supplied anchor OVERRIDES the placement frame (the swept
791    //        loop is still validated against its own plane), so a hole loop
792    //        rides the path in its outer loop's frame instead of re-centering.
793    //        Resolved HERE, before the path is touched, so a bad profile is
794    //        still reported ahead of a bad path exactly as it always was.
795    let placement = resolve_placement(profile, anchor, placement_mode)?;
796    timing.lap("profile");
797
798    // --- 2. Sample the path as a one-segment chain on the single-curve lane:
799    //        `stations` uniform in the parameter, the sampling this builder
800    //        always had, refined only where the measured deviation is over the
801    //        tolerance (`chain_stations`).
802    let chain = std::slice::from_ref(path);
803    let (samples, budget) = chain_stations(chain, false, SamplerLane::SingleCurve, stations, tolerance, None)?;
804    let StationSamples {
805        points,
806        tangents,
807        curvatures,
808        params,
809        ..
810    } = &samples;
811
812    timing.lap("sampling");
813    sweep_sections_through_samples(
814        profile,
815        points,
816        tangents,
817        curvatures,
818        twist_angle,
819        placement,
820        placement_mode,
821        RingFrame::Open,
822        None,
823        None,
824        StationRun {
825            chain,
826            params,
827            budget,
828            tolerance,
829            measure_report,
830            end_scale,
831            breaks: None,
832        },
833    )
834}
835
836/// What a CHAIN builder does with a CORNER (a `G0` joint).
837///
838/// Two of this module's entry points sweep chains, and they answer the question
839/// differently — not because the geometry differs but because their callers'
840/// corner POLICIES do, and a builder that guessed would be overriding one of
841/// them:
842///   - [`sweep_profile_along_chain`] MITRES a polyline's corners, a closed
843///     polyline's closing joint included (`sweep_topology/miter.rs`). Its callers
844///     are the two sweep FEATURES, and a mitred corner is the shape they are
845///     asked for.
846///   - [`sweep_profile_along_chain_with_stations`] REFUSES every corner. Its
847///     callers build their own chains and have already decided what a corner
848///     means: the tube ROUNDS one into a tangent bend or joins it with a ball,
849///     and the wire harness routes tangent-continuous splines. A corner
850///     reaching either of them means their own construction did not come out,
851///     and mitring it instead would silently ship a shape neither feature
852///     offers.
853#[derive(Debug, Clone, Copy, PartialEq, Eq)]
854enum CornerPolicy {
855    /// A polyline's corners are mitred, open or closed; anything else is refused.
856    Mitre,
857    /// Every corner is refused by name.
858    Refuse,
859}
860
861/// The SECTION a mitred sweep carries, placed in world, with its plane normal —
862/// the two things `sweep_topology/miter.rs` needs, and all it needs.
863///
864/// The placement modes are resolved HERE rather than in the mitre builder, on
865/// the same frame the skinning lane's station 0 uses (`û₀.perpendicular()`), so
866/// the two lanes place a section identically and a path that crosses the
867/// continuity gate does not also jump in space:
868///   - `Transplant` maps the profile's plane frame onto the path's first station
869///     (anchor origin onto the path, profile square to it), so the section's
870///     normal is the first tangent;
871///   - `Rigid` takes the profile WHERE IT IS, keeping the offset from the path
872///     and the angle to it that it was drawn with, so the section's normal is
873///     the profile's own.
874fn place_section(
875    profile: &[NurbsCurve],
876    placement: ProfileAnchor,
877    placement_mode: SectionPlacement,
878    start: Vec3,
879    tangent: Vec3,
880) -> Result<(Vec<NurbsCurve>, Vec3), KernelRefusal> {
881    if placement_mode == SectionPlacement::Rigid {
882        return Ok((profile.to_vec(), placement.normal));
883    }
884    let ProfileAnchor { origin, pu, pv, .. } = placement;
885    let r0 = tangent.perpendicular().or_refuse(KernelStage::Fragment, "perpendicular")?;
886    let s0 = tangent.cross(r0).normalized().or_refuse(KernelStage::Fragment, "normalized")?;
887    let mut placed = Vec::with_capacity(profile.len());
888    for curve in profile {
889        let control_points = curve
890            .control_points
891            .iter()
892            .map(|control| {
893                let point = control.point()?;
894                let local = point.sub(origin);
895                let world = start
896                    .add(r0.scale(local.dot(pu)))
897                    .add(s0.scale(local.dot(pv)));
898                Ok(Vec4::from_point(world, control.w))
899            })
900            .collect::<Result<Vec<_>, String>>()
901            .or_refuse(KernelStage::Fragment, "control_point")?;
902        placed.push(
903            NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
904                .or_refuse(KernelStage::Fragment, "curve_new")?,
905        );
906    }
907    Ok((placed, tangent))
908}
909
910/// The placement frame a sweep transplants its profile with: the caller's
911/// `anchor` when it supplied one (a hole loop riding its outer loop's frame),
912/// otherwise the profile's own. Either way the profile is VALIDATED — closed and
913/// planar — because `profile_anchor` is what does that validating, and skipping
914/// it for an anchored loop would let an open hole loop through.
915///
916/// Called by each SAMPLER before it touches the path, so the "bad profile" error
917/// still precedes the "bad path" one, as it did when the two lived in one
918/// function.
919fn resolve_placement(
920    profile: &[NurbsCurve],
921    anchor: Option<ProfileAnchor>,
922    placement_mode: SectionPlacement,
923) -> Result<ProfileAnchor, KernelRefusal> {
924    let computed = profile_anchor(profile)?;
925    Ok(match placement_mode {
926        // RIGID never transplants, so there is no frame to borrow: every loop
927        // keeps its own position already, which is the whole reason the anchor
928        // exists under `Transplant`. Taking a caller's anchor here would silently
929        // swap in another loop's NORMAL for the fold-back guard below.
930        SectionPlacement::Rigid => computed,
931        SectionPlacement::Transplant => anchor.unwrap_or(computed),
932    })
933}
934
935
936/// Sweep a CLOSED PLANAR profile along a CHAIN of path curves, joined
937/// head-to-tail, as one continuous tube — or, for a CLOSED path, as a capless
938/// ring.
939///
940/// The chain is sampled as a single trajectory and handed to the shared core,
941/// so ONE rotation-minimizing frame is propagated across the whole path: a joint
942/// is just another pair of adjacent stations to the RMF, which is what makes the
943/// profile arrive at the far end in the orientation the near end implies rather
944/// than snapping at each segment.
945///
946/// STATION BUDGET. `stations` are distributed across the segments in proportion
947/// to estimated ARC LENGTH (chord sums over 16 samples per curve), floored at 2
948/// per segment so a short fillet between two long lines still carries its
949/// curvature. The shared endpoint of two adjacent segments is sampled ONCE, not
950/// twice — a duplicated station would land in the RMF's coincident-step branch
951/// and waste a section on zero advance. A CLOSED path drops one more station for
952/// the same reason: its last station IS its first.
953///
954/// JOINTS decide the LANE. A break within [`MAX_JOINT_TANGENT_BREAK`] is skinned
955/// here; a break past it is a CORNER, which under [`CornerPolicy::Mitre`] hands an
956/// open all-straight run to the mitre builder (`sweep_topology/miter.rs`) and is
957/// otherwise refused by name, with the angle and the two segments. The
958/// classification carried on the path is what says so — this sampler no longer
959/// measures its own.
960#[allow(clippy::too_many_arguments)]
961fn sweep_profile_along_chain_stations(
962    profile: &[NurbsCurve],
963    path: &SweepPath,
964    stations: usize,
965    twist_angle: f64,
966    anchor: Option<ProfileAnchor>,
967    placement_mode: SectionPlacement,
968    corner_advice: &str,
969    corners: CornerPolicy,
970    tolerance: f64,
971    measure_report: bool,
972) -> Result<SweptChain, KernelRefusal> {
973    let chain = path.curves.as_slice();
974    if chain.is_empty() {
975        return Err(KernelRefusal::input(
976            KernelStage::Collect,
977            "chain_empty",
978            "sweepSolid: path chain is empty",
979        ));
980    }
981    if stations < 2 {
982        return Err(KernelRefusal::input(
983            KernelStage::Collect,
984            "stations",
985            "sweepSolid: need at least 2 stations",
986        ));
987    }
988    // Profile first, matching the single-curve sampler's order of complaint.
989    let placement = resolve_placement(profile, anchor, placement_mode)?;
990
991    // --- The swept ENVELOPE, trimmed at its own self-intersection.
992    //
993    //     Past `ρκ = 1` the sections CROSS and the loft below skins a wall that
994    //     passes through itself. For a CIRCLE carried along one circular planar
995    //     arc the correct solid is a REVOLVE — the section disc truncated at the
996    //     axis, plus the reflection of the part that crossed it, each revolved
997    //     through the path's own turn (`sweep_topology/envelope.rs`) — and this
998    //     is where that lane is taken instead of the loft.
999    //
1000    //     Anything else tight is left to the §4c refusal below, which now carries
1001    //     WHICH half of the configuration this sweep missed. Nothing under
1002    //     `ρκ = 1` reaches the lane at all: the recognition refuses a bend that
1003    //     is not tighter than its section, so every shape that builds today keeps
1004    //     the builder it has.
1005    let envelope_gap =
1006        match super::envelope::recognize_swept_envelope(profile, path, placement_mode)? {
1007            Ok(plan) => {
1008                let mut bodies = super::envelope::build_swept_envelope(&plan)?;
1009                if bodies.len() == 1 {
1010                    return Ok(SweptChain::exact(bodies.remove(0)));
1011                }
1012                return Err(KernelRefusal::unsupported(
1013                    KernelStage::Fragment,
1014                    "envelope_two_bodies",
1015                    format!(
1016                    "{}: a section that crosses the path's axis (ρ·κ = {:.6}) sweeps TWO \
1017                     bodies — the near lobe over the path's own azimuths and the far lobe half \
1018                     a turn from them, meeting only along the axis — and this entry returns one \
1019                     solid. {} were built; ask `sweep_envelope_bodies` for the pair",
1020                    SWEEP_ENVELOPE_REFUSAL,
1021                    plan.ratio(),
1022                    bodies.len()
1023                    ),
1024                ));
1025            }
1026            Err(reason) => reason,
1027        };
1028
1029    // --- A CORNER, read off the path's classification. Every joint was measured
1030    //     once when the path was resolved, the CLOSING joint of a closed path
1031    //     included — which is how a ring's seam gets the same gate as its
1032    //     interior joints instead of being the one joint nobody checked.
1033    //
1034    //     A corner now selects a LANE rather than ending the build. A POLYLINE —
1035    //     every segment straight, at least one corner — is MITRED: the section is
1036    //     swept along each segment and the two sweeps are trimmed to the joint's
1037    //     bisector plane, sharing one face loop there
1038    //     (`sweep_topology/miter.rs`). A CLOSED one is a picture FRAME, whose
1039    //     closing joint is mitred like the rest and which has no caps; the frame
1040    //     lane's own refusals (a spatial loop, by its holonomy; a self-crossing
1041    //     loop; overlapping mitres) live with the construction. What remains
1042    //     refused HERE is a corner on a path that is not all straight — there is
1043    //     no bisector plane for a curve to be trimmed to, and no lane that mixes
1044    //     the two.
1045    if let Some(corner) = path.corner() {
1046        if corners == CornerPolicy::Mitre && path.cornered_polyline() {
1047            // A twist is laid down in arc length over the stations, and a mitre has
1048            // none. A CLOSED frame rolls it along the middle of each side instead,
1049            // where a roll keeps the shared joint loops (`sweep_topology/miter.rs`),
1050            // exactly as it rolls its own counter-twist. An OPEN cornered run does
1051            // not have that construction and is refused.
1052            if twist_angle != 0.0 && !path.closed {
1053                return Err(KernelRefusal::unsupported(
1054                    KernelStage::Classify,
1055                    "cornered_twist",
1056                    "sweepSolid: a CORNERED path cannot carry a twist — its corners are mitred \
1057                     from exact pieces that meet on the joint's bisector plane, and a twist laid \
1058                     down along the path would roll the two sides of that plane apart, so they \
1059                     would no longer share one loop there. Only a CLOSED frame rolls a twist along \
1060                     the middle of its sides. Sweep the run without the twist; a \
1061                     tangent-continuous (smooth) path is skinned through stations and carries one",
1062                ));
1063            }
1064            let (section, section_normal, _) =
1065                mitre_section(profile, placement, placement_mode, path)?;
1066            return super::miter::sweep_section_mitered(
1067                &section,
1068                section_normal,
1069                path,
1070                twist_angle,
1071            )
1072            .map(SweptChain::exact);
1073        }
1074        // A path with BOTH a corner and a curved segment is in NEITHER lane, and
1075        // this is the refusal that says so: the mitre lane needs every segment
1076        // straight (one direction per side for the bisector plane to bisect) and
1077        // the skinning lane needs every joint tangent-continuous (it interpolates
1078        // stations, so it would round the corner off). A rounded rectangle with
1079        // ONE corner left sharp is exactly that path — three G0 joints the mitre
1080        // lane could carry and two G1 joints at an arc it cannot — and mitring
1081        // the sharp corners while skinning the arc is a MIXED construction this
1082        // builder does not have. Refused with both halves named rather than built
1083        // as whichever lane happens to be asked first.
1084        let curved = (0..path.len())
1085            .find(|index| {
1086                let curve = &path.curves[*index];
1087                curve.degree != 1 || curve.control_points.len() != 2
1088            })
1089            .map(|index| format!(" — segment '{}' is CURVED", path.name(index)))
1090            .unwrap_or_default();
1091        // The MIXED-LANE sentence belongs only to a path that actually has a
1092        // curved segment. Under [`CornerPolicy::Refuse`] an ALL-STRAIGHT cornered
1093        // chain reaches this same refusal (the tube's and the wire harness's
1094        // corners are refused whatever their segments are), and telling those
1095        // callers that a straight cornered run is mitred would name a lane they
1096        // deliberately do not have — their own `corner_advice` says what to do
1097        // instead.
1098        let mixed = if curved.is_empty() {
1099            String::new()
1100        } else {
1101            " A path that MIXES the two — corners at some joints and curved segments elsewhere              — is in neither lane: every segment straight is mitred (open or closed), every              joint tangent-continuous is skinned, and nothing builds one construction for some              joints and the other for the rest."
1102                .to_string()
1103        };
1104        return Err(KernelRefusal::unsupported(
1105            KernelStage::Classify,
1106            "corner",
1107            format!(
1108            "the path must be tangent-continuous: segments '{}' and '{}' meet at a {:.1}° \
1109             corner{curved}. The profile is skinned between sampled stations along the path, so a \
1110             corner would be ROUNDED OFF rather than mitred, and a mitre needs two STRAIGHT \
1111             segments: it trims both sweeps to the plane that bisects their directions, and a \
1112             curve has no single direction to bisect.{mixed} {corner_advice}",
1113            path.name(corner.before),
1114            path.name(corner.after),
1115            corner.tangent_break.to_degrees()
1116            ),
1117        ));
1118    }
1119
1120    // --- A CLOSED path takes a REQUESTED twist only where it closes. After one lap
1121    //     the section comes back rolled by the whole twist, so the twist must be a
1122    //     rotational symmetry of the section about the path. The ring lane reads
1123    //     that off the section and refuses by name a twist that does not close
1124    //     ([`closing_twist`]).
1125
1126    // --- A bend TIGHTER than the section is refused on the FLOOR stations,
1127    //     before any are spent refining a run that folds, and so that the
1128    //     refusal quotes the same stations whatever tolerance was asked
1129    //     (`sweep_bend_profile` reads the same). Untwisted `Transplant` only —
1130    //     the reach of a rolled section is the twisted placement's to read, in
1131    //     §4c of `sweep_sections_through_samples`, which stays the backstop.
1132    if placement_mode == SectionPlacement::Transplant
1133        && twist_angle == 0.0
1134        && std::env::var("BREP_SWEEP_BEND_GUARD").as_deref() != Ok("0")
1135    {
1136        let (floor, _) = chain_stations(path.curves.as_slice(), path.closed, SamplerLane::Chain, stations, 0.0, None)?;
1137        let profile_stations = floor_bend_stations(profile, &placement, path, &floor)?;
1138        if let Some(refusal) = tight_bend_refusal(&profile_stations, floor.points.len()) {
1139            return Err(with_envelope_gap(refusal, Some(envelope_gap.as_str())));
1140        }
1141    }
1142
1143    // --- Sample the chain as ONE trajectory (budget, domains, stations), and
1144    //     refine it to the requested tolerance.
1145    //     With `BREP_SWEEP_JOINT_BREAKS` on (the default), the wall columns are BROKEN at
1146    //     every joint where the path's curvature jumps (G1), so refinement and
1147    //     loft both fit each run between such joints on its own. Not on a
1148    //     twisted ring, whose seam-shifted columns run several laps.
1149    let break_after: Option<Vec<bool>> = if super::stations::joint_breaks_enabled()
1150        && !(path.closed && twist_angle != 0.0)
1151    {
1152        let mut after = vec![false; chain.len()];
1153        for joint in &path.joints {
1154            if joint.continuity == JointContinuity::G1 {
1155                after[joint.before] = true;
1156            }
1157        }
1158        Some(after).filter(|after| after.iter().any(|&jump| jump))
1159    } else {
1160        None
1161    };
1162    let (samples, budget) = chain_stations(
1163        path.curves.as_slice(),
1164        path.closed,
1165        SamplerLane::Chain,
1166        stations,
1167        tolerance,
1168        break_after.as_deref(),
1169    )?;
1170    let breaks = break_after.as_deref().map(|after| station_breaks(&samples, after));
1171    let StationSamples {
1172        points,
1173        tangents,
1174        curvatures,
1175        segments,
1176        params,
1177    } = &samples;
1178
1179    // --- CLOSED: the ring needs a frame that comes back to itself. A PLANAR path
1180    //     has one for free (see `ring_normal`); a SPATIAL one comes back rolled by
1181    //     its own holonomy and is closed by the counter-twist policy
1182    //     ([`RingFrame::Spatial`]).
1183    let closure = ring_frame(path, tangents)?;
1184
1185    sweep_sections_through_samples(
1186        profile,
1187        points,
1188        tangents,
1189        curvatures,
1190        twist_angle,
1191        placement,
1192        placement_mode,
1193        closure,
1194        Some(envelope_gap.as_str()),
1195        Some((segments.as_slice(), path)),
1196        StationRun {
1197            chain: path.curves.as_slice(),
1198            params,
1199            budget,
1200            tolerance,
1201            measure_report,
1202            end_scale: None,
1203            breaks: breaks.as_deref(),
1204        },
1205    )
1206}
1207
1208/// The stations a broken run's columns break at: every interior JOINT station
1209/// (one that arrives on segment `i` and departs into `i + 1`) whose joint
1210/// `break_after[i]` marks as a curvature jump. A ring's seam (station 0) is
1211/// not listed; its loft breaks there whenever the run is broken.
1212fn station_breaks(samples: &StationSamples, break_after: &[bool]) -> Vec<usize> {
1213    (1..samples.points.len())
1214        .filter(|&k| {
1215            let arriving = samples.segments[k];
1216            samples.params[k].segment != arriving && break_after.get(arriving).copied().unwrap_or(false)
1217        })
1218        .collect()
1219}
1220
1221/// How a station run CLOSES — which frame a ring's sections are placed on.
1222///
1223/// Three states, because "is this a ring" and "is its frame written down in
1224/// closed form" are different questions and only a planar ring answers yes to
1225/// both:
1226///   - `Open`: the transported frame and two end caps;
1227///   - `Planar(normal)`: a ring whose reference axis is the path plane's normal
1228///     at every station, which returns to itself EXACTLY (see [`ring_normal`]);
1229///   - `Spatial`: a ring on the TRANSPORTED frame, which returns rolled by the
1230///     path's own holonomy and is closed by the counter-twist policy — see
1231///     [`ring_closure_frames`].
1232#[derive(Debug, Clone, Copy)]
1233enum RingFrame {
1234    Open,
1235    Planar(Vec3),
1236    Spatial,
1237}
1238
1239impl RingFrame {
1240    fn is_ring(self) -> bool {
1241        !matches!(self, RingFrame::Open)
1242    }
1243}
1244
1245/// The ring frame a path's stations close on, read off its classification.
1246fn ring_frame(path: &SweepPath, tangents: &[Vec3]) -> Result<RingFrame, KernelRefusal> {
1247    Ok(match (path.closed, path.planar) {
1248        (false, _) => RingFrame::Open,
1249        (true, Some(normal)) => RingFrame::Planar(ring_normal(normal, tangents)?),
1250        (true, None) => RingFrame::Spatial,
1251    })
1252}
1253
1254/// What a CLOSED sweep did to make its section meet itself after one lap — the
1255/// applied twist the frame-closure policy REPORTS.
1256///
1257/// THE POLICY. Carried once round a closed path, the section frame comes back
1258/// ROLLED about the start tangent by the path's HOLONOMY. That angle is not a
1259/// defect of the sampling: the frame is parallel transport of the section's
1260/// axes in the path's normal plane, which is parallel transport on the unit
1261/// sphere along the path's TANGENT INDICATRIX, so by Gauss–Bonnet the roll is
1262/// the solid angle that indicatrix encloses, modulo `2π`. A planar path's
1263/// indicatrix runs along one great circle and encloses a hemisphere — `2π`,
1264/// the identity — which is why a planar ring closes on its own; a spatial one
1265/// generally does not. (A curve lying ON a sphere reads zero too: the radial
1266/// direction is itself rotation-minimizing along any such curve. Its enclosed
1267/// solid angle is not its holonomy; its indicatrix's is.)
1268///
1269/// The sweep closes the ring with the SMALLEST roll that does it: the
1270/// counter-twist `−holonomy`, wrapped to `(−π, π]`.
1271///   - SMOOTH lane: laid down LINEARLY IN ARC LENGTH over the stations, the wrap
1272///     step from the last station back to station 0 included, so every span —
1273///     the seam span too — rolls at the same rate and the closed loft sees no
1274///     seam at all. A uniform rate is the distribution with the smallest peak
1275///     rate and the smallest `∫(roll rate)² ds`.
1276///   - CORNERED lane (`sweep_topology/miter.rs`): shared over the SEGMENTS in
1277///     proportion to their length, each share laid down over its segment's
1278///     untrimmed middle — a roll AT a mitre would pull the shared loop apart —
1279///     and nothing at all when the untwisted lap already closes within the
1280///     lane's own weld floor.
1281///
1282/// A REQUESTED twist rides on top of that counter-twist and is laid down the same
1283/// way, so `applied_twist = requested_twist − holonomy` (or `requested_twist` alone
1284/// where no counter-twist is needed). It closes only as a rotational symmetry of
1285/// the section about the path, `2π·n/k` for a section with `k` of them, and is
1286/// refused by name otherwise ([`crate::SWEEP_TWIST_CLOSURE_REFUSAL`]). A
1287/// FRACTIONAL turn on a symmetric section lands each wall on a different section
1288/// curve than it left: `curve_shift`.
1289///
1290/// `holonomy` is what the untwisted frame measures; `applied_twist` is what was
1291/// laid down. All three angles are radians, right-handed about the path tangent.
1292#[derive(Debug, Clone, Copy, PartialEq)]
1293pub struct SweepClosure {
1294    /// The roll the UNTWISTED frame returns with after one lap, right-handed
1295    /// about the start tangent, wrapped to `(−π, π]`. Zero for a planar path.
1296    pub holonomy: f64,
1297    /// The twist the caller asked for, snapped to the section symmetry it closes
1298    /// on (it matched at round-off). Zero for an untwisted sweep.
1299    pub requested_twist: f64,
1300    /// The twist laid down over the lap: the requested twist plus the
1301    /// counter-twist `−holonomy`, which is zero where the lane closes without one
1302    /// (a planar path, or a frame whose untwisted lap already closes within the
1303    /// weld floor).
1304    pub applied_twist: f64,
1305    /// How far along the section's curve list one lap carries each curve: the
1306    /// wall leaving section curve `j` arrives on curve `(j + curve_shift) mod m`.
1307    /// Zero for no twist and for a whole number of turns. The curves are counted
1308    /// in the order the builder carries them, which on the MITRE lane is the
1309    /// section's order after its winding is made counter-clockwise about the path.
1310    pub curve_shift: usize,
1311}
1312
1313/// The CLOSURE a sweep of `profile` along `path` applies — the frame-closure
1314/// policy's report, exposed so a caller can read the twist a closed sweep laid
1315/// down (see [`SweepClosure`]). `None` for an OPEN path, which has no lap to
1316/// close.
1317///
1318/// Reads the very construction the sweep builds, not a second measurement of
1319/// it: a cornered polyline asks the mitre lane's own frame plan (its placed
1320/// section, its rings, its weld floor), and any other closed path asks the
1321/// smooth lane's own stations and frames at `stations` — the budget the sweep
1322/// was given (32 for [`sweep_profile_along_chain`] untwisted, the caller's for
1323/// [`sweep_profile_along_chain_with_stations`]). Whatever the builder would
1324/// refuse, this refuses with the same words, a requested `twist_angle` that does
1325/// not close included.
1326pub fn sweep_closure(
1327    profile: &[NurbsCurve],
1328    path: &SweepPath,
1329    placement_mode: SectionPlacement,
1330    stations: usize,
1331    twist_angle: f64,
1332) -> Result<Option<SweepClosure>, KernelRefusal> {
1333    if !path.closed {
1334        return Ok(None);
1335    }
1336    let placement = resolve_placement(profile, None, placement_mode)?;
1337    if path.cornered_polyline() {
1338        let (section, section_normal, _) = mitre_section(profile, placement, placement_mode, path)?;
1339        return super::miter::mitred_frame_closure(&section, section_normal, path, twist_angle)
1340            .map(Some);
1341    }
1342    let (
1343        StationSamples {
1344            points,
1345            tangents,
1346            segments,
1347            ..
1348        },
1349        _,
1350    ) = chain_stations(
1351        path.curves.as_slice(),
1352        path.closed,
1353        SamplerLane::Chain,
1354        stations.clamp(2, 1024),
1355        SWEEP_DEFAULT_TOLERANCE,
1356        None,
1357    )?;
1358    let screw = Some((segments.as_slice(), path)).filter(|_| placement_mode == SectionPlacement::Rigid);
1359    let closure = ring_frame(path, &tangents)?;
1360    let (section, _) = place_section(profile, placement, placement_mode, points[0], tangents[0])?;
1361    let requested = ring_closing_twist(&section, &points, &tangents, twist_angle)?;
1362    Ok(station_frames(&points, &tangents, closure, screw, requested)?.2)
1363}
1364
1365/// The requested twist a RING closes on ([`closing_twist`]), read off the
1366/// section as placed at station 0, about the path's first tangent, against the
1367/// ring's own position floor: `1e-6` of the lap's chord length, the floor the
1368/// mitred frame measures its own closure against.
1369fn ring_closing_twist(
1370    section: &[NurbsCurve],
1371    points: &[Vec3],
1372    tangents: &[Vec3],
1373    twist_angle: f64,
1374) -> Result<ClosingTwist, KernelRefusal> {
1375    let lap: f64 = (0..points.len())
1376        .map(|index| points[(index + 1) % points.len()].sub(points[index]).length())
1377        .sum();
1378    closing_twist(section, points[0], tangents[0], twist_angle, 1e-6 * lap)
1379}
1380
1381/// The placed section a MITRED sweep carries and its plane normal, with the
1382/// first segment's chord direction — shared by the builder and by
1383/// [`sweep_closure`], so the instrument reads the section the frame is built
1384/// from.
1385fn mitre_section(
1386    profile: &[NurbsCurve],
1387    placement: ProfileAnchor,
1388    placement_mode: SectionPlacement,
1389    path: &SweepPath,
1390) -> Result<(Vec<NurbsCurve>, Vec3, Vec3), KernelRefusal> {
1391    let [t0, t1] = path.curves[0].domain().or_refuse(KernelStage::Collect, "domain")?;
1392    let start = path.curves[0].evaluate(t0).or_refuse(KernelStage::Collect, "evaluate")?;
1393    // The CHORD direction, which is both the first station's tangent (a
1394    // straight segment's derivative is its chord) and the direction the
1395    // mitre builder sweeps along, so the placed section is square to the
1396    // same vector the construction uses.
1397    let tangent = path.curves[0]
1398        .evaluate(t1).or_refuse(KernelStage::Collect, "evaluate")?
1399        .sub(start)
1400        .normalized()
1401        .map_err(|_| {
1402            KernelRefusal::input(
1403                KernelStage::Collect,
1404                "segment_length",
1405                "sweepSolid: path segment 0 has zero length",
1406            )
1407        })?;
1408    let (section, section_normal) =
1409        place_section(profile, placement, placement_mode, start, tangent)?;
1410    Ok((section, section_normal, tangent))
1411}
1412
1413/// The station frames §3 places its sections on, extracted so the tight-bend
1414/// INSTRUMENT ([`sweep_bend_profile`]) reads the frame the sweep will use — the
1415/// section's reach into a bend depends on how the section is ROLLED about the
1416/// path, so a second frame that merely agreed on a circle would be a different
1417/// measurement on anything else.
1418///
1419/// `screw` is the chain's segment-of-station map and the path whose
1420/// [`SweepPath::screw_axes`] it indexes, passed only by the `Rigid` placement.
1421/// A station on a HELIX segment is framed off the helix's own axis instead of
1422/// transported (see [`screw_reference`]); every other station takes the RMF step
1423/// from its predecessor, so the two compose across a joint in either direction.
1424///
1425/// The third value is the ring's CLOSURE report: `None` for an open run, zero
1426/// for a planar ring, and the measured holonomy with the counter-twist that
1427/// closes it for a spatial one — whose axes are returned already twisted.
1428///
1429/// `requested` is a RING's requested twist, already known to close
1430/// ([`closing_twist`]). It is laid down in the ring's frames over the whole lap,
1431/// the wrap chord included, together with any counter-twist, so the seam span
1432/// rolls at the rate every other span does. An OPEN run ignores it: its twist is
1433/// laid down by the placement, over the stations it has.
1434fn station_frames(
1435    points: &[Vec3],
1436    tangents: &[Vec3],
1437    closure: RingFrame,
1438    screw: Option<(&[usize], &SweepPath)>,
1439    requested: ClosingTwist,
1440) -> Result<(Vec<Vec3>, Vec<Vec3>, Option<SweepClosure>), KernelRefusal> {
1441    match closure {
1442        RingFrame::Open => {
1443            let (r_axes, s_axes) = transported_frames(points, tangents, screw)?;
1444            Ok((r_axes, s_axes, None))
1445        }
1446        RingFrame::Planar(normal) => {
1447            let mut r_axes = Vec::with_capacity(points.len());
1448            let mut s_axes = Vec::with_capacity(points.len());
1449            for tangent in tangents {
1450                // Project out any tangent component and re-normalize, so the frame is
1451                // orthonormal even where the fitted plane and the sampled tangent
1452                // disagree in the last bits.
1453                let r = normal
1454                    .sub(tangent.scale(normal.dot(*tangent)))
1455                    .normalized()
1456                    .map_err(|_| {
1457                        KernelRefusal::internal(
1458                            KernelStage::Classify,
1459                            "planar_frame",
1460                            "sweepSolid: the closed path's plane normal is parallel to its tangent",
1461                        )
1462                    })?;
1463                s_axes.push(tangent.cross(r).normalized().or_refuse(KernelStage::Classify, "normalized")?);
1464                r_axes.push(r);
1465            }
1466            if requested.twist != 0.0 {
1467                roll_over_the_lap(points, &mut r_axes, &mut s_axes, requested.twist)?;
1468            }
1469            Ok((
1470                r_axes,
1471                s_axes,
1472                Some(SweepClosure {
1473                    holonomy: 0.0,
1474                    requested_twist: requested.twist,
1475                    applied_twist: requested.twist,
1476                    curve_shift: requested.shift,
1477                }),
1478            ))
1479        }
1480        RingFrame::Spatial => {
1481            let (r_axes, s_axes, closure) =
1482                ring_closure_frames(points, tangents, screw, requested)?;
1483            Ok((r_axes, s_axes, Some(closure)))
1484        }
1485    }
1486}
1487
1488/// The frames of a closed SPATIAL ring: the transported frame, counter-twisted
1489/// by its own holonomy so the section meets itself (see [`SweepClosure`]).
1490///
1491/// MEASURED, not assumed. The run is transported ONE STEP FURTHER than an open
1492/// run goes — from the last station back to station 0, by the very rule every
1493/// other step takes (the RMF, or a helix segment's screw frame under `Rigid`) —
1494/// and the returned axis is compared with station 0's: the signed angle between
1495/// them, right-handed about the start tangent, is the holonomy `h`.
1496///
1497/// Then station `k`, at chord-length `s_k` round a lap of chord length `L`
1498/// (the wrap chord included), is rolled about its tangent by `φ_k = −h·s_k/L`.
1499/// Rolling about the tangent commutes with the transport step (each step is a
1500/// rotation carrying one tangent onto the next, and it carries a roll about the
1501/// first onto the same roll about the second), so the frame transported from
1502/// the last twisted station across the wrap arrives rolled by
1503/// `h − h·s_{n−1}/L`, and station 0 sits `−h·(L − s_{n−1})/L` further on — the
1504/// same rate as every other span. The ring closes with no seam to skin.
1505///
1506/// No new station law: the closed lane already floors its budget at 16 stations
1507/// per quarter turn of the path's TURNING, and a closed curve turns at least
1508/// `2π` (Fenchel), so a lap carries at least 64 stations. The largest roll this
1509/// lays down is `π`, under 3° a station — finer than the 16 per quarter turn a
1510/// requested twist gets.
1511///
1512/// A REQUESTED twist `T` that closes ([`closing_twist`]) rides on the same rate:
1513/// each station rolls by `(T − h)·s_k/L`, so the section comes back from the lap
1514/// rolled by `T` alone, onto itself. [`sweep_profile_along_chain`] sizes the
1515/// station budget for `|T| + π`.
1516fn ring_closure_frames(
1517    points: &[Vec3],
1518    tangents: &[Vec3],
1519    screw: Option<(&[usize], &SweepPath)>,
1520    requested: ClosingTwist,
1521) -> Result<(Vec<Vec3>, Vec<Vec3>, SweepClosure), KernelRefusal> {
1522    let stations = points.len();
1523    if stations < 2 {
1524        return Err(KernelRefusal::internal(
1525            KernelStage::Collect,
1526            "station_run",
1527            "sweepSolid: need at least 2 stations",
1528        ));
1529    }
1530    // The lap with its wrap: station 0 again, arriving as the LAST segment's end.
1531    let mut lap_points = points.to_vec();
1532    lap_points.push(points[0]);
1533    let mut lap_tangents = tangents.to_vec();
1534    lap_tangents.push(tangents[0]);
1535    let lap_segments: Option<Vec<usize>> = screw.map(|(segments, _)| {
1536        let mut extended = segments.to_vec();
1537        extended.push(segments[stations - 1]);
1538        extended
1539    });
1540    let lap_screw = match (&lap_segments, screw) {
1541        (Some(segments), Some((_, path))) => Some((segments.as_slice(), path)),
1542        _ => None,
1543    };
1544    let (mut r_axes, mut s_axes) = transported_frames(&lap_points, &lap_tangents, lap_screw)?;
1545    let returned = r_axes.pop().expect("a lap has a wrap station");
1546    s_axes.pop();
1547    let holonomy = returned.dot(s_axes[0]).atan2(returned.dot(r_axes[0]));
1548
1549    let applied = if requested.twist == 0.0 {
1550        -holonomy
1551    } else {
1552        requested.twist - holonomy
1553    };
1554    roll_over_the_lap(points, &mut r_axes, &mut s_axes, applied)?;
1555    Ok((
1556        r_axes,
1557        s_axes,
1558        SweepClosure {
1559            holonomy,
1560            requested_twist: requested.twist,
1561            applied_twist: applied,
1562            curve_shift: requested.shift,
1563        },
1564    ))
1565}
1566
1567/// Roll a ring's station frames about their tangents by `roll` over the lap,
1568/// linearly in chord length with the WRAP chord included: station `k` at `s_k`
1569/// of a lap of length `L` rolls by `roll·s_k/L`.
1570fn roll_over_the_lap(
1571    points: &[Vec3],
1572    r_axes: &mut [Vec3],
1573    s_axes: &mut [Vec3],
1574    roll: f64,
1575) -> Result<(), KernelRefusal> {
1576    let stations = points.len();
1577    let mut travelled = Vec::with_capacity(stations);
1578    let mut length = 0.0;
1579    for index in 0..stations {
1580        travelled.push(length);
1581        length += points[(index + 1) % stations].sub(points[index]).length();
1582    }
1583    if length <= 0.0 {
1584        return Err(KernelRefusal::internal(
1585            KernelStage::Classify,
1586            "lap_length",
1587            "sweepSolid: the closed path has zero length",
1588        ));
1589    }
1590    for station in 0..stations {
1591        let phi = roll * travelled[station] / length;
1592        let (sin_phi, cos_phi) = phi.sin_cos();
1593        let (r, s) = (r_axes[station], s_axes[station]);
1594        r_axes[station] = r.scale(cos_phi).add(s.scale(sin_phi));
1595        s_axes[station] = s.scale(cos_phi).sub(r.scale(sin_phi));
1596    }
1597    Ok(())
1598}
1599
1600/// The TRANSPORTED frames of a station run: seeded on an arbitrary perpendicular
1601/// to the first tangent and carried station to station — by the RMF, or by a
1602/// helix segment's screw frame under `Rigid` (see [`station_frames`]).
1603fn transported_frames(
1604    points: &[Vec3],
1605    tangents: &[Vec3],
1606    screw: Option<(&[usize], &SweepPath)>,
1607) -> Result<(Vec<Vec3>, Vec<Vec3>), KernelRefusal> {
1608    let stations = points.len();
1609    let mut r_axes = Vec::with_capacity(stations);
1610    let mut s_axes = Vec::with_capacity(stations);
1611    {
1612        let r0 = tangents[0].perpendicular().or_refuse(KernelStage::Classify, "perpendicular")?; // any unit vector ⟂ T0
1613        s_axes.push(tangents[0].cross(r0).normalized().or_refuse(KernelStage::Classify, "normalized")?);
1614        r_axes.push(r0);
1615        // The helix segment the running roll was fixed for, and that roll.
1616        let mut roll: Option<(usize, f64)> = None;
1617        for index in 0..stations - 1 {
1618            let t_next = tangents[index + 1];
1619            let helix = screw.and_then(|(segments, path)| {
1620                let segment = segments[index + 1];
1621                path.screw_axes[segment].map(|axis| (segment, axis, path))
1622            });
1623            let r_next = match helix {
1624                None => rmf_step(
1625                    r_axes[index],
1626                    tangents[index],
1627                    t_next,
1628                    points[index + 1].sub(points[index]),
1629                )
1630                .ok_or_else(|| {
1631                    KernelRefusal::internal(
1632                        KernelStage::Classify,
1633                        "frame_step",
1634                        format!("sweepSolid: frame degenerated at station {index}"),
1635                    )
1636                })?,
1637                Some((segment, axis, path)) => {
1638                    // The roll is fixed ONCE per helix segment, at the station it
1639                    // departs from — station 0, or the joint the previous segment
1640                    // arrived at — so the incoming frame continues without a snap.
1641                    let phi = match roll {
1642                        Some((fixed, phi)) if fixed == segment => phi,
1643                        _ => {
1644                            let tangent = tangents[index];
1645                            let reference =
1646                                screw_reference(axis, tangent, path.name(segment), index)?;
1647                            let r = r_axes[index];
1648                            let phi = tangent.dot(reference.cross(r)).atan2(reference.dot(r));
1649                            roll = Some((segment, phi));
1650                            phi
1651                        }
1652                    };
1653                    let reference = screw_reference(axis, t_next, path.name(segment), index + 1)?;
1654                    let (sin_phi, cos_phi) = phi.sin_cos();
1655                    reference
1656                        .scale(cos_phi)
1657                        .add(t_next.cross(reference).scale(sin_phi))
1658                }
1659            };
1660            s_axes.push(t_next.cross(r_next).normalized().or_refuse(KernelStage::Classify, "normalized")?);
1661            r_axes.push(r_next);
1662        }
1663    }
1664    Ok((r_axes, s_axes))
1665}
1666
1667/// A HELIX station's reference axis: the screw axis with its tangent component
1668/// removed, `normalize(W − (W·T)T)`.
1669///
1670/// Why this and not the transported frame: a helix is carried into itself by
1671/// ONE rigid motion — the screw about its axis — and that motion fixes both the
1672/// axis and the tangent's angle to it, so the axis' projection onto the normal
1673/// plane is the same body-fixed direction at every station. A frame built on it
1674/// IS the screw, so `R_k = F_k·F_0ᵀ` carries the profile about the coil's axis
1675/// and up its pitch. A rotation-minimizing frame has no spin about the tangent,
1676/// while the screw's frame spins at the helix's torsion `τ`, so the RMF rolls
1677/// away from it by `∫τ ds` — the rotation the user saw. On a TAPERED helix the
1678/// tangent's angle to the axis drifts with the radius, and this frame keeps the
1679/// section square to the axis all the same, which is what a tapered coil is.
1680///
1681/// Undefined only where the path runs ALONG its own axis, which a helix of
1682/// positive radius never does; refused by name there rather than guessed.
1683fn screw_reference(axis: Vec3, tangent: Vec3, segment: &str, station: usize) -> Result<Vec3, KernelRefusal> {
1684    axis.sub(tangent.scale(axis.dot(tangent)))
1685        .normalized()
1686        .map_err(|_| {
1687            KernelRefusal::ill_posed(
1688                KernelStage::Classify,
1689                "screw_reference",
1690                format!(
1691                "sweepSolid: path segment '{segment}' runs along its own helix axis at station \
1692                 {station}, so the screw motion that carries the section has no direction \
1693                 about the path there"
1694                ),
1695            )
1696        })
1697}
1698
1699/// The stations a path is sampled at, and what each one carries: the point, the
1700/// unit tangent, and the CURVATURE VECTOR `κ·N̂` — the path's own bend there,
1701/// measured from the curve rather than differenced off the station polyline,
1702/// because it is the number the tight-bend refusal quotes.
1703pub struct StationSamples {
1704    pub points: Vec<Vec3>,
1705    pub tangents: Vec<Vec3>,
1706    /// `κ·N̂` per station: its length is the curvature and its direction points
1707    /// at the centre of the osculating circle. Zero on a straight piece.
1708    pub curvatures: Vec<Vec3>,
1709    /// The path SEGMENT each station belongs to. A joint station is emitted by
1710    /// the segment ARRIVING at it, so it carries that segment's index.
1711    pub segments: Vec<usize>,
1712    /// Where each station sits for the span AFTER it: the segment it departs
1713    /// into and its parameter there ([`StationParam`]).
1714    pub params: Vec<StationParam>,
1715}
1716
1717/// The CURVATURE VECTOR of a curve from its first two derivatives:
1718///
1719/// ```text
1720///     κ·N̂ = (r̈ − (r̈·T̂)T̂) / |ṙ|²,      T̂ = ṙ/|ṙ|
1721/// ```
1722///
1723/// the component of the second derivative perpendicular to the tangent over the
1724/// squared speed — the reparameterization-invariant form, so a non-uniformly
1725/// parameterized path reads its own geometric bend rather than its
1726/// parameterization's. A degree-1 piece has a zero second derivative
1727/// (`derivatives` pads past the degree), so a straight segment reads exactly
1728/// zero and needs no special case.
1729pub fn curvature_vector(first: Vec3, second: Vec3) -> Vec3 {
1730    let speed_squared = first.dot(first);
1731    if speed_squared <= 0.0 {
1732        return Vec3::default();
1733    }
1734    let tangent = first.scale(1.0 / speed_squared.sqrt());
1735    second
1736        .sub(tangent.scale(second.dot(tangent)))
1737        .scale(1.0 / speed_squared)
1738}
1739
1740/// Which sampler asked for the stations — the two differ in their FLOOR and
1741/// in the words of the degenerate-tangent refusal, both pinned by callers.
1742#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1743enum SamplerLane {
1744    /// The chain sweep: every segment floored at its own turning, 16 stations
1745    /// a quarter turn.
1746    Chain,
1747    /// The single-curve builders (`sweep_profile_along_path` and family): the
1748    /// budget [`path_turning_stations`] hands them, uniform in the parameter,
1749    /// exactly as they always sampled — no turning floor on top, so an
1750    /// untwisted single-curve sweep that reads inside the tolerance is
1751    /// bit-identical to the tree before refinement existed.
1752    SingleCurve,
1753}
1754
1755/// Sample a CHAIN as ONE trajectory: the per-segment arc-length estimate, the
1756/// station budget it implies, and the stations themselves — then REFINE the
1757/// stations where the loft's own interpolant of them would stand off the path
1758/// by more than `tolerance` (`sweep_topology/stations.rs`).
1759///
1760/// Extracted from the chain sweep so the tight-bend INSTRUMENT
1761/// ([`sweep_bend_profile`]) measures the very stations the sweep lofts through,
1762/// rather than a second sampling that agrees with it today.
1763///
1764/// STATION BUDGET. `stations` are distributed across the segments in proportion
1765/// to estimated ARC LENGTH (chord sums over 16 samples per curve), floored at 2
1766/// per segment so a short fillet between two long lines still carries its
1767/// curvature, and — on the chain lane — at the segment's own TURNING at 16
1768/// stations per quarter turn, the density the twisted builder already uses.
1769/// That floor is the measured case behind the error rule: shared out by length
1770/// alone, a rounded rectangle's four short corner arcs got the 2-station floor
1771/// and the ring cut the corners, 6.2 % under `A · perimeter` on a 30 × 18 path
1772/// with `r = 4`; the turning floor took the same path to 4.8e-4. The floor is
1773/// kept as the STARTING budget on both lanes; the error rule below is what
1774/// takes the rest.
1775///
1776/// WHAT THE ERROR RULE REPLACES. Until 2026-09-30 an OPEN path had its straight
1777/// segments LIFTED to the density its turning segments were floored at
1778/// (`floor_total × straight length / curved length`), because a coil with a
1779/// straight lead of 2 stations bowed through the lead (2.7e-5 off Pappus on a
1780/// lead of 10, 5.0e-4 on 100). Measured on 2026-09-30, that lift put a pipe of
1781/// two 100-long legs round a 2-radius quarter bend at the 1024-station cap
1782/// (correct, at 25× the stations it needs), and REFUSED the same pipe at
1783/// `r = 1.5`, and any spatial variant, as "past the 1024-station cap" — a
1784/// legitimate sweep refused for its own budget. The rule below reads the bow
1785/// where it is and puts stations there; the lead of 100 gets a handful next to
1786/// the joint instead of a thousand along its length.
1787///
1788/// THE RULE. The loft interpolates each control-point column with one cubic
1789/// through the stations at shared chord parameters; the same fit through the
1790/// station POINTS is the loft's centre track. Per span, the track's distance
1791/// from the true path at the quarter points is measured
1792/// (`stations::spine_deviations`); a span over `tolerance` is split into
1793/// `ceil((deviation / tolerance)^(1/4))` equal parameter steps (the cubic's
1794/// `h⁴` law), and the run is re-measured. At most [`SWEEP_REFINEMENT_ROUNDS`]
1795/// rounds; a round that would pass the [`SWEEP_MAX_STATIONS`] cap refines the
1796/// worst spans as far as the cap allows and the budget records `at_cap` — the
1797/// sweep still builds and its report says the tolerance was not met.
1798/// `BREP_SWEEP_STATION_REFINEMENT=0` switches the rule off (the bite proof).
1799///
1800/// The shared endpoint of two adjacent segments is sampled ONCE, not twice — a
1801/// duplicated station would land in the RMF's coincident-step branch and waste
1802/// a section on zero advance. A CLOSED path drops one more station for the
1803/// same reason: its last station IS its first.
1804fn chain_stations(
1805    chain: &[NurbsCurve],
1806    closed: bool,
1807    lane: SamplerLane,
1808    stations: usize,
1809    tolerance: f64,
1810    break_after: Option<&[bool]>,
1811) -> Result<(StationSamples, StationBudget), KernelRefusal> {
1812    let position_tolerance = 1e-6;
1813    // --- Per-segment arc-length estimate, and the domain each one is sampled
1814    //     over. A degenerate domain is refused here rather than producing a
1815    //     silently collapsed station block.
1816    //
1817    //     Each segment's TURNING — the total angle its tangent sweeps — is measured
1818    //     too, because that, not its length, is what decides how many stations it
1819    //     needs (see the floor below).
1820    let mut domains = Vec::with_capacity(chain.len());
1821    let mut lengths = Vec::with_capacity(chain.len());
1822    let mut turning = Vec::with_capacity(chain.len());
1823    for (index, curve) in chain.iter().enumerate() {
1824        let [t0, t1] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
1825        if (t1 - t0).abs() <= position_tolerance {
1826            return Err(KernelRefusal::input(
1827                KernelStage::Collect,
1828                "path_domain",
1829                match lane {
1830                    SamplerLane::Chain => format!("sweepSolid: path segment {index} has a degenerate domain"),
1831                    SamplerLane::SingleCurve => "sweepSolid: path domain is degenerate".to_string(),
1832                },
1833            ));
1834        }
1835        let mut length = 0.0;
1836        let mut previous = curve.evaluate(t0).or_refuse(KernelStage::Collect, "evaluate")?;
1837        for sample in 1..=16 {
1838            let point = curve.evaluate(t0 + (t1 - t0) * sample as f64 / 16.0).or_refuse(KernelStage::Collect, "evaluate")?;
1839            length += point.sub(previous).length();
1840            previous = point;
1841        }
1842        domains.push([t0, t1]);
1843        lengths.push(length);
1844        // `segment_turning` is a stringly reading of the curve's unit tangents;
1845        // a failure there is a degenerate tangent, which is the path's fault.
1846        // The single-curve lane never reads it: its budget was decided by
1847        // [`path_turning_stations`] and a path it cannot read is refused by the
1848        // sampling below, in that lane's own words.
1849        turning.push(match lane {
1850            SamplerLane::Chain => segment_turning(curve, [t0, t1]).map_err(|error| {
1851                KernelRefusal::input(
1852                    KernelStage::Classify,
1853                    "path_tangent",
1854                    format!("sweepSolid: path tangent is degenerate on segment {index}: {error}"),
1855                )
1856            })?,
1857            SamplerLane::SingleCurve => 0.0,
1858        });
1859    }
1860    let total_length: f64 = lengths.iter().sum();
1861    if total_length <= position_tolerance {
1862        return Err(KernelRefusal::input(
1863            KernelStage::Collect,
1864            "path_length",
1865            "sweepSolid: path chain has zero length",
1866        ));
1867    }
1868
1869    // --- Station budget per segment: proportional to arc length, floored at 2
1870    //     (a segment needs its two ends) and at the segment's turning, and the
1871    //     remainder handed to the longest segment so the totals land exactly on
1872    //     `stations`.
1873    let floors: Vec<usize> = turning
1874        .iter()
1875        .map(|turn| ((turn / std::f64::consts::FRAC_PI_2) * 16.0).ceil() as usize)
1876        .collect();
1877    let mut budget: Vec<usize> = lengths
1878        .iter()
1879        .zip(&floors)
1880        .map(|(length, floor)| {
1881            let share = (stations as f64 * length / total_length).round() as usize;
1882            share.max(*floor).max(2)
1883        })
1884        .collect();
1885    // Each interior joint shares one station between its two segments, so the
1886    // emitted total is sum(budget) - (segments - 1). A CLOSED path drops its very
1887    // last station too — it is the first one — so it emits one fewer again.
1888    let shared = chain.len() - 1 + usize::from(closed);
1889    let emitted: usize = budget.iter().sum::<usize>() - shared;
1890    // The 2-per-segment floor means a chain of n segments emits at least n+1
1891    // stations, so a long enough chain cannot be held under the loft's station
1892    // cap by any distribution. The loft's interpolation solve is O(stations³)
1893    // per control column, so silently accepting such a path would look like a
1894    // hang. Refuse with the count instead — the same honesty the twist cap uses.
1895    if emitted > SWEEP_MAX_STATIONS {
1896        return Err(KernelRefusal::unsupported(
1897            KernelStage::Collect,
1898            "station_cap",
1899            format!(
1900            "sweepSolid: a {}-segment path needs at least {emitted} stations, past the \
1901             {SWEEP_MAX_STATIONS}-station cap the loft solve can carry; sweep it in fewer, \
1902             longer pieces",
1903            chain.len()
1904            ),
1905        ));
1906    }
1907    if emitted < stations {
1908        let longest = lengths
1909            .iter()
1910            .enumerate()
1911            .max_by(|a, b| a.1.total_cmp(b.1))
1912            .map(|(index, _)| index)
1913            .unwrap_or(0);
1914        budget[longest] += stations - emitted;
1915    }
1916
1917    // --- The parameters each segment is sampled at: uniform over its domain at
1918    //     its budget, then refined where the measured deviation says so.
1919    let mut per_segment: Vec<Vec<f64>> = domains
1920        .iter()
1921        .zip(&budget)
1922        .map(|([t0, t1], count)| {
1923            (0..*count)
1924                .map(|sample| t0 + (t1 - t0) * sample as f64 / (count - 1) as f64)
1925                .collect()
1926        })
1927        .collect();
1928    let initial = per_segment.iter().map(Vec::len).sum::<usize>() - shared;
1929    let mut budget = StationBudget {
1930        initial,
1931        stations: initial,
1932        rounds: 0,
1933        at_cap: false,
1934        rounds_exhausted: false,
1935    };
1936    let refine = tolerance.is_finite() && tolerance > 0.0 && super::stations::refinement_enabled();
1937    let mut samples = sample_chain(chain, closed, lane, &domains, &per_segment)?;
1938    if refine {
1939        loop {
1940            let breaks = break_after.map(|after| station_breaks(&samples, after));
1941            let deviations = super::stations::spine_deviations(chain, &samples.params, &samples.points, closed, breaks.as_deref())
1942                .map_err(|error| {
1943                    KernelRefusal::internal(
1944                        KernelStage::Refine,
1945                        "station_deviation",
1946                        format!("sweepSolid: the station deviation could not be read: {error}"),
1947                    )
1948                })?;
1949            if deviations.iter().all(|deviation| *deviation <= tolerance) {
1950                break;
1951            }
1952            if budget.rounds >= SWEEP_REFINEMENT_ROUNDS {
1953                budget.rounds_exhausted = true;
1954                break;
1955            }
1956            let emitted = samples.points.len();
1957            let (inserted, at_cap) = super::stations::refine_parameters(
1958                chain,
1959                &mut per_segment,
1960                &samples.params,
1961                &deviations,
1962                tolerance,
1963                closed,
1964                emitted,
1965                breaks.as_deref(),
1966            )
1967            .map_err(|error| {
1968                KernelRefusal::internal(
1969                    KernelStage::Refine,
1970                    "station_refinement",
1971                    format!("sweepSolid: the stations could not be refined: {error}"),
1972                )
1973            })?;
1974            budget.at_cap |= at_cap;
1975            if inserted == 0 {
1976                break;
1977            }
1978            budget.rounds += 1;
1979            samples = sample_chain(chain, closed, lane, &domains, &per_segment)?;
1980            if at_cap {
1981                break;
1982            }
1983        }
1984    }
1985    budget.stations = samples.points.len();
1986    Ok((samples, budget))
1987}
1988
1989/// Sample the chain at `per_segment`'s parameters as ONE trajectory: the
1990/// point, unit tangent and curvature vector at every station, the segment it
1991/// arrived on, and where it sits ([`StationParam`]).
1992fn sample_chain(
1993    chain: &[NurbsCurve],
1994    closed: bool,
1995    lane: SamplerLane,
1996    domains: &[[f64; 2]],
1997    per_segment: &[Vec<f64>],
1998) -> Result<StationSamples, KernelRefusal> {
1999    let mut points: Vec<Vec3> = Vec::new();
2000    let mut tangents: Vec<Vec3> = Vec::new();
2001    let mut curvatures: Vec<Vec3> = Vec::new();
2002    let mut segments: Vec<usize> = Vec::new();
2003    let mut params: Vec<StationParam> = Vec::new();
2004    for (index, curve) in chain.iter().enumerate() {
2005        let [t0, _] = domains[index];
2006        let list = &per_segment[index];
2007        let count = list.len();
2008        // Skip the first sample of every segment after the first: that station
2009        // is the joint, already emitted as the previous segment's last. On a
2010        // CLOSED path the LAST segment's last sample is skipped too — it is
2011        // station 0, and a ring that emitted it twice would interpolate a
2012        // zero-length span across its own seam.
2013        let first = usize::from(index > 0);
2014        if first == 1 {
2015            // THE JOINT reads the TIGHTER of the two pieces that meet there. A
2016            // G1 joint is tangent-continuous, not curvature-continuous — a line
2017            // running into a cubic hands over at κ = 0 and the cubic starts at
2018            // its own spike — and the station is emitted once, by the piece that
2019            // ARRIVES. Left as that, a path whose tightest bend sits at the
2020            // START of a curved piece would quote the straight piece's κ = 0 and
2021            // the bend would go unnamed; on the wire harness's own span the two
2022            // ends are mirror images and only ONE of them was being read.
2023            let derivatives = curve.derivatives_small(t0, 2).or_refuse(KernelStage::Collect, "derivatives")?;
2024            let (_, arriving) = station_reading(curve, t0, PathSide::Departing, &derivatives)
2025                .map_err(|fault| fault.refusal(&format!("the start of segment {index}"), t0))?;
2026            if let Some(departing) = curvatures.last_mut() {
2027                if arriving.length() > departing.length() {
2028                    *departing = arriving;
2029                }
2030            }
2031            // The joint station departs into THIS segment.
2032            if let Some(joint) = params.last_mut() {
2033                *joint = StationParam { segment: index, t: t0 };
2034            }
2035        }
2036        let last = count - usize::from(closed && index + 1 == chain.len());
2037        for (sample, &t) in list.iter().enumerate().take(last).skip(first) {
2038            let derivatives = curve.derivatives_small(t, 2).or_refuse(KernelStage::Collect, "derivatives")?;
2039            // A station on a STATIONARY parameter reads the one-sided limit:
2040            // the side the span after it lies on, or the arriving side at a
2041            // segment's end (whose station departs into the next segment).
2042            let side = if sample + 1 == count { PathSide::Arriving } else { PathSide::Departing };
2043            let (tangent, curvature) = station_reading(curve, t, side, &derivatives).map_err(|fault| {
2044                fault.refusal(
2045                    &match lane {
2046                        SamplerLane::Chain => format!("station {sample} of segment {index}"),
2047                        SamplerLane::SingleCurve => format!("station {sample}"),
2048                    },
2049                    t,
2050                )
2051            })?;
2052            points.push(derivatives[0]);
2053            tangents.push(tangent);
2054            curvatures.push(curvature);
2055            segments.push(index);
2056            params.push(StationParam { segment: index, t });
2057        }
2058    }
2059    // A CLOSED path's seam is a joint like any other, and station 0 is the only
2060    // one whose two sides are sampled at opposite ends of the loop: the last
2061    // segment's end is station 0, and it was dropped rather than emitted.
2062    if closed {
2063        if let (Some(curve), Some(domain)) = (chain.last(), domains.last()) {
2064            let derivatives = curve.derivatives_small(domain[1], 2).or_refuse(KernelStage::Collect, "derivatives")?;
2065            let (_, arriving) = station_reading(curve, domain[1], PathSide::Arriving, &derivatives)
2066                .map_err(|fault| fault.refusal(&format!("the end of segment {}", chain.len() - 1), domain[1]))?;
2067            if let Some(departing) = curvatures.first_mut() {
2068                if arriving.length() > departing.length() {
2069                    *departing = arriving;
2070                }
2071            }
2072        }
2073    }
2074    Ok(StationSamples {
2075        points,
2076        tangents,
2077        curvatures,
2078        segments,
2079        params,
2080    })
2081}
2082
2083/// The unit tangent and curvature vector a station reads at `t` from the
2084/// derivatives already evaluated there: the regular reading wherever the first
2085/// derivative has a direction (bit for bit what the sampler always read), and
2086/// the one-sided limit on `side` where the parameter is STATIONARY
2087/// ([`stationary_limit`]) — a refusal where that limit does not exist.
2088fn station_reading(
2089    curve: &NurbsCurve,
2090    t: f64,
2091    side: PathSide,
2092    derivatives: &[Vec3; 3],
2093) -> Result<(Vec3, Vec3), StationaryFault> {
2094    match derivatives[1].normalized() {
2095        Ok(tangent) => Ok((tangent, curvature_vector(derivatives[1], derivatives[2]))),
2096        Err(_) => stationary_limit(curve, t, side).map(|limit| (limit.tangent, limit.curvature)),
2097    }
2098}
2099
2100/// The ring frame's fixed reference axis: the path plane's own normal, oriented
2101/// once and reused at every station.
2102///
2103/// A planar path's rotation-minimizing frame IS the planar frame — the transport
2104/// has no component about the tangent, so the axis perpendicular to the plane is
2105/// carried unchanged the whole way round and comes back to itself EXACTLY. That
2106/// is what makes a closed planar sweep need no twist policy: the holonomy is
2107/// zero by construction, not by cancellation. Taking the plane normal as the
2108/// reference axis says so in the construction rather than hoping a
2109/// station-by-station transport returns to where it started.
2110///
2111/// The guard is the one case a fixed axis cannot serve: a tangent parallel to the
2112/// normal, which a planar path cannot have and a mis-fitted plane could.
2113fn ring_normal(normal: Vec3, tangents: &[Vec3]) -> Result<Vec3, KernelRefusal> {
2114    for (index, tangent) in tangents.iter().enumerate() {
2115        if tangent.cross(normal).length() < 0.5 {
2116            return Err(KernelRefusal::internal(
2117                KernelStage::Classify,
2118                "ring_normal",
2119                format!(
2120                "sweepSolid: the closed path's own plane normal is within 30° of its tangent \
2121                 at station {index}, so the path does not lie in that plane after all"
2122                ),
2123            ));
2124        }
2125    }
2126    normal.normalized().map_err(|_| {
2127        KernelRefusal::internal(
2128            KernelStage::Classify,
2129            "ring_normal_degenerate",
2130            "sweepSolid: the closed path's plane normal is degenerate",
2131        )
2132    })
2133}
2134
2135/// The total TURNING of one path segment: the angle its unit tangent sweeps over
2136/// its own domain, summed over 16 uniform steps — or, where a step turns more
2137/// than [`TURNING_ALIAS_STEP`], over 16 steps per knot span.
2138///
2139/// Not the same question as its length, and the one a station budget has to
2140/// answer: a straight segment of any length is carried exactly by two stations,
2141/// while a quarter arc of any radius needs enough stations that the cubic
2142/// interpolant through them does not cut the corner. 16 samples is the density
2143/// every other estimate in this builder uses — and it ALIASES a segment that
2144/// turns more than a few times: on an 8-turn coil each step is half a turn, and
2145/// the angle between two tangents cannot read more than π however far the curve
2146/// turned between them. A step that large is the sign, so only then is the
2147/// segment re-read densely; everything that reads calmly at 16 keeps exactly the
2148/// reading, and so exactly the floor, it always had (a half circle reads a hair
2149/// over π there, and a floor of 33 — the budget the closed lane is pinned at).
2150fn segment_turning(curve: &NurbsCurve, domain: [f64; 2]) -> Result<f64, String> {
2151    let (total, widest) = turning_at(curve, domain, 16)?;
2152    if widest <= TURNING_ALIAS_STEP {
2153        return Ok(total);
2154    }
2155    let spans = curve.knots.windows(2).filter(|pair| pair[1] > pair[0]).count();
2156    Ok(turning_at(curve, domain, (spans * 16).clamp(64, 8192))?.0)
2157}
2158
2159/// The widest tangent step [`segment_turning`] trusts at 16 samples: π/8, twice
2160/// the step of a quarter arc read at that density.
2161const TURNING_ALIAS_STEP: f64 = std::f64::consts::PI / 8.0;
2162
2163/// `(total turning, widest single step)` over `steps` uniform steps.
2164fn turning_at(curve: &NurbsCurve, domain: [f64; 2], steps: usize) -> Result<(f64, f64), String> {
2165    let [t0, t1] = domain;
2166    let mut total = 0.0;
2167    let mut widest: f64 = 0.0;
2168    // A stationary sample — a cusp in the parameterization, which an involute
2169    // flank's Hermite fit carries by construction — still has a direction of
2170    // travel, and the turning is a question about directions.
2171    let mut previous = curve.unit_tangent(t0, t0, t1)?;
2172    for sample in 1..=steps {
2173        let tangent = curve.unit_tangent(t0 + (t1 - t0) * sample as f64 / steps as f64, t0, t1)?;
2174        let step = previous.dot(tangent).clamp(-1.0, 1.0).acos();
2175        total += step;
2176        widest = widest.max(step);
2177        previous = tangent;
2178    }
2179    Ok((total, widest))
2180}
2181
2182/// ONE double-reflection step (Wang et al. 2008) of a rotation-minimizing frame:
2183/// carry the reference axis `r` from a station with tangent `t` to the next with
2184/// tangent `t_next` across the step vector `step`, then re-orthogonalize against
2185/// the new tangent to shed floating drift. `None` when the result degenerates.
2186///
2187/// Extracted so the frame the sections are placed on and the frame the holonomy
2188/// is measured with are the SAME transport rather than two copies of it.
2189fn rmf_step(r: Vec3, t: Vec3, t_next: Vec3, step: Vec3) -> Option<Vec3> {
2190    let c1 = step.dot(step);
2191    let candidate = if c1 <= 1e-18 {
2192        // Coincident stations: carry the reference axis forward unchanged.
2193        r
2194    } else {
2195        // First reflection across the plane bisecting the step vector.
2196        let reflected_r = r.sub(step.scale(2.0 / c1 * step.dot(r)));
2197        let reflected_t = t.sub(step.scale(2.0 / c1 * step.dot(t)));
2198        // Second reflection across the plane bisecting the tangents.
2199        let v2 = t_next.sub(reflected_t);
2200        let c2 = v2.dot(v2);
2201        if c2 <= 1e-18 {
2202            reflected_r
2203        } else {
2204            reflected_r.sub(v2.scale(2.0 / c2 * v2.dot(reflected_r)))
2205        }
2206    };
2207    candidate
2208        .sub(t_next.scale(candidate.dot(t_next)))
2209        .normalized()
2210        .ok()
2211}
2212
2213// ===========================================================================
2214// The TIGHT BEND: a section carried through a bend tighter than its own reach
2215// ===========================================================================
2216
2217/// How many points each profile curve contributes to the section's REACH.
2218///
2219/// The reach has to be a WITNESS — a point of the section that really does turn
2220/// back — so it is read off the curve itself and never off the control hull:
2221/// `make_arc` places a half-circle's middle controls at `r√2`, so a hull bound
2222/// would refuse a round section 41 % early. Sampling under-reads instead, which
2223/// is the safe direction: at 64 samples per curve a circle's support is short by
2224/// `r(1 − cos(π/128))` = 3.0e-4·r, so the guard can only ever refuse LATE, and a
2225/// bend that slips past it still meets the fold acceptance at the loft's exit.
2226const BEND_SECTION_SAMPLES: usize = 64;
2227
2228/// One station's tight-bend reading: what the path does there and how far the
2229/// section reaches into it.
2230///
2231/// The quantity that decides the sweep is [`BendStation::ratio`] — `reach·κ`,
2232/// the same `ρκ` the fillet's canal surface folds at. A section point offset `d`
2233/// towards the centre of the osculating circle advances `(1 − d·κ)` per unit of
2234/// path, so at `d·κ = 1` it stops and past it it goes BACKWARDS: the swept
2235/// envelope has turned back through itself and the solid is the envelope trimmed
2236/// at that self-intersection, not the loft through the crossing sections.
2237#[derive(Debug, Clone, Copy)]
2238pub struct BendStation {
2239    /// The station's index in the sweep's own station list.
2240    pub station: usize,
2241    /// Where it is on the path.
2242    pub point: Vec3,
2243    /// The path's curvature `κ` there (zero on a straight piece).
2244    pub curvature: f64,
2245    /// The path's radius of curvature `ρ = 1/κ`, `f64::INFINITY` where straight.
2246    pub radius: f64,
2247    /// How far the placed section reaches towards the centre of the bend —
2248    /// its support in the curvature-normal direction. Negative when the whole
2249    /// section sits on the OUTSIDE of the bend, zero where the path is straight.
2250    pub reach: f64,
2251    /// `reach·κ`. `< 1` builds; `≥ 1` folds.
2252    pub ratio: f64,
2253}
2254
2255/// The profile's sample points in the placement frame's own 2D coordinates
2256/// `(a, b) = ((x − origin)·pu, (x − origin)·pv)`.
2257///
2258/// Sampled ONCE: `Transplant` places the same 2D shape at every station
2259/// (`world = station + rᵢ·a + sᵢ·b`), so a station's reach is a pair of dot
2260/// products against the precomputed cloud rather than a re-evaluation of the
2261/// placed curves.
2262fn section_offsets(
2263    profile: &[NurbsCurve],
2264    placement: &ProfileAnchor,
2265) -> Result<Vec<(f64, f64)>, KernelRefusal> {
2266    let ProfileAnchor { origin, pu, pv, .. } = *placement;
2267    let mut offsets = Vec::with_capacity(profile.len() * BEND_SECTION_SAMPLES);
2268    for curve in profile {
2269        let [start, end] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
2270        for sample in 0..BEND_SECTION_SAMPLES {
2271            let t = start + (end - start) * sample as f64 / BEND_SECTION_SAMPLES as f64;
2272            let local = curve.evaluate(t).or_refuse(KernelStage::Classify, "evaluate")?.sub(origin);
2273            offsets.push((local.dot(pu), local.dot(pv)));
2274        }
2275    }
2276    Ok(offsets)
2277}
2278
2279/// The `ρκ` profile: one [`BendStation`] per station, in station order.
2280///
2281/// `axes` are the frames the sections are PLACED on (twist included), because
2282/// the reach is the section's support in the curvature-normal direction and a
2283/// non-round section rolled about the path presents a different support there.
2284fn bend_stations(
2285    points: &[Vec3],
2286    curvatures: &[Vec3],
2287    axes: &[(Vec3, Vec3)],
2288    offsets: &[(f64, f64)],
2289) -> Vec<BendStation> {
2290    (0..points.len())
2291        .map(|station| {
2292            let curvature = curvatures[station].length();
2293            if curvature <= 0.0 {
2294                return BendStation {
2295                    station,
2296                    point: points[station],
2297                    curvature: 0.0,
2298                    radius: f64::INFINITY,
2299                    reach: 0.0,
2300                    ratio: 0.0,
2301                };
2302            }
2303            // The curvature vector is perpendicular to the tangent by
2304            // construction, so its components on (r, s) are the whole of it.
2305            let normal = curvatures[station].scale(1.0 / curvature);
2306            let (r_axis, s_axis) = axes[station];
2307            let (nu, nv) = (normal.dot(r_axis), normal.dot(s_axis));
2308            let reach = offsets
2309                .iter()
2310                .map(|(a, b)| a * nu + b * nv)
2311                .fold(f64::NEG_INFINITY, f64::max);
2312            BendStation {
2313                station,
2314                point: points[station],
2315                curvature,
2316                radius: 1.0 / curvature,
2317                reach,
2318                ratio: reach * curvature,
2319            }
2320        })
2321        .collect()
2322}
2323
2324/// The `ρκ` profile a TRANSPLANT sweep of `profile` along `path` would carry at
2325/// `stations` stations — the instrument behind the refusal below, exposed so a
2326/// caller (or a probe) can measure a path BEFORE asking for the solid.
2327///
2328/// Reads the very stations the sweep's tight-bend refusal reads: the FLOOR
2329/// budget, before the error-driven refinement (`chain_stations`) adds any —
2330/// the same sampling, the same rotation-minimizing frame. A bend too tight
2331/// is decided and quoted on the floor stations so that a path which folds
2332/// is refused before stations are spent refining it, and so that the
2333/// refusal's numbers do not move with the tolerance. Untwisted, which is the
2334/// lane every caller of [`sweep_profile_along_chain_with_stations`] is in.
2335pub fn sweep_bend_profile(
2336    profile: &[NurbsCurve],
2337    path: &SweepPath,
2338    stations: usize,
2339) -> Result<Vec<BendStation>, KernelRefusal> {
2340    let placement = resolve_placement(profile, None, SectionPlacement::Transplant)?;
2341    let (samples, _) = chain_stations(
2342        path.curves.as_slice(),
2343        path.closed,
2344        SamplerLane::Chain,
2345        stations.clamp(2, 1024),
2346        0.0,
2347        None,
2348    )?;
2349    floor_bend_stations(profile, &placement, path, &samples)
2350}
2351
2352/// The `ρκ` profile of a TRANSPLANT sweep over `samples`, on the untwisted
2353/// ring or open frame those stations take — what [`sweep_bend_profile`]
2354/// reports and what the chain sweep refuses on before it refines.
2355fn floor_bend_stations(
2356    profile: &[NurbsCurve],
2357    placement: &ProfileAnchor,
2358    path: &SweepPath,
2359    samples: &StationSamples,
2360) -> Result<Vec<BendStation>, KernelRefusal> {
2361    let closure = ring_frame(path, &samples.tangents)?;
2362    let untwisted = ClosingTwist {
2363        twist: 0.0,
2364        shift: 0,
2365    };
2366    let (r_axes, s_axes, _) = station_frames(&samples.points, &samples.tangents, closure, None, untwisted)?;
2367    let axes: Vec<(Vec3, Vec3)> = r_axes.into_iter().zip(s_axes).collect();
2368    let offsets = section_offsets(profile, placement)?;
2369    Ok(bend_stations(&samples.points, &samples.curvatures, &axes, &offsets))
2370}
2371
2372/// A tight-bend refusal with the envelope lane's own measurement of WHICH
2373/// half of its one configuration the sweep missed appended, when there is
2374/// one — so the refusal names the boundary of what is built rather than
2375/// only the bend that is refused.
2376fn with_envelope_gap(refusal: KernelRefusal, envelope_gap: Option<&str>) -> KernelRefusal {
2377    match envelope_gap {
2378        Some(gap) if !gap.is_empty() => refusal.with_message(|refusal| {
2379            format!(
2380            "{refusal}. The swept envelope trimmed at its own self-intersection is built \
2381             for a CIRCLE carried along one circular planar arc, and this sweep is not \
2382             that: {gap}"
2383            )
2384        }),
2385        _ => refusal,
2386    }
2387}
2388
2389/// The prefix every tight-bend refusal starts with, so a caller can CLASSIFY one
2390/// (the wire harness reports it as a bundle status) without matching free text.
2391pub const SWEEP_TIGHT_BEND_REFUSAL: &str = "sweepSolid: the path bends TIGHTER than the section";
2392
2393/// The slug of the tight-bend refusal (`UnsupportedGeometry`), shared by its
2394/// one mint ([`tight_bend_refusal`]) and [`is_sweep_tight_bend`].
2395pub const SWEEP_TIGHT_BEND_WHAT: &str = "tight_bend";
2396
2397/// Is this the sweep's tight-bend refusal ([`SWEEP_TIGHT_BEND_REFUSAL`])? Read
2398/// off the class and its slug, so a caller that decides on it (the wire
2399/// harness's bundle status) follows the refusal, not its wording.
2400pub fn is_sweep_tight_bend(refusal: &KernelRefusal) -> bool {
2401    matches!(
2402        &refusal.class,
2403        crate::RefusalClass::UnsupportedGeometry { what } if what == SWEEP_TIGHT_BEND_WHAT
2404    )
2405}
2406
2407/// The refusal for a path that bends tighter than the section reaches, or `None`
2408/// when every station builds.
2409///
2410/// Quotes the WORST station rather than the first one scanned — the tightest
2411/// bend is the one the user has to ease, and a path can cross the bar in several
2412/// places (both ends of one Hermite span, typically).
2413fn tight_bend_refusal(profile: &[BendStation], stations: usize) -> Option<KernelRefusal> {
2414    let folded = profile.iter().filter(|station| station.ratio >= 1.0).count();
2415    if folded == 0 {
2416        return None;
2417    }
2418    let worst = profile
2419        .iter()
2420        .max_by(|a, b| a.ratio.total_cmp(&b.ratio))
2421        .expect("a folded station exists");
2422    // The solid exists — the envelope trimmed at its self-intersection — and
2423    // this lane does not build it: a named deferral.
2424    Some(KernelRefusal::unsupported(
2425        KernelStage::Classify,
2426        SWEEP_TIGHT_BEND_WHAT,
2427        format!(
2428        "{SWEEP_TIGHT_BEND_REFUSAL} at station {} of {stations} ({:.4}, {:.4}, {:.4}): the path's \
2429         radius of curvature there is {:.6} and the section reaches {:.6} into the bend, so \
2430         ρ·κ = {:.3} ≥ 1 ({folded} of {stations} stations do). A section carried through a bend \
2431         tighter than its own reach sweeps an envelope that passes through ITSELF — the solid \
2432         there is that envelope trimmed at its own self-intersection, which this lane does not \
2433         build: it skins the section between stations, and past ρ·κ = 1 the sections CROSS and \
2434         the wall folds. Ease the bend to a radius above {:.6}, or narrow the section until it \
2435         reaches no further than {:.6} (a round section of diameter {:.6})",
2436        worst.station,
2437        worst.point.x,
2438        worst.point.y,
2439        worst.point.z,
2440        worst.radius,
2441        worst.reach,
2442        worst.ratio,
2443        worst.reach,
2444        worst.radius,
2445        2.0 * worst.radius,
2446        ),
2447    ))
2448}
2449
2450/// The part of the sweep that does not care HOW the stations were sampled:
2451/// validate the profile, distribute the twist over the sampled polyline,
2452/// propagate the rotation-minimizing frame, place a profile copy per station
2453/// and loft through them.
2454///
2455/// Split out so a MULTI-SEGMENT path can share it
2456/// ([`sweep_profile_along_chain_stations`]). The single-curve sampler above is
2457/// deliberately left calling this with its OWN sampling rather than being
2458/// re-expressed as a one-element chain: two code paths that agree today are not
2459/// the same thing as one code path, and the untwisted single-curve geometry is
2460/// pinned by volume tests that must not move.
2461///
2462/// The RMF is propagated over the station sequence as a whole, so a chain's
2463/// frame carries across a joint exactly as it carries across any other pair of
2464/// adjacent stations — there is no per-segment restart to reconcile.
2465///
2466/// `closure` turns the run into a RING: anything but [`RingFrame::Open`] says the
2467/// stations come back round to station 0 (which is therefore NOT repeated at the
2468/// end). `Planar(normal)` says the path lies in the plane of that normal, so the
2469/// reference axis is fixed rather than transported — a planar frame, whose
2470/// holonomy round the loop is zero by construction. `Spatial` transports the
2471/// frame and closes it with the counter-twist policy ([`SweepClosure`]). Either
2472/// way the sections skin through a CLOSED loft: one face per section curve, no
2473/// end caps, `V − E + F = 0`. `Open` is the open run: transported frame, two end
2474/// caps, and the refusal below for a trajectory that closes anyway.
2475///
2476/// `chain` is the station-to-segment map and the classified path, from the chain
2477/// sampler; the single-curve sampler has none. Only `Rigid` reads it, to frame a
2478/// HELIX segment's stations off its screw axis ([`screw_reference`]).
2479/// The sampled run's geometry and budget, carried into
2480/// [`sweep_sections_through_samples`] for the report it writes.
2481struct StationRun<'a> {
2482    chain: &'a [NurbsCurve],
2483    params: &'a [StationParam],
2484    budget: StationBudget,
2485    tolerance: f64,
2486    measure_report: bool,
2487    /// The section's SCALE at the far end, laid down linearly in sampled arc
2488    /// length from 1 at the start (an OPEN `Transplant` run only; see
2489    /// [`sweep_profile_twisted_scaled`]). `None` for every other builder, which
2490    /// leaves the placement bit-identical to the unscaled one.
2491    end_scale: Option<f64>,
2492    /// The stations the wall's columns break at (`BREP_SWEEP_JOINT_BREAKS`);
2493    /// `None` keeps one interpolant per column.
2494    breaks: Option<&'a [usize]>,
2495}
2496
2497#[allow(clippy::too_many_arguments)]
2498fn sweep_sections_through_samples(
2499    profile: &[NurbsCurve],
2500    points: &[Vec3],
2501    tangents: &[Vec3],
2502    curvatures: &[Vec3],
2503    twist_angle: f64,
2504    placement: ProfileAnchor,
2505    placement_mode: SectionPlacement,
2506    closure: RingFrame,
2507    envelope_gap: Option<&str>,
2508    chain: Option<(&[usize], &SweepPath)>,
2509    run: StationRun<'_>,
2510) -> Result<SweptChain, KernelRefusal> {
2511    let mut timing = crate::loft_topology::ConstructionProfile::new("sweep_sections");
2512    let tolerance = 1e-6;
2513    let stations = points.len();
2514    if stations < 2 {
2515        return Err(KernelRefusal::internal(
2516            KernelStage::Collect,
2517            "station_run",
2518            "sweepSolid: need at least 2 stations",
2519        ));
2520    }
2521
2522    let ProfileAnchor { origin, pu, pv, .. } = placement;
2523
2524    // --- 2b. Twist distribution: cumulative ARC-LENGTH fractions over the
2525    //         sampled station polyline (chord sums), so the twist advances
2526    //         uniformly in space even on a non-uniformly parameterized path.
2527    //         Only computed when a twist is actually requested — the
2528    //         `twist_angle == 0.0` path must stay bit-identical to the
2529    //         pre-twist builder — and only on an OPEN run. These fractions stop at
2530    //         the last station, so a RING laid down by them would roll its wrap
2531    //         span at a different rate from every other; a ring rolls its twist
2532    //         in its frames instead, over the whole lap (§3).
2533    let twist_fractions: Option<Vec<f64>> = if twist_angle != 0.0 && !closure.is_ring() {
2534        let mut cumulative = vec![0.0; stations];
2535        let mut total = 0.0;
2536        for index in 1..stations {
2537            total += points[index].sub(points[index - 1]).length();
2538            cumulative[index] = total;
2539        }
2540        if total <= tolerance {
2541            return Err(KernelRefusal::input(
2542                KernelStage::Collect,
2543                "path_length",
2544                "sweepSolid: path has zero length; cannot distribute the twist",
2545            ));
2546        }
2547        for length in &mut cumulative {
2548            *length /= total;
2549        }
2550        Some(cumulative)
2551    } else {
2552        None
2553    };
2554
2555    // --- 2c. Scaling law (`StationRun::end_scale`): the section's scale at each
2556    //         station, linear in the same sampled ARC-LENGTH fraction the twist
2557    //         uses, from 1 at the start to `end_scale` at the end. Only an OPEN
2558    //         `Transplant` run takes one: a ring has no end to scale towards, and
2559    //         `Rigid` carries the profile where it stands, about no centre a
2560    //         scale could be taken about. `None` leaves every axis untouched.
2561    let station_scales: Option<Vec<f64>> = match run.end_scale {
2562        None => None,
2563        Some(end_scale) => {
2564            if !end_scale.is_finite() || end_scale <= 0.0 {
2565                return Err(KernelRefusal::input(
2566                    KernelStage::Collect,
2567                    "end_scale",
2568                    format!("sweepSolid: the end scale must be finite and positive, got {end_scale}"),
2569                ));
2570            }
2571            if closure.is_ring() || placement_mode == SectionPlacement::Rigid {
2572                return Err(KernelRefusal::unsupported(
2573                    KernelStage::Collect,
2574                    "end_scale_mode",
2575                    "sweepSolid: a scaling law needs an open path and a section placed square to it",
2576                ));
2577            }
2578            let mut cumulative = vec![0.0; stations];
2579            let mut total = 0.0;
2580            for index in 1..stations {
2581                total += points[index].sub(points[index - 1]).length();
2582                cumulative[index] = total;
2583            }
2584            if total <= tolerance {
2585                return Err(KernelRefusal::input(
2586                    KernelStage::Collect,
2587                    "path_length",
2588                    "sweepSolid: path has zero length; cannot distribute the scale",
2589                ));
2590            }
2591            Some(
2592                cumulative
2593                    .iter()
2594                    .map(|length| 1.0 + (end_scale - 1.0) * (length / total))
2595                    .collect(),
2596            )
2597        }
2598    };
2599
2600    // --- 3. The station frames.
2601    //
2602    //   OPEN: rotation-minimizing frames via the double-reflection method, seeded
2603    //   on an arbitrary perpendicular to T0 — arbitrary because `Rigid` cancels
2604    //   the seed out (`R_k = F_k·F_0ᵀ`) and `Transplant` has always taken whatever
2605    //   roll `perpendicular()` returned.
2606    //
2607    //   RING: the plane normal is the reference axis AT EVERY STATION. A planar
2608    //   path's RMF is that frame already — the transport has no component about
2609    //   the tangent — so this is not a different frame from the open lane's, it is
2610    //   the same frame written down in closed form instead of accumulated. Which
2611    //   matters for exactly one reason: written down, it returns to itself at the
2612    //   seam EXACTLY, so the ring's last section meets its first with no residual
2613    //   roll to skin away.
2614    //
2615    //   SPATIAL RING: the open lane's transported frame, carried one step further
2616    //   round the wrap to MEASURE the roll it returns with (the holonomy), and
2617    //   counter-twisted by that roll linearly in arc length so the lap's last span
2618    //   rolls at the same rate as every other and the ring meets itself
2619    //   (`ring_closure_frames`).
2620    //
2621    //   A REQUESTED twist on a RING is laid down in those frames too, over the
2622    //   whole lap with the wrap, on top of the counter-twist — but only a twist
2623    //   that closes: after the lap the section comes back rolled by it, so it must
2624    //   carry the section onto itself ([`closing_twist`], refused by name
2625    //   otherwise). A fractional turn on a symmetric section closes onto a
2626    //   DIFFERENT curve than it left, `shift` along, and the loft below is told.
2627    //
2628    //   RIGID on a HELIX segment: the helix's own screw frame (see
2629    //   `screw_reference`), which the RMF rolls away from by the helix's
2630    //   integrated torsion. `Transplant` keeps the RMF everywhere — it squares
2631    //   the section to the path and centres it there, and its callers (SWP, the
2632    //   tube, the harness) are not this contract.
2633    let screw = chain.filter(|_| placement_mode == SectionPlacement::Rigid);
2634    let requested = if closure.is_ring() && twist_angle != 0.0 {
2635        let (section, _) = place_section(profile, placement, placement_mode, points[0], tangents[0])?;
2636        ring_closing_twist(&section, points, tangents, twist_angle)?
2637    } else {
2638        ClosingTwist {
2639            twist: 0.0,
2640            shift: 0,
2641        }
2642    };
2643    let (r_axes, s_axes, _) = station_frames(points, tangents, closure, screw, requested)?;
2644
2645    // --- 3b. An OPEN trajectory that comes back to where it started cannot be
2646    //         capped: the first and last sections land on top of each other, and
2647    //         the loft's own complaint about that ("end sections coincide") says
2648    //         nothing about the path. Name it here instead, with the two things
2649    //         that do work. The check is on the PATH's first and last station
2650    //         POINTS, which is enough: a path that comes back to where it started
2651    //         puts the two caps in the same place whatever direction it arrives
2652    //         from — coincident when it also arrives pointing the same way,
2653    //         interpenetrating when it does not, and neither is a solid worth
2654    //         building.
2655    //
2656    //         TWO CLOSURE NOTIONS COEXIST, and deliberately. A path whose ends
2657    //         meet within the chainer's join band is CLASSIFIED closed and swept
2658    //         as a ring above — that is the shape a user drew as a loop. This band
2659    //         is a thousandth of the distance TRAVELLED, a hundred times looser,
2660    //         and it catches the run that is nearly a loop without being one: a
2661    //         359.7° arc whose caps would interpenetrate rather than coincide. The
2662    //         first is a shape with a construction; the second is an accident, and
2663    //         it is still refused. On a circular arc the band is the last ~0.36°
2664    //         before closure, so a 359° sweep still builds.
2665    if !closure.is_ring() {
2666        let travel: f64 = points
2667            .windows(2)
2668            .map(|pair| pair[1].sub(pair[0]).length())
2669            .sum();
2670        let gap = points[stations - 1].sub(points[0]).length();
2671        if travel > tolerance && gap <= 1e-3 * travel {
2672            // A run that is nearly a loop without being one: the input does not
2673            // say whether it is a ring or an open sweep, so neither is chosen.
2674            return Err(KernelRefusal::ill_posed(
2675                KernelStage::Classify,
2676                "near_closed_path",
2677                format!(
2678                "sweepSolid: the path returns to where it started ({gap:.3e} apart after \
2679                 travelling {travel:.3e}), so the sweep's two end caps would land on top of each \
2680                 other. A closed path swept this way IS a revolution — build it with Revolve \
2681                 about the same axis, or close the path exactly so it sweeps as a capless ring, \
2682                 or sweep the run in two halves and union them"
2683                ),
2684            ));
2685        }
2686    }
2687
2688    // --- 4. Place a transformed copy of the profile at each station, by the mode
2689    //        the caller asked for (see `SectionPlacement`).
2690    //
2691    //   TRANSPLANT maps the profile's own plane frame onto the station frame,
2692    //       world = P_k + r_k·(l·pu) + s_k·(l·pv),   l = x − origin
2693    //   which lands the anchor origin ON the path and the profile square to it.
2694    //   The profile's distance from the path and its angle to the path are both
2695    //   discarded — there is no term along the tangent to carry them.
2696    //
2697    //   RIGID applies the path's own motion to the profile where it stands,
2698    //       world = P_k + a·T_k + b·r_k + c·s_k,     (a,b,c) = (l·T_0, l·r_0, l·s_0)
2699    //                                                l = x − P_0
2700    //   which is `P_k + R_k·(x − P_0)` for `R_k = F_k·F_0ᵀ`, written in the frame
2701    //   basis rather than as a matrix. The tangent term `a·T_k` is exactly what
2702    //   TRANSPLANT drops, and carrying it is what preserves both the profile's
2703    //   offset from the path and its angle to it. At station 0 the frames
2704    //   coincide and the section IS the profile, so the START cap lies in the
2705    //   plane it was drawn in.
2706    timing.lap("frames");
2707    let path_start = points[0];
2708    let (t0, r0, s0) = (tangents[0], r_axes[0], s_axes[0]);
2709    let rigid = placement_mode == SectionPlacement::Rigid;
2710    let mut sections: Vec<Vec<NurbsCurve>> = Vec::with_capacity(stations);
2711    // Only the RIGID guard below reads these; TRANSPLANT leaves them empty.
2712    let mut station_points: Vec<Vec<Vec3>> = Vec::with_capacity(if rigid { stations } else { 0 });
2713    let mut section_normals: Vec<Vec3> = Vec::with_capacity(if rigid { stations } else { 0 });
2714    let mut anchor_track: Vec<Vec3> = Vec::with_capacity(if rigid { stations } else { 0 });
2715    // The axes the section is actually PLACED on, twist included — what the
2716    // tight-bend guard below measures the section's reach in.
2717    let mut placed_axes: Vec<(Vec3, Vec3)> = Vec::with_capacity(stations);
2718    // The section's AFFINE placement per station, for the report: the image of
2719    // the anchor origin (the centre track) and the images of `pu` and `pv`.
2720    let mut centres: Vec<Vec3> = Vec::with_capacity(stations);
2721    let mut axes_1: Vec<Vec3> = Vec::with_capacity(stations);
2722    let mut axes_2: Vec<Vec3> = Vec::with_capacity(stations);
2723    for station in 0..stations {
2724        let station_origin = points[station];
2725        // Rotate the RMF axes about the tangent by the station's twist angle
2726        // (Rodrigues on vectors ⟂ the tangent: r' = r·cosφ + s·sinφ,
2727        // s' = s·cosφ − r·sinφ, since s = t × r and t × s = −r).
2728        let (ri, si) = match &twist_fractions {
2729            Some(fractions) => {
2730                let phi = twist_angle * fractions[station];
2731                let (sin_phi, cos_phi) = phi.sin_cos();
2732                let r = r_axes[station];
2733                let s = s_axes[station];
2734                (
2735                    r.scale(cos_phi).add(s.scale(sin_phi)),
2736                    s.scale(cos_phi).sub(r.scale(sin_phi)),
2737                )
2738            }
2739            None => (r_axes[station], s_axes[station]),
2740        };
2741        // A scaling law scales the placed axes (TRANSPLANT only, refused above
2742        // otherwise), so `place` scales the profile about its anchor origin and
2743        // the tight-bend guard below reads the SCALED section's reach.
2744        let (ri, si) = match &station_scales {
2745            Some(scales) => (ri.scale(scales[station]), si.scale(scales[station])),
2746            None => (ri, si),
2747        };
2748        placed_axes.push((ri, si));
2749        let tk = tangents[station];
2750        let place = |x: Vec3| -> Vec3 {
2751            if rigid {
2752                let local = x.sub(path_start);
2753                station_origin
2754                    .add(tk.scale(local.dot(t0)))
2755                    .add(ri.scale(local.dot(r0)))
2756                    .add(si.scale(local.dot(s0)))
2757            } else {
2758                let local = x.sub(origin);
2759                station_origin
2760                    .add(ri.scale(local.dot(pu)))
2761                    .add(si.scale(local.dot(pv)))
2762            }
2763        };
2764        {
2765            let centre = place(origin);
2766            centres.push(centre);
2767            axes_1.push(place(origin.add(pu)).sub(centre));
2768            axes_2.push(place(origin.add(pv)).sub(centre));
2769        }
2770        if rigid {
2771            // The section's own normal takes the same rotation (a direction, so
2772            // `R_k` without the translation), and the anchor origin's track is
2773            // the profile's bulk motion for the near-parallel guard.
2774            let n0 = placement.normal;
2775            section_normals.push(
2776                tk.scale(n0.dot(t0))
2777                    .add(ri.scale(n0.dot(r0)))
2778                    .add(si.scale(n0.dot(s0))),
2779            );
2780            anchor_track.push(place(origin));
2781            station_points.push(Vec::with_capacity(
2782                profile.iter().map(|c| c.control_points.len()).sum(),
2783            ));
2784        }
2785        let mut section = Vec::with_capacity(profile.len());
2786        for curve in profile {
2787            let control_points = curve
2788                .control_points
2789                .iter()
2790                .map(|point| {
2791                    let weight = point.w;
2792                    let euclidean = Vec3::new(point.x / weight, point.y / weight, point.z / weight);
2793                    let world = place(euclidean);
2794                    if rigid {
2795                        station_points[station].push(world);
2796                    }
2797                    Vec4 {
2798                        x: world.x * weight,
2799                        y: world.y * weight,
2800                        z: world.z * weight,
2801                        w: weight,
2802                    }
2803                })
2804                .collect();
2805            section.push(NurbsCurve::new(
2806                curve.degree,
2807                curve.knots.clone(),
2808                control_points,
2809            ).or_refuse(KernelStage::Fragment, "curve_new")?);
2810        }
2811        sections.push(section);
2812    }
2813
2814    // --- 4b. RIGID only: refuse a sweep whose sections fold through each other.
2815    //
2816    // TRANSPLANT keeps every section square to the path, so it can only fold
2817    // where the path's curvature radius drops below the profile's extent — the
2818    // case this builder has always documented as the caller's to avoid. RIGID
2819    // can fold for a second, much more reachable reason: a turning path carries
2820    // the profile around the TURN'S OWN AXIS, so a profile straddling that axis
2821    // has one half advancing while the other retreats. That is not a tolerance
2822    // question, it is a sign question, so it is answered exactly.
2823    //
2824    // The placement map is AFFINE in `x`, so the advance is affine in `x` too and
2825    // its extremes over the section lie on the control points. Checking the hull
2826    // therefore bounds the advance over the curves AND over the region they
2827    // enclose — this is a proof, not a sampling.
2828    //
2829    // ON A RING the guard walks one step FURTHER: the wrap from the last station
2830    // back to station 0 is a step the sections take like any other, and it is the
2831    // one step an open run does not have. A ring whose wrap step folded while
2832    // every interior step advanced would otherwise pass. On a ring whose twist
2833    // lands each curve `shift` along, the wrap step's control points arrive on
2834    // that curve's: the flat control-point list of station 0, turned left by the
2835    // points of the `shift` curves before it (curves `j` and `j + shift` carry the
2836    // same number, which is what makes the turn a relabelling).
2837    let step_count = if closure.is_ring() {
2838        stations
2839    } else {
2840        stations - 1
2841    };
2842    let next_station = |station: usize| (station + 1) % stations;
2843    if rigid {
2844        let landing_offset: usize = profile[..requested.shift]
2845            .iter()
2846            .map(|curve| curve.control_points.len())
2847            .sum();
2848        let mut most_positive = 0.0f64;
2849        let mut most_negative = 0.0f64;
2850        let mut longest_step = 0.0f64;
2851        for station in 0..step_count {
2852            let normal = section_normals[station];
2853            let arriving = &station_points[next_station(station)];
2854            let turn = if next_station(station) == 0 { landing_offset } else { 0 };
2855            for (before, after) in station_points[station]
2856                .iter()
2857                .zip(arriving[turn..].iter().chain(&arriving[..turn]))
2858            {
2859                let step = after.sub(*before);
2860                longest_step = longest_step.max(step.length());
2861                let advance = step.dot(normal);
2862                most_positive = most_positive.max(advance);
2863                most_negative = most_negative.min(advance);
2864            }
2865        }
2866        // Scale-relative, and far below any geometric tolerance: this band only
2867        // has to separate a sign from floating noise, never a small motion from
2868        // a large one.
2869        let noise = 1e-9 * longest_step.max(tolerance);
2870        if most_positive > noise && most_negative < -noise {
2871            return Err(KernelRefusal::unsupported(
2872                KernelStage::Classify,
2873                "straddles_axis",
2874                "sweepSolid: the profile sweeps back through itself — part of it advances along \
2875                 the path while part of it retreats. A turning path carries the profile around \
2876                 the turn's own axis, so a profile that STRADDLES that axis folds into itself; \
2877                 move the profile clear of the axis, or sweep the run in pieces",
2878            ));
2879        }
2880        if most_positive <= noise && most_negative >= -noise {
2881            return Err(KernelRefusal::input(
2882                KernelStage::Classify,
2883                "no_advance",
2884                "sweepSolid: the path does not advance through the profile — it runs inside the \
2885                 profile plane, so the sweep encloses no volume",
2886            ));
2887        }
2888        // The near-parallel case, on the anchor origin's own track: the same 0.1
2889        // threshold `extrude_profile_brep` refuses a sliver at, so a STRAIGHT
2890        // path is accepted here exactly when the translational sweep of the same
2891        // profile and vector is. A station whose origin barely moves is skipped —
2892        // an origin sitting on the turn axis means the profile straddles it, and
2893        // the fold-back guard above has already spoken.
2894        for station in 0..step_count {
2895            let step = anchor_track[next_station(station)].sub(anchor_track[station]);
2896            let length = step.length();
2897            if length <= noise {
2898                continue;
2899            }
2900            if step.dot(section_normals[station]).abs() / length < 0.1 {
2901                return Err(KernelRefusal::input(
2902                    KernelStage::Classify,
2903                    "sliver",
2904                    "sweepSolid: the path is nearly parallel to the profile plane, which sweeps a \
2905                     sliver rather than a solid",
2906                ));
2907            }
2908        }
2909    }
2910
2911    // --- 4c. TRANSPLANT: refuse a path that bends TIGHTER than the section
2912    //         reaches, before the loft rather than after it.
2913    //
2914    // A section square to the path, offset `d` towards the centre of the
2915    // osculating circle, advances `(1 − d·κ)` per unit of path: at `d·κ = 1` it
2916    // stands still and past it it RETREATS, so consecutive sections cross and
2917    // the wall the loft skins through them passes through itself. That is the
2918    // same `ρκ > 1` the fillet's canal surface folds at, and the same defect the
2919    // soundness acceptance catches at the loft's exit — but caught THERE it can
2920    // only name a face and two parameters, where here it can name the station,
2921    // the bend and the section that does not fit through it.
2922    //
2923    // RIGID is not measured here: it does not keep the section square to the
2924    // path, so `ρκ` is not its criterion, and §4b above is its guard.
2925    //
2926    // The reach is a WITNESS and the curvature is the PATH's own, so this refuses
2927    // only where a real section point really does turn back. What it does not see
2928    // is a bend that peaks BETWEEN two stations — the loft interpolates those,
2929    // and the acceptance at the exit remains the backstop.
2930    if !rigid && std::env::var("BREP_SWEEP_BEND_GUARD").as_deref() != Ok("0") {
2931        let offsets = section_offsets(profile, &placement)?;
2932        let profile_stations = bend_stations(points, curvatures, &placed_axes, &offsets);
2933        if let Some(refusal) = tight_bend_refusal(&profile_stations, stations) {
2934            // The ENVELOPE lane builds this shape exactly for ONE configuration
2935            // (a circle on one circular planar arc), and a caller that lands here
2936            // has missed it (`with_envelope_gap`). An untwisted chain sweep was
2937            // already asked this on its floor stations; this is the backstop
2938            // for the twisted and single-curve runs, and for a bend that peaks
2939            // between floor stations and shows on the refined ones.
2940            return Err(with_envelope_gap(refusal, envelope_gap));
2941        }
2942    }
2943
2944    // --- 5. Loft through the swept sections.
2945    //
2946    //   OPEN: side walls plus two planar end caps.
2947    //
2948    //   RING: the CLOSED loft — the sections form a cycle, the last flowing back
2949    //   into the first through the same C² cyclic interpolation every interior
2950    //   span gets, so the seam is not a weld. One face per section curve and NO
2951    //   CAPS, which is the whole point: a ring has no ends to cap, and capping it
2952    //   would be two faces inside the material. The topology it emits is
2953    //   `c` corner vertices, `c` corner rings, `c` seam edges and `c` faces, so
2954    //   `V − E + F = c − 2c + c = 0` — the Euler characteristic of a torus, which
2955    //   is what a section carried once round a loop encloses.
2956    //   A RING whose requested twist lands each curve `shift` along skins each
2957    //   wall from its own curve into that one (`loft_profile_brep_closed_shifted`),
2958    //   so there is still one wall per section curve.
2959    //   The loft mints its own refusals; the wrap below keeps that class and
2960    //   prefixes the text.
2961    timing.lap("sections_preflight");
2962    let solid = match closure {
2963        RingFrame::Planar(_) | RingFrame::Spatial => {
2964            // The loft mints its own refusals; its class rides through the
2965            // sweep's wrap (a station cap stays a deferral, the acceptance's
2966            // fold stays an UnsoundResult).
2967            match run.breaks.filter(|_| requested.shift == 0) {
2968                Some(breaks) => crate::loft_topology::loft_profile_brep_closed_broken(&sections, breaks),
2969                None => crate::loft_profile_brep_closed_shifted(&sections, requested.shift),
2970            }
2971            .map_err(|error| {
2972                error.with_message(|error| {
2973                    format!("sweepSolid: closed loft through swept sections failed: {error}")
2974                })
2975            })?
2976        }
2977        RingFrame::Open => match run.breaks.filter(|breaks| !breaks.is_empty()) {
2978            Some(breaks) => crate::loft_topology::loft_profile_brep_broken(&sections, breaks),
2979            None => loft_profile_brep(&sections),
2980        }
2981        .map_err(|error| {
2982            error.with_message(|error| {
2983                format!("sweepSolid: loft through swept sections failed: {error}")
2984            })
2985        })?,
2986    };
2987
2988    timing.lap("loft");
2989    if !run.measure_report {
2990        // The station refinement, tight-bend guard, loft validation and soundness
2991        // acceptance have all completed. Only solid-only callers reach this exit.
2992        return Ok(SweptChain { solid, report: None });
2993    }
2994    // --- 6. The MEASURED BOUND of what was just built
2995    //        (`sweep_topology/stations.rs`): the loft's own interpolants of the
2996    //        centre track and the section axes against the true path and the
2997    //        transported frame, and the built volume by quadrature against the
2998    //        kinematic sweep's. Read off the very sections the loft skinned.
2999    let moments = super::stations::section_moments(profile, origin, pu, pv).map_err(|error| {
3000        KernelRefusal::internal(
3001            KernelStage::Refine,
3002            "section_moments",
3003            format!("sweepSolid: the section's area could not be read: {error}"),
3004        )
3005    })?;
3006    let (pu_in_frame, pv_in_frame) = if rigid {
3007        ([pu.dot(t0), pu.dot(r0), pu.dot(s0)], [pv.dot(t0), pv.dot(r0), pv.dot(s0)])
3008    } else {
3009        ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0])
3010    };
3011    let report = super::stations::station_report(&super::stations::PlacedRun {
3012        chain: run.chain,
3013        params: run.params,
3014        points,
3015        tangents,
3016        axes: &placed_axes,
3017        centres: &centres,
3018        e1: &axes_1,
3019        e2: &axes_2,
3020        pu_in_frame,
3021        pv_in_frame,
3022        closed: closure.is_ring(),
3023        sections: &sections,
3024        moments,
3025        reach: super::stations::section_reach(profile, origin),
3026        shift: requested.shift,
3027        budget: run.budget,
3028        tolerance: run.tolerance,
3029        breaks: match closure {
3030            RingFrame::Open => run.breaks.filter(|breaks| !breaks.is_empty()),
3031            _ => run.breaks.filter(|_| requested.shift == 0),
3032        },
3033        slide_in_wall: !rigid
3034            && twist_angle == 0.0
3035            && station_scales.is_none()
3036            && !matches!(closure, RingFrame::Spatial),
3037    })?;
3038    timing.lap("approximation");
3039    Ok(SweptChain {
3040        solid,
3041        report: Some(report),
3042    })
3043}
3044
3045/// Helical sweep (§5.7): sweep a CLOSED PLANAR profile loop along a helix of
3046/// `helix_radius` about the axis through `axis_origin` with direction
3047/// `axis_direction`, rising `pitch` per revolution for `turns` revolutions.
3048///
3049/// Sample a helix — `turns` revolutions about `axis_direction` from
3050/// `axis_origin`, starting at angle `start_angle` (radians, measured from the
3051/// axis frame's `u`) and rising `pitch` per turn, the radius running linearly
3052/// from `start_radius` to `end_radius` — uniformly in angle: 64 stations per
3053/// turn (at least 9, at most 4097 in total, so beyond 64 turns the per-turn
3054/// density thins). Returns the points and their chord parameters `s ∈ [0,1]`
3055/// (uniform-in-angle IS chord-length for a constant-radius helix, which is
3056/// what the averaged-knot interpolation assumes). `left_handed` winds the
3057/// angle the other way. The axis frame is `w = axis`, `u` = the component of
3058/// `reference` perpendicular to the axis (so angle zero points AT the
3059/// reference — the helix feature's local +X, or its start point), falling
3060/// back to `w.perpendicular()` when there is no usable reference, and
3061/// `v = w × u`. Shared by [`sweep_profile_helix`] and the HX feature, so the
3062/// coil a sweep builds and the edge a helix feature publishes agree exactly.
3063///
3064/// Errors on a degenerate axis, non-finite inputs, `turns ≤ 0`, more than 256
3065/// turns, a negative radius or pitch, or a helix that is a single point (both
3066/// radii AND the pitch zero).
3067#[allow(clippy::too_many_arguments)]
3068pub fn helix_sample_points(
3069    axis_origin: Vec3,
3070    axis_direction: Vec3,
3071    reference: Option<Vec3>,
3072    start_radius: f64,
3073    end_radius: f64,
3074    pitch: f64,
3075    turns: f64,
3076    start_angle: f64,
3077    left_handed: bool,
3078) -> Result<(Vec<Vec3>, Vec<f64>), KernelRefusal> {
3079    use std::f64::consts::TAU;
3080    let w = axis_direction.normalized().map_err(|_| {
3081        KernelRefusal::input(
3082            KernelStage::Collect,
3083            "helix_axis",
3084            "helix: axis direction is degenerate",
3085        )
3086    })?;
3087    for (name, value) in [
3088        ("radius", start_radius),
3089        ("end radius", end_radius),
3090        ("pitch", pitch),
3091        ("turns", turns),
3092        ("start angle", start_angle),
3093    ] {
3094        if !value.is_finite() {
3095            return Err(KernelRefusal::input(
3096                KernelStage::Collect,
3097                "helix_finite",
3098                format!("helix: {name} must be a finite number"),
3099            ));
3100        }
3101    }
3102    if start_radius < 0.0 || end_radius < 0.0 {
3103        return Err(KernelRefusal::input(
3104            KernelStage::Collect,
3105            "helix_radius",
3106            "helix: radius must not be negative",
3107        ));
3108    }
3109    if pitch < 0.0 {
3110        return Err(KernelRefusal::input(
3111            KernelStage::Collect,
3112            "helix_pitch",
3113            "helix: pitch must not be negative",
3114        ));
3115    }
3116    if turns <= 0.0 {
3117        return Err(KernelRefusal::input(
3118            KernelStage::Collect,
3119            "helix_turns",
3120            "helix: turns must be positive",
3121        ));
3122    }
3123    if turns > 256.0 {
3124        return Err(KernelRefusal::input(
3125            KernelStage::Collect,
3126            "helix_turns_limit",
3127            "helix: turns must be at most 256",
3128        ));
3129    }
3130    if start_radius == 0.0 && end_radius == 0.0 && pitch == 0.0 {
3131        return Err(KernelRefusal::input(
3132            KernelStage::Collect,
3133            "helix_point",
3134            "helix: zero radius and zero pitch describe a single point",
3135        ));
3136    }
3137    let u = match reference {
3138        Some(reference) => {
3139            let radial = reference.sub(w.scale(reference.dot(w)));
3140            radial
3141                .normalized()
3142                .or_else(|_| w.perpendicular())
3143                .or_refuse(KernelStage::Collect, "perpendicular")?
3144        }
3145        None => w.perpendicular().or_refuse(KernelStage::Collect, "perpendicular")?,
3146    };
3147    let v = w.cross(u).normalized().or_refuse(KernelStage::Collect, "normalized")?;
3148    let total_angle = turns * TAU;
3149    let height = pitch * turns;
3150    let sign = if left_handed { -1.0 } else { 1.0 };
3151    let count = ((turns * 64.0).ceil() as usize + 1).clamp(9, 4097);
3152    let mut points = Vec::with_capacity(count);
3153    let mut parameters = Vec::with_capacity(count);
3154    for index in 0..count {
3155        let s = index as f64 / (count - 1) as f64;
3156        let theta = start_angle + sign * total_angle * s;
3157        let radius = start_radius + (end_radius - start_radius) * s;
3158        points.push(
3159            axis_origin
3160                .add(u.scale(radius * theta.cos()))
3161                .add(v.scale(radius * theta.sin()))
3162                .add(w.scale(height * s)),
3163        );
3164        parameters.push(s);
3165    }
3166    Ok((points, parameters))
3167}
3168
3169/// [`helix_sample_points`] fitted as ONE cubic curve (global interpolation —
3170/// `interpolate_curve`, the machinery every fitted path here uses). Cubic
3171/// interpolation error on a circle of radius R with node spacing Δθ is
3172/// ≈ R·Δθ⁴/384: ~2·10⁻⁷·R at 64 stations per turn.
3173#[allow(clippy::too_many_arguments)]
3174pub fn fit_helix_curve(
3175    axis_origin: Vec3,
3176    axis_direction: Vec3,
3177    reference: Option<Vec3>,
3178    start_radius: f64,
3179    end_radius: f64,
3180    pitch: f64,
3181    turns: f64,
3182    start_angle: f64,
3183    left_handed: bool,
3184) -> Result<NurbsCurve, KernelRefusal> {
3185    let (points, parameters) = helix_sample_points(
3186        axis_origin,
3187        axis_direction,
3188        reference,
3189        start_radius,
3190        end_radius,
3191        pitch,
3192        turns,
3193        start_angle,
3194        left_handed,
3195    )?;
3196    interpolate_curve(&points, 3, &parameters).or_refuse(KernelStage::Refine, "interpolate")
3197}
3198
3199/// The helix is transcendental, not exactly NURBS-representable, so the path
3200/// is FIT: points (R·cosθ, R·sinθ, pitch·θ/2π) in the axis frame are sampled
3201/// uniformly in θ and globally interpolated with a cubic (`interpolate_curve`
3202/// — the same machinery every other fitted path here uses).  DENSITY: 64
3203/// samples per turn, capped at 1025 total nodes.  Cubic interpolation error
3204/// on a circle of radius R with node spacing Δθ is ≈ R·Δθ⁴/384: ~2·10⁻⁷·R at
3205/// 64/turn, and still ~6·10⁻⁵·R at the cap's worst case (16/turn at the
3206/// 64-turn limit) — orders below any profile a caller could sweep without
3207/// self-intersecting.  Uniform-in-θ parameters are exact chord-length for a
3208/// helix (constant speed), which is what the averaged-knot interpolation
3209/// assumes.
3210///
3211/// The fitted path then drives the EXISTING path-sweep core with 32 stations
3212/// per turn (min 32, capped at 1024 — the loft's dense interpolation solve is
3213/// O(stations³) per control column, so the cap trades per-turn density, never
3214/// correctness, at high turn counts).
3215///
3216/// GUARDS beyond the path sweep's own: the path sweep documents
3217/// self-intersection as caller responsibility, so the helix variant — which
3218/// knows its curvature analytically — rejects the two garbage modes itself:
3219///   • fold-over: the helix curvature radius (R² + c²)/R (c = pitch/2π) must
3220///     exceed the profile's max extent about its centroid, or the tube folds
3221///     through itself on the inner side (the torus tube-radius > major-radius
3222///     failure, pitch-relaxed);
3223///   • coil collision (turns ≥ 1): the normal gap between consecutive coils,
3224///     pitch·2πR/√((2πR)² + pitch²), must exceed the profile diameter.
3225/// Both use the profile's max sample distance from its centroid — conservative
3226/// for asymmetric profiles (extent in a harmless direction still counts), but
3227/// a false reject beats silent garbage.
3228///
3229/// SHALLOW COILS BUILD. They did not until 2026-09-08: the loft measured its
3230/// advance by the END-TO-END chord, which on a whole-turn helix is purely
3231/// AXIAL while both caps face nearly tangentially, so `|n·chord|` fell under
3232/// the loft's 0.1 sliver band and everything with pitch ≲ 0.63·R — most
3233/// springs — was refused. The loft measures the advance at each END now
3234/// (`loft_topology::basic::advance_from`), which is the direction the tube
3235/// actually grows through the cap it is orienting, so the band only ever
3236/// catches a real sliver.
3237pub fn sweep_profile_helix(
3238    profile: &[NurbsCurve],
3239    axis_origin: Vec3,
3240    axis_direction: Vec3,
3241    helix_radius: f64,
3242    pitch: f64,
3243    turns: f64,
3244    name: Option<&str>,
3245) -> Result<BrepSolid, KernelRefusal> {
3246    use std::f64::consts::TAU;
3247
3248    // --- 1. Validate the helix parameters with honest errors.
3249    let w = axis_direction.normalized().map_err(|_| {
3250        KernelRefusal::input(
3251            KernelStage::Collect,
3252            "helix_axis",
3253            "sweep_profile_helix: axis direction is degenerate",
3254        )
3255    })?;
3256    if !(helix_radius.is_finite() && helix_radius > 0.0) {
3257        return Err(KernelRefusal::input(
3258            KernelStage::Collect,
3259            "helix_radius",
3260            "sweep_profile_helix: helix radius must be positive",
3261        ));
3262    }
3263    if !(pitch.is_finite() && pitch > 0.0) {
3264        return Err(KernelRefusal::input(
3265            KernelStage::Collect,
3266            "helix_pitch",
3267            "sweep_profile_helix: pitch must be positive",
3268        ));
3269    }
3270    if !(turns.is_finite() && turns > 0.0) {
3271        return Err(KernelRefusal::input(
3272            KernelStage::Collect,
3273            "helix_turns",
3274            "sweep_profile_helix: turns must be positive",
3275        ));
3276    }
3277    // 64 turns bounds the loft's O(stations³) interpolation solve; beyond it
3278    // the station cap would silently degrade per-turn density anyway.
3279    if turns > 64.0 {
3280        return Err(KernelRefusal::unsupported(
3281            KernelStage::Collect,
3282            "helix_turns_cap",
3283            "sweep_profile_helix: turns must be at most 64",
3284        ));
3285    }
3286
3287    // --- 2. Profile extent about its centroid, sampled exactly like the path
3288    //        sweep derives its placement origin (boundary-sample mean), so the
3289    //        extent is measured about the point that actually rides the path.
3290    let mut samples = Vec::new();
3291    for curve in profile {
3292        let [start, end] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
3293        for sample in 0..16 {
3294            samples.push(curve.evaluate(start + (end - start) * sample as f64 / 16.0).or_refuse(KernelStage::Collect, "evaluate")?);
3295        }
3296    }
3297    if !samples.is_empty() {
3298        let mut centroid = Vec3::default();
3299        for point in &samples {
3300            centroid = centroid.add(*point);
3301        }
3302        let origin = centroid.scale(1.0 / samples.len() as f64);
3303        let extent = samples
3304            .iter()
3305            .map(|point| point.sub(origin).length())
3306            .fold(0.0, f64::max);
3307        let c = pitch / TAU; // axial rise per radian
3308                             // Fold-over: profile reaches past the helix's center of curvature.
3309        let curvature_radius = (helix_radius * helix_radius + c * c) / helix_radius;
3310        if extent >= curvature_radius {
3311            return Err(KernelRefusal::unsupported(
3312                KernelStage::Classify,
3313                "helix_fold",
3314                format!(
3315                "sweep_profile_helix: profile extent {extent:.6} reaches the helix \
3316                 curvature radius {curvature_radius:.6}; the tube would fold through \
3317                 itself — increase the helix radius or pitch, or shrink the profile"
3318                ),
3319            ));
3320        }
3321        // Coil collision: only possible once the sweep spans a full revolution.
3322        if turns >= 1.0 {
3323            let circumference = TAU * helix_radius;
3324            let turn_length = (circumference * circumference + pitch * pitch).sqrt();
3325            let coil_gap = pitch * circumference / turn_length;
3326            if coil_gap <= 2.0 * extent {
3327                return Err(KernelRefusal::unsupported(
3328                    KernelStage::Classify,
3329                    "coil_collision",
3330                    format!(
3331                    "sweep_profile_helix: consecutive turns would self-intersect — \
3332                     coil gap {coil_gap:.6} does not clear the profile diameter {:.6}; \
3333                     increase the pitch or shrink the profile",
3334                    2.0 * extent
3335                    ),
3336                ));
3337            }
3338        }
3339    }
3340
3341    // --- 3. Fit the helical path (see the density rationale in the fn docs) —
3342    //        the SAME sampler + fit the HX feature publishes as its edge.
3343    let path = fit_helix_curve(
3344        axis_origin,
3345        w,
3346        None,
3347        helix_radius,
3348        helix_radius,
3349        pitch,
3350        turns,
3351        0.0,
3352        false,
3353    )
3354    .map_err(|error| {
3355        error.with_message(|error| format!("sweep_profile_helix: helix path fit failed: {error}"))
3356    })?;
3357
3358    // --- 4. Drive the existing sweep core; its (or the loft's) failures
3359    //        propagate with helix context prepended.
3360    // `BREP_HELIX_DENSE_STATIONS` (default ON since the 2026-11-05
3361    // promotion; `=0` restores 32) skins the tube at 64 stations a turn
3362    // instead of 32. At 32 the skinning error is the tube's
3363    // largest: brep-bench sweep/helical-pipe (r 1 on R 10, pitch 5, three
3364    // turns) reads its volume 4.3e-6 and its area 3.2e-6 under the closed
3365    // form πr²L, 2πrL; at 64 they read 3.9e-7 and 3.2e-7 (48: 8.8e-7), and
3366    // swept/ball-thread-groove 2.6e-7 and 2.7e-7. The path fit (64 samples a
3367    // turn) is already ~2e-8 of R and is unchanged.
3368    let per_turn = if switch!("BREP_HELIX_DENSE_STATIONS", true) { 64.0 } else { 32.0 };
3369    let stations = ((turns * per_turn).ceil() as usize).clamp(32, 1024);
3370    // The helix builder places the profile ON the fitted helix (the coil's
3371    // section is drawn once and carried round), which is `Transplant` by
3372    // construction — the radius comes from the helix argument, not the profile's
3373    // own position.
3374    sweep_profile_along_path_stations(
3375        profile,
3376        &path,
3377        name,
3378        stations,
3379        0.0,
3380        None,
3381        SectionPlacement::Transplant,
3382        SWEEP_DEFAULT_TOLERANCE,
3383        true,
3384    )
3385    .map(|swept| swept.solid)
3386    .map_err(|error| error.with_message(|error| format!("sweep_profile_helix: {error}")))
3387}
3388