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