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