brep_construction/construction/sweep_topology/path.rs
1use super::*;
2
3/// The largest tangent break, in radians, a chained path may have at a joint
4/// before the joint is a CORNER.
5///
6/// This is a REAL geometric boundary, not a tuning knob, and it now selects the
7/// LANE rather than deciding a refusal. The skinning builder lofts consecutive
8/// stations, so a corner between two stations would be rendered as a smooth
9/// blend across it — the tube cuts the corner, and near a sharp one the section
10/// sweeps through itself. So a break inside this band is skinned as ONE tube
11/// (line→fillet→line, spline pieces, an arc train), and a break past it is a
12/// corner, which is built a different way or not at all:
13/// - every segment STRAIGHT (a polyline, open or CLOSED) → the MITRE lane: the
14/// section is swept along each segment and the two sweeps are trimmed to
15/// the joint's bisector plane, sharing one face loop there
16/// ([`SweepPath::cornered_polyline`], `sweep_topology/miter.rs`). A closed one is
17/// a picture FRAME: its closing joint is a mitre like the rest and it has no
18/// caps at all;
19/// - a corner at a CURVED segment → refused by name. A curve has no single
20/// direction for a bisector plane to bisect, so there is no plane both
21/// sides can be trimmed to.
22///
23/// ~1.15° (0.02 rad). Loose enough to absorb the tangent disagreement of two
24/// curves a sketch chained on endpoint coincidence, tight enough that anything
25/// a user would call a corner is refused rather than silently rounded off.
26///
27/// This is INDEPENDENT of the chainer's join tolerance, and deliberately so.
28/// `common::chain_path_segments` joins on POSITION (`1e-5 * scale`); this gate
29/// measures DIRECTION. Two collinear segments meeting with a positional gap have
30/// a zero tangent break, and two segments meeting exactly at a point can still
31/// break 90°. So a run the chainer happily orders head-to-tail may still be
32/// refused by a consumer of this classification — which is not an inconsistency
33/// but the SW/SWP split itself: the chainer's job is to decide what order the
34/// picks form a run in, and this gate's job is to decide whether that run is one
35/// the skinning builder can carry a section along.
36pub const MAX_JOINT_TANGENT_BREAK: f64 = 0.02;
37
38/// How much the CURVATURE VECTOR may disagree across a joint, relative to the
39/// curvatures being compared, before the joint is G1 rather than G2.
40///
41/// Dimensionless and deliberately tiny: the two sides of a G2 joint are the same
42/// analytic curve evaluated from two parameterizations (two arcs of one circle,
43/// two collinear lines), so they agree to rounding — a dozen orders of magnitude
44/// inside this bar. Everything else separates by a FULL curvature: a line
45/// meeting a fillet of radius `r` jumps by `1/r`, an S-bend of two equal arcs by
46/// `2/r`. There is no population in between to tune against, which is why this
47/// number needs no tuning.
48const MAX_JOINT_CURVATURE_BREAK: f64 = 1e-9;
49
50/// How far a sampled path point may sit off its own fitted plane, relative to
51/// the path's extent, before the path is SPATIAL rather than planar.
52///
53/// Read only by the CLOSED lane, and the reason it is tight: a planar closed
54/// path transports a section round the loop and back to itself exactly (the
55/// frame's only rotation is about the plane normal, which comes back to where it
56/// started), while a spatial one returns the section rotated by the path's
57/// HOLONOMY. Calling a spatial path planar would mean skinning that mismatch
58/// into the ring instead of refusing it, so the bar admits only paths that are
59/// planar to rounding — a sketch-authored chain, or resident edges that share a
60/// plane — and refuses the rest by name.
61const MAX_PLANARITY_DEVIATION: f64 = 1e-7;
62
63/// How continuous a path is AT ONE JOINT — the classification every sweep
64/// refusal reads instead of re-deriving the same angle from the curves.
65///
66/// The three levels are the standard geometric ones, and each is decided by a
67/// measurement [`PathJoint`] carries beside it:
68/// - `G0` — the position matches and nothing else: the tangent turns by more
69/// than [`MAX_JOINT_TANGENT_BREAK`]. A corner.
70/// - `G1` — the unit tangents agree; the curvature VECTORS do not. A line
71/// meeting a fillet arc, two arcs of different radius, an S-bend of two
72/// equal arcs curving opposite ways.
73/// - `G2` — the unit tangents AND the curvature vectors agree. Two arcs of ONE
74/// circle (the shape a sketch publishes for a circle), two collinear lines.
75///
76/// G1 and G2 are not distinguished by any refusal today — the skinning builder
77/// needs G1 and is indifferent to the curvature jump, because it interpolates
78/// the stations rather than the segments. The distinction is recorded because it
79/// is the difference between a path whose swept surface is curvature-continuous
80/// and one whose is not, which is what a later curvature-driven station law
81/// (remaining work item 2) has to refine against.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum JointContinuity {
84 /// Position only — a corner.
85 G0,
86 /// Tangent continuous, curvature discontinuous.
87 G1,
88 /// Tangent and curvature continuous.
89 G2,
90}
91
92impl JointContinuity {
93 /// The `G0` / `G1` / `G2` spelling, for a message or a record.
94 pub fn label(self) -> &'static str {
95 match self {
96 JointContinuity::G0 => "G0",
97 JointContinuity::G1 => "G1",
98 JointContinuity::G2 => "G2",
99 }
100 }
101}
102
103/// ONE joint of a resolved path: which two segments meet there, how continuously
104/// ([`JointContinuity`]), and the two measurements that decided it.
105///
106/// `before`/`after` are INDICES into the path's segments, and the CLOSING joint
107/// of a closed path is `(n-1, 0)` — including the single-segment case `(0, 0)`,
108/// a lone closed curve meeting itself.
109#[derive(Debug, Clone, Copy)]
110pub struct PathJoint {
111 /// The segment ARRIVING at the joint (at its own domain end).
112 pub before: usize,
113 /// The segment DEPARTING from it (at its own domain start).
114 pub after: usize,
115 /// The angle between the arriving and departing UNIT TANGENTS, in radians.
116 /// The measured angle a corner refusal quotes.
117 pub tangent_break: f64,
118 /// `|Δk|` of the CURVATURE VECTOR across the joint, in 1/length. A vector
119 /// rather than a magnitude, so two equal arcs curving opposite ways (an
120 /// S-bend) read `2/r` rather than zero.
121 pub curvature_break: f64,
122 /// The level those two measurements put the joint at.
123 pub continuity: JointContinuity,
124 /// True for the joint that CLOSES a closed path (the last segment's end
125 /// meeting the first segment's start). An open path has none.
126 pub closing: bool,
127}
128
129/// A resolved sweep path AND its classification: the ordered, head-to-tail
130/// curves, the name of each, whether the run is CLOSED, the PLANE it lies in if
131/// it lies in one, and the continuity of every joint — the closing one included.
132///
133/// This is the sweep's path type, and the classification is computed ONCE, here,
134/// where the path is resolved. Before it, three refusals each derived their own
135/// answer to the same question from the same curves: the builder's corner gate
136/// measured a tangent break while sampling, the sampler decided a path was
137/// closed by comparing its first and last station, and `SW`'s `translate` mode
138/// inferred closure from the fact that a closed path's advances through the
139/// profile must sum to zero. They agreed, but nothing made them agree, and none
140/// of the three could SAY what it had found — a closed path was only ever
141/// reported as the consequence the refusing rule happened to notice.
142///
143/// ORDER AND ORIENTATION are the caller's: this classifies the chain it is
144/// given, segment order and each segment's direction untouched, so the first
145/// segment still decides which way the sweep runs.
146#[derive(Debug, Clone)]
147pub struct SweepPath {
148 /// The ordered, head-to-tail world curves.
149 pub curves: Vec<NurbsCurve>,
150 /// Each curve's source name, parallel to `curves`. A short or empty slice is
151 /// legal — [`SweepPath::name`] degrades to `<unnamed>` — because a caller
152 /// that builds a chain itself (the tube's bend runs, the wire harness'
153 /// spline spans) has no per-segment user-facing name to give.
154 pub names: Vec<String>,
155 /// The last segment's end returns to the first segment's start.
156 pub closed: bool,
157 /// The UNIT NORMAL of the plane the whole path lies in, when it lies in one
158 /// to within `MAX_PLANARITY_DEVIATION` of its own extent.
159 ///
160 /// `None` for a spatial path, and also for one whose sampled polygon
161 /// encloses no signed area to derive a normal from — a straight run, or a
162 /// figure-of-eight whose lobes cancel. Only the CLOSED lane reads this, and
163 /// a straight run is never closed.
164 pub planar: Option<Vec3>,
165 /// Every joint, in order: the interior ones `(0,1), (1,2), …`, then the
166 /// CLOSING one `(n-1, 0)` when the path is closed.
167 pub joints: Vec<PathJoint>,
168 /// Every segment is a STRAIGHT LINE — a degree-1 curve with two control
169 /// points, which is the test `SW`'s `translate` mode applies to a segment
170 /// before it reduces it to a chord.
171 ///
172 /// Read with [`Self::corner`] by the MITRE lane: a cornered run of straight
173 /// segments is a polyline, and a polyline corner is the one corner a sweep
174 /// can join exactly (see [`SweepPath::cornered_polyline`]). A corner at a CURVED
175 /// segment is not — there is no single bisector plane a curve's section can
176 /// be trimmed to — so the straightness of the segments, not the size of the
177 /// break, is what separates the two.
178 pub straight: bool,
179 /// Each segment's SCREW AXIS direction, parallel to `curves`: `Some` for a
180 /// segment its builder KNOWS is a helix about that axis, `None` for every
181 /// other curve. Unit length; its sign is irrelevant.
182 ///
183 /// Not measured here, and deliberately so: a helix's published curve is a
184 /// cubic FIT, and a fit is not a helix to any bar a classification could
185 /// hold it to without a tolerance keyed to the fit density — and a TAPERED
186 /// helix is not a constant-slope curve at all. The feature that wound the
187 /// helix hands its axis over instead ([`Self::with_screw_axes`]).
188 ///
189 /// Read only by the `Rigid` placement (SW `pathAlign`): on a helix the path's
190 /// own motion is the SCREW about this axis, and the rotation-minimizing frame
191 /// every other curve is carried by rolls away from that screw by the helix's
192 /// integrated torsion — 169.75° over three turns of a radius-5, pitch-5 coil.
193 pub screw_axes: Vec<Option<Vec3>>,
194}
195
196impl SweepPath {
197 /// Classify `curves` (ordered head-to-tail) into a path. `names` may be
198 /// shorter than `curves`, or empty.
199 pub fn new(curves: Vec<NurbsCurve>, names: Vec<String>) -> Result<Self, KernelRefusal> {
200 if curves.is_empty() {
201 return Err(KernelRefusal::input(
202 KernelStage::Collect,
203 "chain_empty",
204 "sweepSolid: path chain is empty",
205 ));
206 }
207 // --- Endpoints, and the SCALE every position test below is relative to.
208 // Same form as the chainer's (`1e-5 * scale`, floored at 1.0 so a
209 // path at the origin gets an absolute band): the two have to agree
210 // about closure, since the chainer STOPS extending a run when its
211 // tail returns to its head and this is what then reports that the
212 // run it produced is a ring.
213 let mut endpoints = Vec::with_capacity(curves.len());
214 for curve in &curves {
215 let [t0, t1] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
216 endpoints.push((curve.evaluate(t0).or_refuse(KernelStage::Classify, "evaluate")?, curve.evaluate(t1).or_refuse(KernelStage::Classify, "evaluate")?));
217 }
218 let first_start = endpoints[0].0;
219 let scale = endpoints
220 .iter()
221 .flat_map(|(a, b)| [a, b])
222 .map(|point| point.sub(first_start).length())
223 .fold(1.0_f64, f64::max);
224 let join_tolerance = 1e-5 * scale;
225
226 // --- Sample the run once, for the planarity fit and for the travelled
227 // distance the closure test needs a floor from. 16 per curve is the
228 // sampling density `profile_anchor` uses to judge a profile's own
229 // plane, so a path and a profile are held to the same resolution.
230 let mut samples = Vec::with_capacity(16 * curves.len() + 1);
231 for curve in &curves {
232 let [t0, t1] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
233 for index in 0..16 {
234 samples.push(curve.evaluate(t0 + (t1 - t0) * index as f64 / 16.0).or_refuse(KernelStage::Classify, "evaluate")?);
235 }
236 }
237 samples.push(endpoints[curves.len() - 1].1);
238 let travel: f64 = samples
239 .windows(2)
240 .map(|pair| pair[1].sub(pair[0]).length())
241 .sum();
242
243 // --- CLOSURE. The run returns to where it started, and has actually
244 // gone somewhere: a zero-length curve trivially ends where it began,
245 // and calling that a ring would send it into the closed lane instead
246 // of the zero-length refusal that names it.
247 let closed = travel > join_tolerance
248 && endpoints[curves.len() - 1]
249 .1
250 .sub(first_start)
251 .length()
252 <= join_tolerance;
253
254 // --- PLANARITY. Newell over the sampled polygon gives the candidate
255 // normal (exact for a planar sample set, whatever the winding), and
256 // the samples are then CHECKED against it — a normal that fits
257 // nothing is no answer. A degenerate normal (no enclosed area) is
258 // `None` rather than an error: an open straight run is a perfectly
259 // good path that simply has no one plane.
260 let planar = match crate::polygon::newell_normal(&samples).normalized() {
261 Ok(normal) => {
262 let deviation = samples
263 .iter()
264 .map(|point| point.sub(first_start).dot(normal).abs())
265 .fold(0.0_f64, f64::max);
266 (deviation <= MAX_PLANARITY_DEVIATION * scale).then_some(normal)
267 }
268 Err(_) => None,
269 };
270
271 // --- JOINTS, interior then closing. A closed single-curve path has
272 // exactly one joint — the curve meeting itself.
273 let mut joints = Vec::with_capacity(curves.len());
274 for index in 1..curves.len() {
275 joints.push(Self::joint(&curves, index - 1, index, false)?);
276 }
277 if closed {
278 joints.push(Self::joint(&curves, curves.len() - 1, 0, true)?);
279 }
280
281 // --- STRAIGHTNESS. The same test `SW`'s `translate` loop applies before
282 // it reduces a segment to its chord: a degree-1 curve with two
283 // control points. Recorded per PATH rather than per segment because
284 // every consumer asks about the whole run — the mitre lane needs all
285 // of them straight, and one curved segment is what sends a cornered
286 // run back to the refusal.
287 let straight = curves
288 .iter()
289 .all(|curve| curve.degree == 1 && curve.control_points.len() == 2);
290
291 let screw_axes = vec![None; curves.len()];
292 Ok(Self {
293 curves,
294 names,
295 closed,
296 planar,
297 joints,
298 straight,
299 screw_axes,
300 })
301 }
302
303 /// Attach each segment's SCREW AXIS ([`Self::screw_axes`]), parallel to the
304 /// curves. A zero axis is refused rather than silently read as "no axis".
305 pub fn with_screw_axes(mut self, axes: Vec<Option<Vec3>>) -> Result<Self, KernelRefusal> {
306 if axes.len() != self.curves.len() {
307 return Err(KernelRefusal::input(
308 KernelStage::Collect,
309 "screw_axes_count",
310 format!(
311 "sweepSolid: {} screw axes for a {}-segment path",
312 axes.len(),
313 self.curves.len()
314 ),
315 ));
316 }
317 self.screw_axes = axes
318 .into_iter()
319 .enumerate()
320 .map(|(index, axis)| {
321 axis.map(|axis| {
322 axis.normalized().map_err(|_| {
323 KernelRefusal::input(
324 KernelStage::Collect,
325 "screw_axis",
326 format!(
327 "sweepSolid: path segment '{}' has a degenerate screw axis",
328 self.name(index)
329 ),
330 )
331 })
332 })
333 .transpose()
334 })
335 .collect::<Result<_, _>>()?;
336 Ok(self)
337 }
338
339 /// Classify a borrowed chain — the entry a caller assembling curves for one
340 /// build uses ([`Self::new`] takes them by value for a caller that owns them).
341 pub fn from_curves(curves: &[NurbsCurve], names: &[String]) -> Result<Self, KernelRefusal> {
342 Self::new(curves.to_vec(), names.to_vec())
343 }
344
345 /// One joint's measurements and level. `before` is read at its domain END and
346 /// `after` at its domain START — the tangent the path ARRIVES with against
347 /// the one it DEPARTS with, which is the only pair that measures the joint
348 /// itself: sampling a station further along either side would fold that
349 /// segment's own curvature into the break and let a genuine corner through
350 /// on a curved segment.
351 fn joint(
352 curves: &[NurbsCurve],
353 before: usize,
354 after: usize,
355 closing: bool,
356 ) -> Result<PathJoint, KernelRefusal> {
357 let arriving = Self::frame_at(&curves[before], true, before, "end")?;
358 let departing = Self::frame_at(&curves[after], false, after, "start")?;
359 // Both unit, so the dot is the cosine of the break.
360 let tangent_break = arriving.0.dot(departing.0).clamp(-1.0, 1.0).acos();
361 let curvature_break = departing.1.sub(arriving.1).length();
362 let curvature_bar = MAX_JOINT_CURVATURE_BREAK
363 * (1.0 + arriving.1.length() + departing.1.length());
364 let continuity = if tangent_break > MAX_JOINT_TANGENT_BREAK {
365 JointContinuity::G0
366 } else if curvature_break > curvature_bar {
367 JointContinuity::G1
368 } else {
369 JointContinuity::G2
370 };
371 Ok(PathJoint {
372 before,
373 after,
374 tangent_break,
375 curvature_break,
376 continuity,
377 closing,
378 })
379 }
380
381 /// `(unit tangent, curvature vector)` at one end of one segment.
382 ///
383 /// The curvature VECTOR is `k = (r' × r'') × r' / |r'|⁴` — magnitude `κ`,
384 /// pointing at the centre of curvature — so it is invariant to the
385 /// parameterization (a rational arc is not parameterized in its own angle)
386 /// and it carries the bend's DIRECTION, which the magnitude alone does not.
387 /// A degree-1 segment has `r'' = 0` and so `k = 0`, which is the honest
388 /// reading: a line's curvature is zero.
389 fn frame_at(
390 curve: &NurbsCurve,
391 at_end: bool,
392 index: usize,
393 which: &str,
394 ) -> Result<(Vec3, Vec3), KernelRefusal> {
395 let [t0, t1] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
396 let parameter = if at_end { t1 } else { t0 };
397 let derivatives = curve.derivatives(parameter, 2).or_refuse(KernelStage::Classify, "derivatives")?;
398 let speed = derivatives[1].length();
399 let tangent = match derivatives[1].normalized() {
400 Ok(tangent) => tangent,
401 Err(_) => {
402 // A STATIONARY end (coincident end poles): the one-sided
403 // limit, or the refusal that names why there is none.
404 let side = if at_end { PathSide::Arriving } else { PathSide::Departing };
405 let limit = stationary_limit(curve, parameter, side)
406 .map_err(|fault| fault.refusal(&format!("the {which} of segment {index}"), parameter))?;
407 return Ok((limit.tangent, limit.curvature));
408 }
409 };
410 let curvature = derivatives[1]
411 .cross(derivatives[2])
412 .cross(derivatives[1])
413 .scale(1.0 / speed.powi(4));
414 Ok((tangent, curvature))
415 }
416
417 /// The number of segments.
418 pub fn len(&self) -> usize {
419 self.curves.len()
420 }
421
422 /// No segments — impossible through [`Self::new`], which refuses one.
423 pub fn is_empty(&self) -> bool {
424 self.curves.is_empty()
425 }
426
427 /// Segment `index`'s name, degrading to `<unnamed>` for a caller that named
428 /// none.
429 pub fn name(&self, index: usize) -> &str {
430 self.names
431 .get(index)
432 .map(String::as_str)
433 .unwrap_or("<unnamed>")
434 }
435
436 /// The first CORNER (a `G0` joint), if the path has one — what a builder that
437 /// skins between stations refuses on.
438 pub fn corner(&self) -> Option<&PathJoint> {
439 self.joints
440 .iter()
441 .find(|joint| joint.continuity == JointContinuity::G0)
442 }
443
444 /// This path is a CORNERED POLYLINE: every segment straight, with at least
445 /// one `G0` joint. The MITRE lane's selector, and the one predicate both the
446 /// builder and the two features read — the builder to pick the lane, the
447 /// features to know how many faces to name (one wall per segment × section
448 /// edge, rather than one per section edge).
449 ///
450 /// Each clause is a separate geometric reason:
451 /// - STRAIGHT, because a mitre trims both sides to ONE plane, and only a
452 /// straight segment has a single direction for that plane to bisect;
453 /// - a CORNER, because a tangent-continuous polyline (collinear segments)
454 /// is already carried by the skinning lane, which must keep it.
455 ///
456 /// CLOSED IS NOT A CLAUSE, and that is this predicate's whole content: a
457 /// closed cornered polyline — a picture FRAME — is mitred at every joint
458 /// INCLUDING the closing one, and comes out as one wall per (segment ×
459 /// section curve) with no caps at all. On a PLANAR loop the joint rotations
460 /// are all about the path plane's normal and sum to the loop's total turning,
461 /// `±2π`, so the section carried once round comes back as itself and the
462 /// closing mitre is built exactly like the others (`sweep_topology/miter.rs`
463 /// derives it, and measures the residual it predicts to be zero). A SPATIAL
464 /// loop's section returns rolled by the path's own holonomy, and the lane
465 /// closes it with a counter-twist shared over the sides — the same closure
466 /// policy the smooth ring lane applies ([`crate::SweepClosure`]).
467 ///
468 /// So this answers "is this the MITRE lane", and [`Self::closed`] answers
469 /// "does the result have caps". Both features read both.
470 pub fn cornered_polyline(&self) -> bool {
471 self.straight && self.corner().is_some()
472 }
473}
474
475// ===========================================================================
476// A STATIONARY path parameter: where the first derivative vanishes
477// ===========================================================================
478
479/// Which side of a parameter a stationary reading is taken from: the path
480/// LEAVING it (the span after a station) or ARRIVING at it (a segment's end).
481#[derive(Clone, Copy, Debug, PartialEq, Eq)]
482pub(super) enum PathSide {
483 Departing,
484 Arriving,
485}
486
487/// The one-sided limit of a path's direction and bend at a stationary
488/// parameter ([`stationary_limit`]).
489#[derive(Clone, Copy, Debug)]
490pub(super) struct StationaryLimit {
491 /// The unit direction of travel (increasing parameter) on the side read.
492 pub tangent: Vec3,
493 /// The limit of the curvature vector `κ·N̂`; zero where the path leaves
494 /// its tangent line slower than a circle would.
495 pub curvature: Vec3,
496}
497
498/// Why a stationary parameter has no limit to report.
499#[derive(Clone, Debug)]
500pub(super) enum StationaryFault {
501 /// Every derivative the curve carries vanishes: no direction exists.
502 Everywhere,
503 /// The path leaves its tangent line at order `leaves`, below twice the
504 /// order `order` it leaves its point at, so `κ` grows without bound as
505 /// `κ ≈ coefficient · s^(-exponent)` in arc length `s` from the point.
506 Unbounded { order: usize, leaves: usize, coefficient: f64, exponent: f64 },
507 /// The two sides leave in opposite directions (or at an angle): the
508 /// curve turns back on itself here — a cusp, not a bend.
509 Reverses { angle: f64 },
510 /// A rational curve whose bend is not settled by the derivatives it can
511 /// report (orders past its degree), or an evaluation that failed.
512 Unreadable(String),
513}
514
515impl StationaryFault {
516 /// The refusal for this fault at `where_` (e.g. "the start of segment 0").
517 pub(super) fn refusal(&self, where_: &str, parameter: f64) -> KernelRefusal {
518 match self {
519 StationaryFault::Everywhere | StationaryFault::Unreadable(_) => KernelRefusal::input(
520 KernelStage::Classify,
521 "path_tangent",
522 match self {
523 StationaryFault::Unreadable(detail) => format!(
524 "sweepSolid: path tangent is degenerate at {where_} (t = {parameter}): the \
525 parameter is stationary there and its one-sided limit could not be read \
526 ({detail})"
527 ),
528 _ => format!(
529 "sweepSolid: path tangent is degenerate at {where_} (t = {parameter}): \
530 every derivative of the curve vanishes there"
531 ),
532 },
533 ),
534 StationaryFault::Unbounded { order, leaves, coefficient, exponent } => KernelRefusal::input(
535 KernelStage::Classify,
536 "path_curvature",
537 format!(
538 "sweepSolid: the path's curvature is unbounded at {where_} (t = {parameter}): \
539 the parameter is stationary there (first non-zero derivative of order \
540 {order}) and the curve leaves its tangent line at order {leaves}, below \
541 {double}, so κ ≈ {coefficient:.4e}·s^-{exponent:.3} in arc length s from \
542 that point and any section folds through itself beside it. A section \
543 reaching d into the bend folds over the first (d·{coefficient:.4e})^{inverse:.3} \
544 of the path. Give the path a non-zero tangent there (separate the coincident \
545 control points) or trim the stationary end off",
546 double = 2 * order,
547 inverse = 1.0 / exponent,
548 ),
549 ),
550 StationaryFault::Reverses { angle } => KernelRefusal::input(
551 KernelStage::Classify,
552 "path_cusp",
553 format!(
554 "sweepSolid: the path turns back on itself at {where_} (t = {parameter}): the \
555 parameter is stationary there and the curve leaves it {:.3}° away from the \
556 direction it arrived in — a cusp, which no section can be carried round. \
557 Split the path at the cusp and sweep the pieces",
558 angle.to_degrees()
559 ),
560 ),
561 }
562 }
563}
564
565/// The relative floor under which a Taylor term of the path is read as zero:
566/// the term's size over the knot span, `|C⁽ʲ⁾|·hʲ/j!`, against the control
567/// net's extent. Far below any modelling tolerance, far above the round-off of
568/// a derivative assembled from coincident control points (exactly zero).
569const STATIONARY_TERM_FLOOR: f64 = 1e-9;
570
571/// The one-sided direction and curvature of `curve` at a parameter where its
572/// first derivative vanishes, read off the curve's Taylor expansion there
573/// rather than probed.
574///
575/// Write `C(t + σh) − C(t) = a·(σh)ᵏ/k! + … + b⊥·(σh)ᵐ/m! + …` with `a` the
576/// first non-zero derivative and `b⊥` the first derivative with a component
577/// across `a`. In arc length `s ∝ hᵏ` the path leaves its tangent line as
578/// `y ∝ s^(m/k)`, so
579///
580/// ```text
581/// m > 2k: κ → 0
582/// m = 2k: κ → 2·(|b⊥|/(2k)!)·(k!)²/|a|², towards b⊥
583/// m < 2k: κ → ∞ (refused, StationaryFault::Unbounded)
584/// ```
585///
586/// (`k = 1` is the regular reading `C''⊥/|C'|²`.) The direction of travel on
587/// side `σ` is `σ^(k−1)·â`: a parameter stationary to EVEN order inside a
588/// span turns the curve back on itself, and at an interior parameter both
589/// sides are read (on the halves of a split, so a knot there is honoured) and
590/// refused as a cusp when they disagree by more than a joint may
591/// ([`MAX_JOINT_TANGENT_BREAK`]). A three-pole straight run (`k = 3`, no
592/// component across) reads `κ = 0`; a parabola parameterized as `(t³, t⁶)`
593/// reads `κ = 2` at its vertex, as `(t, t²)` does.
594///
595/// Orders are read up to the curve's degree. Past it a polynomial's
596/// derivatives are exactly zero; a rational curve's are not, so a rational
597/// curve whose bend is not settled by then is [`StationaryFault::Unreadable`].
598pub(super) fn stationary_limit(
599 curve: &NurbsCurve,
600 parameter: f64,
601 side: PathSide,
602) -> Result<StationaryLimit, StationaryFault> {
603 let unreadable = |error: String| StationaryFault::Unreadable(error);
604 let [t0, t1] = curve.domain().map_err(unreadable)?;
605 let span = (t1 - t0).abs();
606 let interior = parameter > t0 + 1e-12 * span.max(1.0) && parameter < t1 - 1e-12 * span.max(1.0);
607 let limit = |(tangent, curvature): (Vec3, Result<Vec3, StationaryFault>)| {
608 curvature.map(|curvature| StationaryLimit { tangent, curvature })
609 };
610 if !interior {
611 let side = if parameter <= t0 + 1e-12 * span.max(1.0) { PathSide::Departing } else { PathSide::Arriving };
612 return limit(one_sided_limit(curve, parameter, side)?);
613 }
614 // Inside the domain: read each side on its own half, so a knot of
615 // reduced continuity at the parameter is read from the side it belongs to.
616 // The directions are compared FIRST: a cusp is a cusp whatever its bend
617 // (the semicubical one's is unbounded on both sides too).
618 let (before, after) = curve.split(parameter).map_err(unreadable)?;
619 let arriving = one_sided_limit(&before, before.domain().map_err(unreadable)?[1], PathSide::Arriving)?;
620 let departing = one_sided_limit(&after, after.domain().map_err(unreadable)?[0], PathSide::Departing)?;
621 let angle = arriving.0.dot(departing.0).clamp(-1.0, 1.0).acos();
622 if angle > MAX_JOINT_TANGENT_BREAK {
623 return Err(StationaryFault::Reverses { angle });
624 }
625 // Both sides must have a bend: a station there carries the span BEFORE it
626 // as well as the one after, so an unbounded side is refused whichever
627 // side the caller reads.
628 let arriving = limit(arriving)?;
629 let departing = limit(departing)?;
630 Ok(match side {
631 PathSide::Departing => departing,
632 PathSide::Arriving => arriving,
633 })
634}
635
636/// [`stationary_limit`] at a parameter that is an END of `curve`'s domain,
637/// read from the side the domain lies on: the direction of travel, and the
638/// curvature limit or the fault that says there is none.
639fn one_sided_limit(
640 curve: &NurbsCurve,
641 parameter: f64,
642 side: PathSide,
643) -> Result<(Vec3, Result<Vec3, StationaryFault>), StationaryFault> {
644 let unreadable = |error: String| StationaryFault::Unreadable(error);
645 let degree = curve.degree;
646 let rational = curve
647 .control_points
648 .iter()
649 .any(|point| (point.w - curve.control_points[0].w).abs() > 1e-15 * point.w.abs().max(1.0));
650 let derivatives = curve.derivatives(parameter, degree).map_err(unreadable)?;
651 // The knot span on the side read: the Taylor terms are sized over it.
652 let h = {
653 let mut knots: Vec<f64> = curve.knots.clone();
654 knots.dedup_by(|a, b| (*a - *b).abs() <= 0.0);
655 let (lower, upper) = match side {
656 PathSide::Departing => (
657 parameter,
658 knots.iter().copied().find(|knot| *knot > parameter).unwrap_or(parameter),
659 ),
660 PathSide::Arriving => (
661 knots.iter().rev().copied().find(|knot| *knot < parameter).unwrap_or(parameter),
662 parameter,
663 ),
664 };
665 upper - lower
666 };
667 if !(h > 0.0) {
668 return Err(StationaryFault::Unreadable(format!("no knot span on the {side:?} side of t = {parameter}")));
669 }
670 let size = {
671 let points: Vec<Vec3> = curve
672 .control_points
673 .iter()
674 .map(|point| point.point())
675 .collect::<Result<_, _>>()
676 .map_err(unreadable)?;
677 let mut low = points[0];
678 let mut high = points[0];
679 for point in &points {
680 low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
681 high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
682 }
683 high.sub(low).length()
684 };
685 if !(size > 0.0) {
686 return Err(StationaryFault::Everywhere);
687 }
688 // `|v|·hʲ/j!` — the size of the j-th Taylor term over the span.
689 let mut factorial = [1.0f64; 32];
690 for index in 1..factorial.len() {
691 factorial[index] = factorial[index - 1] * index as f64;
692 }
693 let term = |order: usize, vector: Vec3| vector.length() * h.powi(order as i32) / factorial[order.min(31)];
694 let floor = STATIONARY_TERM_FLOOR * size;
695 let order = (1..=degree.min(31))
696 .find(|&order| term(order, derivatives[order]) > floor)
697 .ok_or(StationaryFault::Everywhere)?;
698 let a = derivatives[order];
699 let along = a.normalized().map_err(unreadable)?;
700 let sign = match side {
701 PathSide::Departing => 1.0,
702 PathSide::Arriving => {
703 if (order - 1) % 2 == 0 {
704 1.0
705 } else {
706 -1.0
707 }
708 }
709 };
710 let tangent = along.scale(sign);
711 let across = |vector: Vec3| vector.sub(along.scale(vector.dot(along)));
712 let leaves = (order + 1..=degree.min(31)).find(|&leaves| term(leaves, across(derivatives[leaves])) > floor);
713 let curvature = match leaves {
714 None if rational => Err(StationaryFault::Unreadable(format!(
715 "a rational curve stationary to order {order} with no bend up to its degree {degree}"
716 ))),
717 None => Ok(Vec3::default()),
718 Some(leaves) if leaves > 2 * order => Ok(Vec3::default()),
719 Some(leaves) if leaves == 2 * order => {
720 let bend = across(derivatives[leaves]);
721 let scale = 2.0 / factorial[leaves] * factorial[order] * factorial[order] / a.dot(a);
722 Ok(bend.scale(scale))
723 }
724 Some(leaves) => {
725 // y = c·x^q with x = |a|hᵏ/k!, y = |b⊥|hᵐ/m!, q = m/k < 2, so
726 // κ ≈ y'' = c·q·(q − 1)·x^(q − 2).
727 let q = leaves as f64 / order as f64;
728 let c = (across(derivatives[leaves]).length() / factorial[leaves])
729 / (a.length() / factorial[order]).powf(q);
730 Err(StationaryFault::Unbounded {
731 order,
732 leaves,
733 coefficient: c * q * (q - 1.0),
734 exponent: 2.0 - q,
735 })
736 }
737 };
738 Ok((tangent, curvature))
739}
740