Skip to main content

brep_kernel/geometry/
curve.rs

1use crate::Vec3;
2use serde::{Deserialize, Serialize};
3
4const EPS: f64 = 1e-12;
5
6/// Knot IDENTITY tolerance (parameter-space): two knot parameters within this
7/// absolute band are treated as the SAME knot for snapping — insert_knot,
8/// `NurbsCurve::split`, monotonicity and clamp checks.  This is the single
9/// source for the "absolute 1e-9 knot tolerance" that `split` enforces and
10/// that imprint's trim guards mirror.  Distinct in PURPOSE (not just value)
11/// from [`KNOT_DEDUP_EPS`]; the two are deliberately NOT unified.
12pub const KNOT_IDENTITY_TOL: f64 = 1e-9;
13
14/// Numerical knot DEDUP epsilon (parameter-space): the tighter floor used when
15/// *counting distinct* knots (SSI/CSI `interior_knot_count`) or comparing whole
16/// knot vectors for exact reconstruction (analytic surface recognition).  This
17/// answers "are these two knot floats the same value?", NOT "are these the same
18/// knot for snapping?" — so it stays at 1e-12 and must NOT be unified with the
19/// looser [`KNOT_IDENTITY_TOL`].
20///
21/// Comparand: the absolute difference of two knot values of ONE knot vector,
22/// and a knot's distance from either end of the active domain
23/// (`knots[degree]`, `knots[len − 1 − degree]`), in that curve's parameter
24/// units. Two knots within it count as one, and a knot within it of an end is
25/// not interior. The containment lanes' per-pcurve sample count
26/// ([`crate::trim_sample_count`]) counts interior knots this way.
27pub const KNOT_DEDUP_EPS: f64 = 1e-12;
28
29/// Count distinct knots strictly inside a valid knot vector's active domain.
30/// Multiplicities and values within [`KNOT_DEDUP_EPS`] of the domain ends are
31/// ignored. Used to choose sampling density for intersections and containment.
32pub(crate) fn interior_knot_count(knots: &[f64], degree: usize) -> usize {
33    distinct_interior_knots(knots, degree).count()
34}
35
36fn distinct_interior_knots(knots: &[f64], degree: usize) -> impl Iterator<Item = f64> + '_ {
37    let start = knots[degree];
38    let end = knots[knots.len() - 1 - degree];
39    let mut previous = None;
40    knots.iter().copied().filter(move |&knot| {
41        if knot <= start + KNOT_DEDUP_EPS || knot >= end - KNOT_DEDUP_EPS {
42            return false;
43        }
44        if previous.is_none_or(|value: f64| (value - knot).abs() > KNOT_DEDUP_EPS) {
45            previous = Some(knot);
46            true
47        } else {
48            false
49        }
50    })
51}
52
53#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
54pub struct Vec4 {
55    pub x: f64,
56    pub y: f64,
57    pub z: f64,
58    pub w: f64,
59}
60
61/// Construct a line in the parameter plane (z = 0).
62pub(crate) fn parameter_line(u0: f64, v0: f64, u1: f64, v1: f64) -> Result<NurbsCurve, String> {
63    make_line(Vec3::new(u0, v0, 0.0), Vec3::new(u1, v1, 0.0))
64}
65
66/// Project a curve onto plane axes while preserving its knots and rational weights.
67pub(crate) fn curve_to_plane_parameters(
68    curve: &NurbsCurve,
69    origin: Vec3,
70    x_axis: Vec3,
71    y_axis: Vec3,
72) -> Result<NurbsCurve, String> {
73    NurbsCurve::new(
74        curve.degree,
75        curve.knots.clone(),
76        curve
77            .control_points
78            .iter()
79            .map(|point| {
80                let euclidean = Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w);
81                let delta = euclidean.sub(origin);
82                Vec4 {
83                    x: delta.dot(x_axis) * point.w,
84                    y: delta.dot(y_axis) * point.w,
85                    z: 0.0,
86                    w: point.w,
87                }
88            })
89            .collect(),
90    )
91}
92
93impl Vec4 {
94    pub fn from_point(point: Vec3, weight: f64) -> Self {
95        Self {
96            x: point.x * weight,
97            y: point.y * weight,
98            z: point.z * weight,
99            w: weight,
100        }
101    }
102
103    pub(crate) fn add(self, rhs: Self) -> Self {
104        Self {
105            x: self.x + rhs.x,
106            y: self.y + rhs.y,
107            z: self.z + rhs.z,
108            w: self.w + rhs.w,
109        }
110    }
111
112    pub(crate) fn scale(self, factor: f64) -> Self {
113        Self {
114            x: self.x * factor,
115            y: self.y * factor,
116            z: self.z * factor,
117            w: self.w * factor,
118        }
119    }
120
121    pub(crate) fn point(self) -> Result<Vec3, String> {
122        if self.w.abs() <= EPS {
123            return Err("cannot project a homogeneous point with zero weight".into());
124        }
125        Ok(Vec3::new(self.x / self.w, self.y / self.w, self.z / self.w))
126    }
127}
128
129/// Largest degree served by the allocation-free stack-array basis engine.
130/// Higher degrees (rare: only externally imported geometry) fall back to the
131/// heap-allocating `KnotVector` path.
132pub(crate) const MAX_STACK_DEGREE: usize = 7;
133pub(crate) const MAX_STACK_ORDER: usize = MAX_STACK_DEGREE + 1;
134
135/// `BREP_DEBUG_KNOTS=1` diagnostic for a rejected knot vector: dumps the whole
136/// vector (plus a backtrace) to stderr and appends it to the returned message,
137/// so a knot failure buried behind a `Result` that a caller only prints —
138/// STEP import's `first_error`, say — still names the offending construction
139/// site. Off by default; the message stays byte-identical without the var.
140fn knot_reject(reason: &str, knots: &[f64], degree: usize) -> String {
141    if std::env::var("BREP_DEBUG_KNOTS").is_err() {
142        return reason.to_string();
143    }
144    let mut worst_descent = f64::NEG_INFINITY;
145    let mut worst_index = 0usize;
146    for (index, pair) in knots.windows(2).enumerate() {
147        let descent = pair[0] - pair[1];
148        if descent > worst_descent {
149            worst_descent = descent;
150            worst_index = index;
151        }
152    }
153    let detail = format!(
154        "{reason} [degree={degree} count={} worst_descent={worst_descent:.6e} at index \
155         {worst_index} knots={knots:?}]",
156        knots.len()
157    );
158    eprintln!(
159        "KNOT-REJECT {detail}\n{}",
160        std::backtrace::Backtrace::force_capture()
161    );
162    detail
163}
164
165/// Validation shared by `KnotVector::new` and the lazily-validated
166/// curve/surface types. Must stay the single source of truth so cached
167/// validation and eager validation reject exactly the same inputs.
168pub(crate) fn validate_knots(knots: &[f64], degree: usize) -> Result<(), String> {
169    if degree < 1 {
170        return Err("KnotVector: degree must be >= 1".into());
171    }
172    if knots.len() < 2 * (degree + 1) {
173        return Err(format!(
174            "KnotVector: need at least {} knots for degree {}, got {}",
175            2 * (degree + 1),
176            degree,
177            knots.len()
178        ));
179    }
180    if knots.iter().any(|value| !value.is_finite()) {
181        return Err("KnotVector: knots must be finite".into());
182    }
183    if knots
184        .windows(2)
185        .any(|pair| pair[1] < pair[0] - KNOT_IDENTITY_TOL)
186    {
187        return Err(knot_reject(
188            "KnotVector: knots must be non-decreasing",
189            knots,
190            degree,
191        ));
192    }
193    let first = knots[0];
194    let last = knots[knots.len() - 1];
195    for index in 0..=degree {
196        if (knots[index] - first).abs() > KNOT_IDENTITY_TOL {
197            return Err(knot_reject(
198                "KnotVector: expected clamped start",
199                knots,
200                degree,
201            ));
202        }
203        if (knots[knots.len() - 1 - index] - last).abs() > KNOT_IDENTITY_TOL {
204            return Err(knot_reject("KnotVector: expected clamped end", knots, degree));
205        }
206    }
207    if last - first <= KNOT_IDENTITY_TOL {
208        return Err(knot_reject(
209            "KnotVector: degenerate parameter range",
210            knots,
211            degree,
212        ));
213    }
214    Ok(())
215}
216
217pub(crate) fn knot_domain(knots: &[f64], degree: usize) -> [f64; 2] {
218    [knots[degree], knots[knots.len() - 1 - degree]]
219}
220
221pub(crate) fn knot_clamp(knots: &[f64], degree: usize, parameter: f64) -> f64 {
222    let [start, end] = knot_domain(knots, degree);
223    parameter.clamp(start, end)
224}
225
226pub(crate) fn knot_find_span(knots: &[f64], degree: usize, parameter: f64) -> usize {
227    let parameter = knot_clamp(knots, degree, parameter);
228    let n = knots.len() - degree - 2;
229    if parameter >= knots[n + 1] {
230        // At/after the domain end.  A properly clamped vector has the end knot
231        // at multiplicity exactly `degree + 1`, so span `n` is the last
232        // non-empty interval.  An over-clamped end (a vendor exporter can emit
233        // multiplicity > degree + 1, e.g. two coincident knot VALUES) leaves
234        // span `n` pointing at a zero-width interval whose basis functions are
235        // all zero.  Walk back to the last interval that actually has width.
236        let mut span = n;
237        while span > degree && knots[span] >= knots[span + 1] {
238            span -= 1;
239        }
240        return span;
241    }
242    if parameter <= knots[degree] {
243        // At/before the domain start — the mirror of the case above.  For a
244        // properly clamped start (multiplicity degree + 1) this returns
245        // `degree`; for an over-clamped start it advances past the extra
246        // coincident knots to the first non-empty interval so evaluation never
247        // lands on a zero-width span (which would yield an all-zero,
248        // zero-weight homogeneous point).
249        let mut span = degree;
250        while span < n && knots[span + 1] <= parameter {
251            span += 1;
252        }
253        return span;
254    }
255    let mut low = degree;
256    let mut high = n + 1;
257    let mut middle = (low + high) / 2;
258    while parameter < knots[middle] || parameter >= knots[middle + 1] {
259        if parameter < knots[middle] {
260            high = middle;
261        } else {
262            low = middle;
263        }
264        middle = (low + high) / 2;
265    }
266    middle
267}
268
269/// Cox–de Boor basis functions into a caller-provided stack array.
270/// Requires `degree <= MAX_STACK_DEGREE`; entries `0..=degree` are written.
271pub(crate) fn basis_functions_into(
272    knots: &[f64],
273    degree: usize,
274    span: usize,
275    parameter: f64,
276    basis: &mut [f64; MAX_STACK_ORDER],
277) {
278    debug_assert!(degree <= MAX_STACK_DEGREE);
279    let mut left = [0.0f64; MAX_STACK_ORDER];
280    let mut right = [0.0f64; MAX_STACK_ORDER];
281    basis[0] = 1.0;
282    for j in 1..=degree {
283        left[j] = parameter - knots[span + 1 - j];
284        right[j] = knots[span + j] - parameter;
285        let mut saved = 0.0;
286        for r in 0..j {
287            let denominator = right[r + 1] + left[j - r];
288            let temporary = if denominator.abs() <= EPS {
289                0.0
290            } else {
291                basis[r] / denominator
292            };
293            basis[r] = saved + right[r + 1] * temporary;
294            saved = left[j - r] * temporary;
295        }
296        basis[j] = saved;
297    }
298}
299
300/// Basis derivatives (The NURBS Book A2.3) into caller-provided stack rows.
301/// Writes rows `0..=min(derivative_count, degree)` of `out`; rows above the
302/// degree keep whatever the caller initialized them to (callers zero-fill,
303/// matching the heap implementation's zero rows). Requires
304/// `degree <= MAX_STACK_DEGREE` and `out.len() > derivative_count`.
305pub(crate) fn basis_derivatives_into(
306    knots: &[f64],
307    degree: usize,
308    span: usize,
309    parameter: f64,
310    derivative_count: usize,
311    out: &mut [[f64; MAX_STACK_ORDER]],
312) {
313    debug_assert!(degree <= MAX_STACK_DEGREE);
314    debug_assert!(out.len() > derivative_count);
315    let p = degree;
316    let n = derivative_count.min(p);
317    let mut ndu = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
318    let mut left = [0.0f64; MAX_STACK_ORDER];
319    let mut right = [0.0f64; MAX_STACK_ORDER];
320    ndu[0][0] = 1.0;
321
322    for j in 1..=p {
323        left[j] = parameter - knots[span + 1 - j];
324        right[j] = knots[span + j] - parameter;
325        let mut saved = 0.0;
326        for r in 0..j {
327            ndu[j][r] = right[r + 1] + left[j - r];
328            let temporary = if ndu[j][r].abs() <= EPS {
329                0.0
330            } else {
331                ndu[r][j - 1] / ndu[j][r]
332            };
333            ndu[r][j] = saved + right[r + 1] * temporary;
334            saved = left[j - r] * temporary;
335        }
336        ndu[j][j] = saved;
337    }
338
339    for j in 0..=p {
340        out[0][j] = ndu[j][p];
341    }
342    let mut a = [[0.0f64; MAX_STACK_ORDER]; 2];
343    for r in 0..=p {
344        let mut s1 = 0;
345        let mut s2 = 1;
346        a[0][0] = 1.0;
347        for k in 1..=n {
348            a[s2] = [0.0; MAX_STACK_ORDER];
349            let mut value = 0.0;
350            let rk = r as isize - k as isize;
351            let pk = p - k;
352            if r >= k {
353                let denominator = ndu[pk + 1][rk as usize];
354                a[s2][0] = a[s1][0] / denominator;
355                value = a[s2][0] * ndu[rk as usize][pk];
356            }
357            let j1 = if rk >= -1 { 1 } else { (-rk) as usize };
358            let j2 = if r <= pk + 1 { k - 1 } else { p - r };
359            if j1 <= j2 {
360                for j in j1..=j2 {
361                    let index = (rk + j as isize) as usize;
362                    a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][index];
363                    value += a[s2][j] * ndu[index][pk];
364                }
365            }
366            if r <= pk {
367                a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r];
368                value += a[s2][k] * ndu[r][pk];
369            }
370            out[k][r] = value;
371            std::mem::swap(&mut s1, &mut s2);
372        }
373    }
374    let mut factor = p as f64;
375    for k in 1..=n {
376        for value in out[k][..=p].iter_mut() {
377            *value *= factor;
378        }
379        factor *= (p - k) as f64;
380    }
381}
382
383#[derive(Clone, Debug, Deserialize, Serialize)]
384pub struct KnotVector {
385    pub knots: Vec<f64>,
386    pub degree: usize,
387}
388
389/// Distinct interior knots, excluding endpoint neighborhoods within `1e-12`.
390pub(crate) fn interior_knots(knots: &[f64], degree: usize) -> Vec<f64> {
391    distinct_interior_knots(knots, degree).collect()
392}
393
394impl KnotVector {
395    pub fn new(knots: Vec<f64>, degree: usize) -> Result<Self, String> {
396        validate_knots(&knots, degree)?;
397        Ok(Self { knots, degree })
398    }
399
400    pub fn control_point_count(&self) -> usize {
401        self.knots.len() - self.degree - 1
402    }
403
404    pub fn domain(&self) -> [f64; 2] {
405        [
406            self.knots[self.degree],
407            self.knots[self.knots.len() - 1 - self.degree],
408        ]
409    }
410
411    pub fn clamp_param(&self, parameter: f64) -> f64 {
412        knot_clamp(&self.knots, self.degree, parameter)
413    }
414
415    pub fn find_span(&self, parameter: f64) -> usize {
416        knot_find_span(&self.knots, self.degree, parameter)
417    }
418
419    pub fn basis_functions(&self, span: usize, parameter: f64) -> Vec<f64> {
420        if self.degree <= MAX_STACK_DEGREE {
421            let mut basis = [0.0f64; MAX_STACK_ORDER];
422            basis_functions_into(&self.knots, self.degree, span, parameter, &mut basis);
423            return basis[..=self.degree].to_vec();
424        }
425        let mut basis = vec![0.0; self.degree + 1];
426        let mut left = vec![0.0; self.degree + 1];
427        let mut right = vec![0.0; self.degree + 1];
428        basis[0] = 1.0;
429        for j in 1..=self.degree {
430            left[j] = parameter - self.knots[span + 1 - j];
431            right[j] = self.knots[span + j] - parameter;
432            let mut saved = 0.0;
433            for r in 0..j {
434                let denominator = right[r + 1] + left[j - r];
435                let temporary = if denominator.abs() <= EPS {
436                    0.0
437                } else {
438                    basis[r] / denominator
439                };
440                basis[r] = saved + right[r + 1] * temporary;
441                saved = left[j - r] * temporary;
442            }
443            basis[j] = saved;
444        }
445        basis
446    }
447
448    pub fn basis_derivatives(
449        &self,
450        span: usize,
451        parameter: f64,
452        derivative_count: usize,
453    ) -> Vec<Vec<f64>> {
454        if self.degree <= MAX_STACK_DEGREE && derivative_count <= MAX_STACK_DEGREE {
455            let mut rows = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
456            basis_derivatives_into(
457                &self.knots,
458                self.degree,
459                span,
460                parameter,
461                derivative_count,
462                &mut rows[..=derivative_count],
463            );
464            return rows[..=derivative_count]
465                .iter()
466                .map(|row| row[..=self.degree].to_vec())
467                .collect();
468        }
469        let p = self.degree;
470        let n = derivative_count.min(p);
471        let mut ndu = vec![vec![0.0; p + 1]; p + 1];
472        let mut left = vec![0.0; p + 1];
473        let mut right = vec![0.0; p + 1];
474        ndu[0][0] = 1.0;
475
476        for j in 1..=p {
477            left[j] = parameter - self.knots[span + 1 - j];
478            right[j] = self.knots[span + j] - parameter;
479            let mut saved = 0.0;
480            for r in 0..j {
481                ndu[j][r] = right[r + 1] + left[j - r];
482                let temporary = if ndu[j][r].abs() <= EPS {
483                    0.0
484                } else {
485                    ndu[r][j - 1] / ndu[j][r]
486                };
487                ndu[r][j] = saved + right[r + 1] * temporary;
488                saved = left[j - r] * temporary;
489            }
490            ndu[j][j] = saved;
491        }
492
493        let mut derivatives = vec![vec![0.0; p + 1]; derivative_count + 1];
494        for j in 0..=p {
495            derivatives[0][j] = ndu[j][p];
496        }
497        let mut a = vec![vec![0.0; p + 1]; 2];
498        for r in 0..=p {
499            let mut s1 = 0;
500            let mut s2 = 1;
501            a[0][0] = 1.0;
502            for k in 1..=n {
503                a[s2].fill(0.0);
504                let mut value = 0.0;
505                let rk = r as isize - k as isize;
506                let pk = p - k;
507                if r >= k {
508                    let denominator = ndu[pk + 1][rk as usize];
509                    a[s2][0] = a[s1][0] / denominator;
510                    value = a[s2][0] * ndu[rk as usize][pk];
511                }
512                let j1 = if rk >= -1 { 1 } else { (-rk) as usize };
513                let j2 = if r <= pk + 1 { k - 1 } else { p - r };
514                if j1 <= j2 {
515                    for j in j1..=j2 {
516                        let index = (rk + j as isize) as usize;
517                        a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][index];
518                        value += a[s2][j] * ndu[index][pk];
519                    }
520                }
521                if r <= pk {
522                    a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r];
523                    value += a[s2][k] * ndu[r][pk];
524                }
525                derivatives[k][r] = value;
526                std::mem::swap(&mut s1, &mut s2);
527            }
528        }
529        let mut factor = p as f64;
530        for (k, row) in derivatives.iter_mut().enumerate().take(n + 1).skip(1) {
531            for value in row {
532                *value *= factor;
533            }
534            factor *= (p - k) as f64;
535        }
536        derivatives
537    }
538}
539
540#[derive(Clone, Debug, Deserialize, Serialize)]
541pub struct NurbsCurve {
542    pub degree: usize,
543    pub knots: Vec<f64>,
544    pub control_points: Vec<Vec4>,
545    /// One-time validation cache. Deserialized curves (which bypass `new`)
546    /// run the full `new`-equivalent checks on first geometric use instead of
547    /// re-validating the knot vector on every evaluation.
548    #[serde(skip, default)]
549    validated: std::cell::Cell<bool>,
550}
551
552impl NurbsCurve {
553    /// Whether the one-time validation has run. For the boolean's
554    /// operand-state instrument (`BREP_DEBUG_OPERAND_STATE`).
555    pub(crate) fn is_validated(&self) -> bool {
556        self.validated.get()
557    }
558
559    /// Sets the validation cache: for the operand-state instrument only.
560    pub(crate) fn set_validated(&mut self, validated: bool) {
561        self.validated = std::cell::Cell::new(validated);
562    }
563
564    pub fn new(degree: usize, knots: Vec<f64>, control_points: Vec<Vec4>) -> Result<Self, String> {
565        let curve = Self {
566            degree,
567            knots,
568            control_points,
569            validated: std::cell::Cell::new(false),
570        };
571        curve.ensure_valid()?;
572        Ok(curve)
573    }
574
575    /// The full construction-time checks, run at most once per instance.
576    fn ensure_valid(&self) -> Result<(), String> {
577        if self.validated.get() {
578            return Ok(());
579        }
580        validate_knots(&self.knots, self.degree)?;
581        let expected = self.knots.len() - self.degree - 1;
582        if self.control_points.len() != expected {
583            return Err(format!(
584                "NurbsCurve: knot vector implies {} control points, got {}",
585                expected,
586                self.control_points.len()
587            ));
588        }
589        if self.control_points.iter().any(|point| {
590            point.w <= EPS
591                || ![point.x, point.y, point.z, point.w]
592                    .iter()
593                    .all(|value| value.is_finite())
594        }) {
595            return Err("NurbsCurve: control points must be finite with positive weights".into());
596        }
597        self.validated.set(true);
598        Ok(())
599    }
600
601    fn knot_vector(&self) -> Result<KnotVector, String> {
602        KnotVector::new(self.knots.clone(), self.degree)
603    }
604
605    pub fn domain(&self) -> Result<[f64; 2], String> {
606        self.ensure_valid()?;
607        Ok(knot_domain(&self.knots, self.degree))
608    }
609
610    pub fn evaluate_homogeneous(&self, parameter: f64) -> Result<Vec4, String> {
611        self.ensure_valid()?;
612        let span = knot_find_span(&self.knots, self.degree, parameter);
613        let parameter = knot_clamp(&self.knots, self.degree, parameter);
614        let mut point = Vec4 {
615            x: 0.0,
616            y: 0.0,
617            z: 0.0,
618            w: 0.0,
619        };
620        if self.degree <= MAX_STACK_DEGREE {
621            let mut basis = [0.0f64; MAX_STACK_ORDER];
622            basis_functions_into(&self.knots, self.degree, span, parameter, &mut basis);
623            for (index, value) in basis[..=self.degree].iter().enumerate() {
624                point = point.add(self.control_points[span - self.degree + index].scale(*value));
625            }
626        } else {
627            let knot_vector = self.knot_vector()?;
628            let basis = knot_vector.basis_functions(span, parameter);
629            for (index, value) in basis.iter().enumerate() {
630                point = point.add(self.control_points[span - self.degree + index].scale(*value));
631            }
632        }
633        Ok(point)
634    }
635
636    pub fn evaluate(&self, parameter: f64) -> Result<Vec3, String> {
637        self.evaluate_homogeneous(parameter)?.point()
638    }
639
640    /// The straight segment this curve traces, as `(start, end)`, or `None`
641    /// when it genuinely bends.
642    ///
643    /// What a direct-edit heal actually needs to know about an edge is
644    /// *geometric* — "is this a straight segment I may rebuild between two
645    /// re-solved corners?" — but it used to be answered by the
646    /// *representation* `degree == 1 && control_points.len() == 2`. That
647    /// answer is wrong for a line that carries an interior knot, which is what
648    /// an offset shell or a boolean leaves behind when it splits a box edge and
649    /// rejoins the pieces: the same line, three control points, and every heal
650    /// that asked the representation question called it "curved".
651    ///
652    /// Weights are strictly positive (`ensure_valid`), so every point of the
653    /// curve is a convex combination of its control points and the curve is a
654    /// straight segment **iff** those control points are collinear — for any
655    /// degree, not just degree 1. Monotone projections onto the chord are
656    /// required too, so a polyline that doubles back along its own line (it
657    /// covers the segment but does not parameterise it) is not mistaken for
658    /// one.
659    pub(crate) fn straight_segment(&self, tolerance: f64) -> Option<(Vec3, Vec3)> {
660        self.ensure_valid().ok()?;
661        let points = self
662            .control_points
663            .iter()
664            .map(|point| point.point().ok())
665            .collect::<Option<Vec<Vec3>>>()?;
666        let start = *points.first()?;
667        let end = *points.last()?;
668        let chord = end.sub(start);
669        let length = chord.length();
670        if length <= tolerance {
671            return None;
672        }
673        let direction = chord.scale(1.0 / length);
674        let mut reached = 0.0f64;
675        for point in &points {
676            let offset = point.sub(start);
677            let axial = offset.dot(direction);
678            if offset.sub(direction.scale(axial)).length() > tolerance {
679                return None; // off the chord — the curve genuinely bends
680            }
681            if axial < reached - tolerance {
682                return None; // collinear, but the polygon doubles back
683            }
684            reached = reached.max(axial);
685        }
686        Some((start, end))
687    }
688
689    /// Value beyond the domain (Golovanov §2.15): every curve must answer
690    /// out-of-domain queries because intersection and projection
691    /// algorithms probe there.  Closed curves wrap the parameter
692    /// cyclically; open curves extend linearly along the end tangent.
693    pub fn evaluate_extended(&self, parameter: f64) -> Result<Vec3, String> {
694        Ok(self.derivatives_extended(parameter, 0)?[0])
695    }
696
697    /// Derivatives beyond the domain (§2.15).  The open-end extension is
698    /// linear: the first derivative is the boundary tangent and higher
699    /// derivatives vanish.
700    pub fn derivatives_extended(
701        &self,
702        parameter: f64,
703        derivative_count: usize,
704    ) -> Result<Vec<Vec3>, String> {
705        let [start, end] = self.domain()?;
706        if parameter >= start && parameter <= end {
707            return self.derivatives(parameter, derivative_count);
708        }
709        let period = end - start;
710        if period > 0.0 {
711            let closed =
712                self.evaluate(start)?.sub(self.evaluate(end)?).length() <= 1e-9 * (1.0 + period);
713            if closed {
714                let wrapped = start + (parameter - start).rem_euclid(period);
715                return self.derivatives(wrapped, derivative_count);
716            }
717        }
718        let boundary = if parameter < start { start } else { end };
719        let base = self.derivatives(boundary, derivative_count.max(1))?;
720        let mut result = Vec::with_capacity(derivative_count + 1);
721        result.push(base[0].add(base[1].scale(parameter - boundary)));
722        if derivative_count >= 1 {
723            result.push(base[1]);
724        }
725        for _ in 2..=derivative_count {
726            result.push(Vec3::default());
727        }
728        Ok(result)
729    }
730
731    pub fn derivatives(
732        &self,
733        parameter: f64,
734        derivative_count: usize,
735    ) -> Result<Vec<Vec3>, String> {
736        self.ensure_valid()?;
737        let parameter = knot_clamp(&self.knots, self.degree, parameter);
738        let span = knot_find_span(&self.knots, self.degree, parameter);
739        let calculated_count = derivative_count.min(self.degree);
740        let mut homogeneous: Vec<Vec4> = Vec::with_capacity(calculated_count + 1);
741        if self.degree <= MAX_STACK_DEGREE {
742            let mut rows = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
743            basis_derivatives_into(
744                &self.knots,
745                self.degree,
746                span,
747                parameter,
748                calculated_count,
749                &mut rows[..=calculated_count],
750            );
751            for row in rows.iter().take(calculated_count + 1) {
752                let mut point = Vec4 {
753                    x: 0.0,
754                    y: 0.0,
755                    z: 0.0,
756                    w: 0.0,
757                };
758                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
759                    point =
760                        point.add(self.control_points[span - self.degree + index].scale(*value));
761                }
762                homogeneous.push(point);
763            }
764        } else {
765            let knot_vector = self.knot_vector()?;
766            let basis = knot_vector.basis_derivatives(span, parameter, calculated_count);
767            for row in basis.iter().take(calculated_count + 1) {
768                let mut point = Vec4 {
769                    x: 0.0,
770                    y: 0.0,
771                    z: 0.0,
772                    w: 0.0,
773                };
774                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
775                    point =
776                        point.add(self.control_points[span - self.degree + index].scale(*value));
777                }
778                homogeneous.push(point);
779            }
780        }
781
782        let mut result: Vec<Vec3> = Vec::with_capacity(derivative_count + 1);
783        for k in 0..=calculated_count {
784            let mut value = Vec3::new(homogeneous[k].x, homogeneous[k].y, homogeneous[k].z);
785            for i in 1..=k {
786                value = value.sub(result[k - i].scale(binomial(k, i) * homogeneous[i].w));
787            }
788            result.push(value.scale(1.0 / homogeneous[0].w));
789        }
790        result.resize(derivative_count + 1, Vec3::default());
791        Ok(result)
792    }
793
794    /// The curve's unit TANGENT at `parameter`, read as the one-sided limit
795    /// when the first derivative vanishes there.
796    ///
797    /// This is what `derivatives(t, 1)?[1].normalized()?` should always have
798    /// been. That shape refuses on a curve class that is not exotic at all —
799    /// any Hermite segment whose end tangent is the zero vector, of which an
800    /// INVOLUTE flank is the standard source (speed `r_base * t`, so a profile
801    /// sampled from the base circle outwards carries an exactly zero tangent at
802    /// its start, one per flank per tooth). The direction of travel is still
803    /// defined there, as the limit from inside the range, and
804    /// [`Self::stationary_tangent_rescue`] reads it.
805    ///
806    /// Pass the range the CALLER owns — an edge's `[t0, t1]`, not the curve's
807    /// domain, where the two differ (an `EdgeRecord` keeps the whole curve and
808    /// records the sub-range it uses), so the probe never reads geometry
809    /// outside the caller's own span.
810    ///
811    /// The error names the parameter and the range it probed, because the only
812    /// curve that reaches it is stationary EVERYWHERE the range allows, and the
813    /// caller's own identifier is the half this function cannot supply.
814    ///
815    /// Escape hatch for tamper-verification: `BREP_CUSP_TANGENT_RESCUE=0`
816    /// restores the bare `normalized()` refusal, the same hatch the imprint
817    /// driver's seed loop carries.
818    pub fn unit_tangent(
819        &self,
820        parameter: f64,
821        range_start: f64,
822        range_end: f64,
823    ) -> Result<Vec3, String> {
824        let derivative = self.derivatives(parameter, 1)?[1];
825        self.tangent_or_one_sided_limit(derivative, parameter, range_start, range_end)
826    }
827
828    /// The point and unit tangent that `derivatives_extended(parameter, 1)`
829    /// reads, with the tangent taken as [`Self::unit_tangent`] takes it.
830    ///
831    /// The blend march reads its section plane — the point and the edge's
832    /// unit tangent — through the EXTENDED evaluation at every station,
833    /// overshoot stations past the edge's ends included, and `unit_tangent`
834    /// cannot stand in for that read: it evaluates `derivatives`, which CLAMPS
835    /// a parameter outside the domain, where `derivatives_extended` WRAPS it on
836    /// a closed curve. A closed rim's overshoot station would read a different
837    /// tangent. This is the same one evaluation the march always made, so a
838    /// non-zero derivative returns the vector `derivatives[1].normalized()`
839    /// returned, to the bit, at no extra cost.
840    ///
841    /// Where the derivative vanishes, the one-sided limit is read at the
842    /// parameter the extended evaluation actually took its derivative from —
843    /// the parameter itself inside the domain, the wrapped one on a closed
844    /// curve, the boundary past an open end, where the extension's direction
845    /// IS the boundary's one-sided limit. The caller's range is widened to
846    /// contain that parameter, because an overshoot station reads outside the
847    /// caller's span on purpose; the ladder still probes from the side the
848    /// range lies on.
849    pub fn point_and_unit_tangent_extended(
850        &self,
851        parameter: f64,
852        range_start: f64,
853        range_end: f64,
854    ) -> Result<(Vec3, Vec3), String> {
855        let derivatives = self.derivatives_extended(parameter, 1)?;
856        if let Ok(tangent) = derivatives[1].normalized() {
857            return Ok((derivatives[0], tangent));
858        }
859        let read_at = self.extended_read_parameter(parameter)?;
860        let low = range_start.min(range_end).min(read_at);
861        let high = range_start.max(range_end).max(read_at);
862        let tangent = self.tangent_or_one_sided_limit(derivatives[1], read_at, low, high)?;
863        Ok((derivatives[0], tangent))
864    }
865
866    /// The in-domain parameter whose derivatives `derivatives_extended` reads
867    /// for `parameter`: itself inside the domain, wrapped on a closed curve,
868    /// the nearer boundary past an open end. Mirrors that function's three
869    /// cases; only the zero-derivative lane of
870    /// [`Self::point_and_unit_tangent_extended`] pays for it.
871    fn extended_read_parameter(&self, parameter: f64) -> Result<f64, String> {
872        let [start, end] = self.domain()?;
873        if parameter >= start && parameter <= end {
874            return Ok(parameter);
875        }
876        if self.extension_wraps(start, end)? {
877            return Ok(start + (parameter - start).rem_euclid(end - start));
878        }
879        Ok(if parameter < start { start } else { end })
880    }
881
882    /// `derivatives_extended`'s closed test: a curve whose ends meet WRAPS an
883    /// out-of-domain parameter instead of extending it.
884    fn extension_wraps(&self, start: f64, end: f64) -> Result<bool, String> {
885        let period = end - start;
886        Ok(period > 0.0
887            && self.evaluate(start)?.sub(self.evaluate(end)?).length() <= 1e-9 * (1.0 + period))
888    }
889
890    /// The open end `parameter` lies past, when the first derivative VANISHES
891    /// there — the one case in which `derivatives_extended`'s point does not
892    /// move with its parameter: past an open end it returns
893    /// `P(end) + C'(end)·(t − end)`, which is `P(end)` for every `t` when
894    /// `C'(end) = 0`. `None` inside the domain, on a closed curve (which wraps
895    /// onto the real curve), and past an end whose derivative is regular.
896    ///
897    /// The zero test is [`Self::point_and_unit_tangent_extended`]'s own: the
898    /// derivative has no unit vector. A caller that extends past such an end
899    /// supplies the SPEED the parameterization does not; the direction is the
900    /// one-sided limit that function already reads there.
901    pub(crate) fn stationary_open_end(&self, parameter: f64) -> Result<Option<f64>, String> {
902        let [start, end] = self.domain()?;
903        if parameter >= start && parameter <= end {
904            return Ok(None);
905        }
906        let boundary = if parameter < start { start } else { end };
907        if self.derivatives(boundary, 1)?[1].normalized().is_ok()
908            || self.extension_wraps(start, end)?
909        {
910            return Ok(None);
911        }
912        Ok(Some(boundary))
913    }
914
915    /// `derivative`, normalized — or, where it vanishes, the one-sided limit
916    /// from inside `[range_start, range_end]` at `parameter`, or the named
917    /// refusal. The one failure lane [`Self::unit_tangent`] and
918    /// [`Self::point_and_unit_tangent_extended`] share.
919    fn tangent_or_one_sided_limit(
920        &self,
921        derivative: Vec3,
922        parameter: f64,
923        range_start: f64,
924        range_end: f64,
925    ) -> Result<Vec3, String> {
926        let error = match derivative.normalized() {
927            Ok(tangent) => return Ok(tangent),
928            Err(error) => error,
929        };
930        if std::env::var("BREP_CUSP_TANGENT_RESCUE").as_deref() == Ok("0") {
931            return Err(error);
932        }
933        self.stationary_tangent_rescue(parameter, range_start, range_end)
934            .ok_or_else(|| {
935                format!(
936                    "curve tangent: the first derivative vanishes at t = {parameter} and \
937                     everywhere in [{range_start}, {range_end}] the probe can reach, so this \
938                     curve has no direction of travel to report"
939                )
940            })
941    }
942
943    /// The unit tangent just inside `[range_start, range_end]`, for a
944    /// `parameter` where the first derivative VANISHES.
945    ///
946    /// A curve can be stationary at a parameter where the curve itself is
947    /// perfectly well behaved, and the direction of travel is then still
948    /// defined as the one-sided limit. The standard case is a cubic Bezier
949    /// whose first two control points coincide — the shape a Hermite segment
950    /// takes when its end tangent is the zero vector — and an INVOLUTE is the
951    /// standard source of one: the involute's speed is `r_base * t`, so a gear
952    /// flank sampled from the base circle outwards starts with an exactly zero
953    /// tangent and every tooth profile carries one per flank. The 2026-09-14
954    /// herringbone report is that shape: a hit landing exactly on the cusp
955    /// parameter made `derivatives(t, 1)[1].normalized()` fail and killed the
956    /// whole union.
957    ///
958    /// The range bounds the probe — pass an edge's own `[t0, t1]` and the
959    /// rescue never reads the curve outside the span the caller owns. The
960    /// ladder walks OUTWARDS, and it starts at 1e-6 of the span rather than at
961    /// the smallest representable step: the rescued direction is a ONE-SIDED
962    /// limit, so a nearer probe truncates less, but the derivative at a
963    /// stationary point is a CANCELLING sum that shrinks with the step while
964    /// its rounding error does not — at 1e-9 of the span the involute cusp
965    /// below reads its own limit direction only to 1e-6, worse than at 1e-6 of
966    /// the span. Later rungs exist for a higher-order stationary point, whose
967    /// derivative is still under the zero-length floor at the first. `None`
968    /// means the curve is stationary everywhere the range allows, where no
969    /// direction exists to report at all.
970    pub fn stationary_tangent_rescue(
971        &self,
972        parameter: f64,
973        range_start: f64,
974        range_end: f64,
975    ) -> Option<Vec3> {
976        let low = range_start.min(range_end);
977        let high = range_start.max(range_end);
978        let span = high - low;
979        if !(span > 0.0) {
980            return None;
981        }
982        for scale in [1e-6, 1e-4, 1e-2, 1e-1] {
983            let step = span * scale;
984            for probe in [parameter + step, parameter - step] {
985                if probe < low || probe > high {
986                    continue;
987                }
988                if let Some(unit) = self
989                    .derivatives(probe, 1)
990                    .ok()
991                    .and_then(|derivatives| derivatives[1].normalized().ok())
992                {
993                    return Some(unit);
994                }
995            }
996        }
997        None
998    }
999
1000    /// Allocation-free twin of [`Self::derivatives`] for the hot
1001    /// `derivative_count <= 2` path.
1002    ///
1003    /// Byte-for-byte faithful copy of the arithmetic in [`Self::derivatives`]:
1004    /// identical basis evaluation, identical summation order, and the identical
1005    /// rational de-homogenization recurrence. Only the storage differs — a
1006    /// fixed-size `[Vec4; 3]` / `[Vec3; 3]` on the stack instead of the heap
1007    /// `Vec`s. Entries beyond `derivative_count.min(degree)` stay
1008    /// `Vec3::default()`, exactly as the heap version's trailing `resize` leaves
1009    /// them.
1010    pub(crate) fn derivatives_small(
1011        &self,
1012        parameter: f64,
1013        derivative_count: usize,
1014    ) -> Result<[Vec3; 3], String> {
1015        debug_assert!(derivative_count <= 2);
1016        self.ensure_valid()?;
1017        let parameter = knot_clamp(&self.knots, self.degree, parameter);
1018        let span = knot_find_span(&self.knots, self.degree, parameter);
1019        let calculated_count = derivative_count.min(self.degree);
1020        let zero = Vec4 {
1021            x: 0.0,
1022            y: 0.0,
1023            z: 0.0,
1024            w: 0.0,
1025        };
1026        let mut homogeneous = [zero; 3];
1027        if self.degree <= MAX_STACK_DEGREE {
1028            let mut rows = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
1029            basis_derivatives_into(
1030                &self.knots,
1031                self.degree,
1032                span,
1033                parameter,
1034                calculated_count,
1035                &mut rows[..=calculated_count],
1036            );
1037            for (k, row) in rows.iter().take(calculated_count + 1).enumerate() {
1038                let mut point = zero;
1039                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
1040                    point =
1041                        point.add(self.control_points[span - self.degree + index].scale(*value));
1042                }
1043                homogeneous[k] = point;
1044            }
1045        } else {
1046            let knot_vector = self.knot_vector()?;
1047            let basis = knot_vector.basis_derivatives(span, parameter, calculated_count);
1048            for (k, row) in basis.iter().take(calculated_count + 1).enumerate() {
1049                let mut point = zero;
1050                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
1051                    point =
1052                        point.add(self.control_points[span - self.degree + index].scale(*value));
1053                }
1054                homogeneous[k] = point;
1055            }
1056        }
1057
1058        let mut result = [Vec3::default(); 3];
1059        for k in 0..=calculated_count {
1060            let mut value = Vec3::new(homogeneous[k].x, homogeneous[k].y, homogeneous[k].z);
1061            for i in 1..=k {
1062                value = value.sub(result[k - i].scale(binomial(k, i) * homogeneous[i].w));
1063            }
1064            result[k] = value.scale(1.0 / homogeneous[0].w);
1065        }
1066        Ok(result)
1067    }
1068
1069    /// Point and first derivative `(C, C')` with zero heap allocation.
1070    /// Bit-identical to `derivatives(t, 1)` at indices `[0]` and `[1]`.
1071    #[inline]
1072    pub(crate) fn deriv1(&self, parameter: f64) -> Result<(Vec3, Vec3), String> {
1073        let d = self.derivatives_small(parameter, 1)?;
1074        Ok((d[0], d[1]))
1075    }
1076
1077    pub fn reversed(&self) -> Result<Self, String> {
1078        let start = self.knots[0];
1079        let end = self.knots[self.knots.len() - 1];
1080        let knots = self
1081            .knots
1082            .iter()
1083            .rev()
1084            .map(|knot| start + end - knot)
1085            .collect();
1086        let control_points = self.control_points.iter().rev().copied().collect();
1087        Self::new(self.degree, knots, control_points)
1088    }
1089
1090    pub fn insert_knot(&self, parameter: f64, requested: usize) -> Result<Self, String> {
1091        let knot_vector = self.knot_vector()?;
1092        let degree = self.degree;
1093        let parameter = knot_vector.clamp_param(parameter);
1094        // A parameter within knot tolerance of an existing knot must BE
1095        // that knot: counting it as a multiplicity while find_span places
1096        // it in the span below (parameter infinitesimally smaller) makes
1097        // the Boehm index bookkeeping inconsistent and corrupts the net.
1098        let parameter = self
1099            .knots
1100            .iter()
1101            .copied()
1102            .find(|knot| (knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1103            .unwrap_or(parameter);
1104        let multiplicity = self
1105            .knots
1106            .iter()
1107            .filter(|knot| (**knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1108            .count();
1109        let insertion_count = requested.min(degree.saturating_sub(multiplicity));
1110        if insertion_count == 0 {
1111            return Ok(self.clone());
1112        }
1113        let span = knot_vector.find_span(parameter);
1114        let last_control = self.control_points.len() - 1;
1115        let mut knots = Vec::with_capacity(self.knots.len() + insertion_count);
1116        knots.extend_from_slice(&self.knots[..=span]);
1117        knots.extend(std::iter::repeat_n(parameter, insertion_count));
1118        knots.extend_from_slice(&self.knots[span + 1..]);
1119
1120        let mut output = vec![
1121            Vec4 {
1122                x: 0.0,
1123                y: 0.0,
1124                z: 0.0,
1125                w: 1.0,
1126            };
1127            last_control + 1 + insertion_count
1128        ];
1129        output[..=span - degree].copy_from_slice(&self.control_points[..=span - degree]);
1130        for index in span - multiplicity..=last_control {
1131            output[index + insertion_count] = self.control_points[index];
1132        }
1133        let mut affected = vec![
1134            Vec4 {
1135                x: 0.0,
1136                y: 0.0,
1137                z: 0.0,
1138                w: 1.0,
1139            };
1140            degree + 1
1141        ];
1142        affected[..=degree - multiplicity]
1143            .copy_from_slice(&self.control_points[span - degree..=span - multiplicity]);
1144        let mut left = 0;
1145        for insertion in 1..=insertion_count {
1146            left = span - degree + insertion;
1147            for index in 0..=degree - insertion - multiplicity {
1148                let denominator = self.knots[index + span + 1] - self.knots[left + index];
1149                let alpha = (parameter - self.knots[left + index]) / denominator;
1150                affected[index] = affected[index + 1]
1151                    .scale(alpha)
1152                    .add(affected[index].scale(1.0 - alpha));
1153            }
1154            output[left] = affected[0];
1155            output[span + insertion_count - insertion - multiplicity] =
1156                affected[degree - insertion - multiplicity];
1157        }
1158        for index in left + 1..span - multiplicity {
1159            output[index] = affected[index - left];
1160        }
1161        Self::new(degree, knots, output)
1162    }
1163
1164    pub fn split(&self, parameter: f64) -> Result<(Self, Self), String> {
1165        let [start, end] = self.domain()?;
1166        if parameter <= start + KNOT_IDENTITY_TOL || parameter >= end - KNOT_IDENTITY_TOL {
1167            return Err(format!(
1168                "NurbsCurve.split: parameter {parameter} must be strictly inside domain [{start}, {end}]"
1169            ));
1170        }
1171        // Snap onto a coincident knot so multiplicity and span agree (see
1172        // insert_knot).
1173        let parameter = self
1174            .knots
1175            .iter()
1176            .copied()
1177            .find(|knot| (knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1178            .unwrap_or(parameter);
1179        let multiplicity = self
1180            .knots
1181            .iter()
1182            .filter(|knot| (**knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1183            .count();
1184        let refined = self.insert_knot(parameter, self.degree.saturating_sub(multiplicity))?;
1185        let first = refined
1186            .knots
1187            .iter()
1188            .position(|knot| (*knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1189            .ok_or_else(|| "NurbsCurve.split: inserted knot not found".to_string())?;
1190        let mut left_knots = refined.knots[..first + self.degree].to_vec();
1191        left_knots.push(parameter);
1192        let left_points = refined.control_points[..first].to_vec();
1193        let mut right_knots = vec![parameter; self.degree + 1];
1194        right_knots.extend_from_slice(&refined.knots[first + self.degree..]);
1195        let right_points = refined.control_points[first - 1..].to_vec();
1196        Ok((
1197            Self::new(self.degree, left_knots, left_points)?,
1198            Self::new(self.degree, right_knots, right_points)?,
1199        ))
1200    }
1201}
1202
1203pub fn make_line(start: Vec3, end: Vec3) -> Result<NurbsCurve, String> {
1204    NurbsCurve::new(
1205        1,
1206        vec![0.0, 0.0, 1.0, 1.0],
1207        vec![Vec4::from_point(start, 1.0), Vec4::from_point(end, 1.0)],
1208    )
1209}
1210
1211pub fn make_arc(
1212    center: Vec3,
1213    x_axis: Vec3,
1214    y_axis: Vec3,
1215    radius: f64,
1216    start_angle: f64,
1217    end_angle: f64,
1218) -> Result<NurbsCurve, String> {
1219    if radius <= EPS {
1220        return Err("makeArc: radius must be positive".into());
1221    }
1222    let x_axis = x_axis.normalized()?;
1223    let y_axis = y_axis.normalized()?;
1224    if x_axis.dot(y_axis).abs() > 1e-9 {
1225        return Err("makeArc: xAxis and yAxis must be orthogonal".into());
1226    }
1227    let mut theta = end_angle - start_angle;
1228    if theta <= EPS {
1229        return Err("makeArc: endAngle must exceed startAngle".into());
1230    }
1231    if theta > std::f64::consts::TAU + EPS {
1232        return Err("makeArc: sweep exceeds full circle".into());
1233    }
1234    theta = theta.min(std::f64::consts::TAU);
1235    let segment_count = ((theta / std::f64::consts::FRAC_PI_2 - EPS).ceil() as usize).clamp(1, 4);
1236    let segment_angle = theta / segment_count as f64;
1237    let middle_weight = (segment_angle / 2.0).cos();
1238    let point_at = |angle: f64| {
1239        center
1240            .add(x_axis.scale(radius * angle.cos()))
1241            .add(y_axis.scale(radius * angle.sin()))
1242    };
1243    let tangent_at = |angle: f64| x_axis.scale(-angle.sin()).add(y_axis.scale(angle.cos()));
1244
1245    let mut points = Vec::with_capacity(2 * segment_count + 1);
1246    let mut angle = start_angle;
1247    let mut first_point = point_at(angle);
1248    let mut first_tangent = tangent_at(angle);
1249    points.push(Vec4::from_point(first_point, 1.0));
1250    for _ in 0..segment_count {
1251        angle += segment_angle;
1252        let end_point = point_at(angle);
1253        let end_tangent = tangent_at(angle);
1254        let cross = first_tangent.cross(end_tangent);
1255        let denominator = cross.length_squared();
1256        if denominator <= EPS {
1257            return Err("makeArc: arc tangents are parallel".into());
1258        }
1259        let distance = end_point.sub(first_point).cross(end_tangent).dot(cross) / denominator;
1260        let middle = first_point.add(first_tangent.scale(distance));
1261        points.push(Vec4::from_point(middle, middle_weight));
1262        points.push(Vec4::from_point(end_point, 1.0));
1263        first_point = end_point;
1264        first_tangent = end_tangent;
1265    }
1266    let mut knots = vec![0.0, 0.0, 0.0];
1267    for index in 1..segment_count {
1268        let knot = index as f64 / segment_count as f64;
1269        knots.extend([knot, knot]);
1270    }
1271    knots.extend([1.0, 1.0, 1.0]);
1272    NurbsCurve::new(2, knots, points)
1273}
1274
1275pub fn make_circle(center: Vec3, normal: Vec3, radius: f64) -> Result<NurbsCurve, String> {
1276    let normal = normal.normalized()?;
1277    let x_axis = normal.perpendicular()?;
1278    let y_axis = normal.cross(x_axis).normalized()?;
1279    make_arc(center, x_axis, y_axis, radius, 0.0, std::f64::consts::TAU)
1280}
1281
1282/// Build the exactly orthonormal local frame shared by the conic
1283/// constructors.  The conic algebra below (implicit equation, tangent
1284/// intersection, shoulder weight) is only exact in an orthonormal frame, so
1285/// the in-plane hint is Gram-Schmidt-projected against the primary direction
1286/// instead of trusted verbatim: callers only owe us non-parallel vectors.
1287fn conic_frame(fn_name: &str, primary: Vec3, hint: Vec3) -> Result<(Vec3, Vec3), String> {
1288    let x_axis = primary
1289        .normalized()
1290        .map_err(|_| format!("{fn_name}: primary axis must be non-zero"))?;
1291    if hint.length() <= EPS {
1292        return Err(format!("{fn_name}: in-plane direction must be non-zero"));
1293    }
1294    hint.sub(x_axis.scale(hint.dot(x_axis)))
1295        .normalized()
1296        .map(|y_axis| (x_axis, y_axis))
1297        .map_err(|_| format!("{fn_name}: frame directions must not be parallel"))
1298}
1299
1300/// Trim-range validation shared by the conic constructors.  The knot span IS
1301/// the conic parameter range, so it must clear the knot identity band or the
1302/// resulting curve would fail knot validation with an unhelpful message.
1303fn conic_range(fn_name: &str, t0: f64, t1: f64) -> Result<(), String> {
1304    if !t0.is_finite() || !t1.is_finite() {
1305        return Err(format!("{fn_name}: parameter range must be finite"));
1306    }
1307    if t1 - t0 <= KNOT_IDENTITY_TOL {
1308        return Err(format!("{fn_name}: t1 ({t1}) must exceed t0 ({t0})"));
1309    }
1310    Ok(())
1311}
1312
1313/// Extreme trim parameters overflow the conic point formulas (cosh exceeds
1314/// f64 near |t| ~ 710, focal·t² near |t| ~ 1e150); surface that as the
1315/// constructor's own honest error instead of the generic NurbsCurve
1316/// finiteness rejection.
1317fn conic_points_finite(fn_name: &str, points: &[Vec4]) -> Result<(), String> {
1318    if points.iter().any(|point| {
1319        ![point.x, point.y, point.z, point.w]
1320            .iter()
1321            .all(|value| value.is_finite())
1322    }) {
1323        return Err(format!(
1324            "{fn_name}: control points overflow f64 — parameter range too extreme"
1325        ));
1326    }
1327    Ok(())
1328}
1329
1330/// Exact parabola segment y² = 4·focal·x in the local frame (vertex at the
1331/// origin, `axis` = +x, `latus_direction` = +y), parametrized the standard
1332/// way P(t) = (focal·t², 2·focal·t) and trimmed to t ∈ [t0, t1].  A parabola
1333/// segment is a plain quadratic polynomial in t (all weights 1), so a single
1334/// degree-2 Bézier over the knot span [t0, t1] reproduces both the point set
1335/// AND the parametrization exactly — no fitting, and evaluate(t) == P(t) for
1336/// every t, not just at the ends.
1337pub fn make_parabola(
1338    vertex: Vec3,
1339    axis: Vec3,
1340    latus_direction: Vec3,
1341    focal: f64,
1342    t0: f64,
1343    t1: f64,
1344) -> Result<NurbsCurve, String> {
1345    if !focal.is_finite() || focal <= EPS {
1346        return Err("make_parabola: focal distance must be positive".into());
1347    }
1348    conic_range("make_parabola", t0, t1)?;
1349    let (x_axis, y_axis) = conic_frame("make_parabola", axis, latus_direction)?;
1350    let point_at = |t: f64| {
1351        vertex
1352            .add(x_axis.scale(focal * t * t))
1353            .add(y_axis.scale(2.0 * focal * t))
1354    };
1355    // Bernstein middle point of the quadratic polynomial,
1356    // P(t0) + (t1−t0)/2·P'(t0), collapses to local (focal·t0·t1,
1357    // focal·(t0+t1)) — which is also the intersection of the two end
1358    // tangents, as it must be for any parabola segment.
1359    let middle = vertex
1360        .add(x_axis.scale(focal * t0 * t1))
1361        .add(y_axis.scale(focal * (t0 + t1)));
1362    let control_points = vec![
1363        Vec4::from_point(point_at(t0), 1.0),
1364        Vec4::from_point(middle, 1.0),
1365        Vec4::from_point(point_at(t1), 1.0),
1366    ];
1367    conic_points_finite("make_parabola", &control_points)?;
1368    NurbsCurve::new(2, vec![t0, t0, t0, t1, t1, t1], control_points)
1369}
1370
1371/// Exact arc of the hyperbola branch x²/a² − y²/b² = 1, x > 0 in the local
1372/// frame (center at the origin, `major_axis` = +x, `minor_axis` = +y),
1373/// parametrized P(t) = (a·cosh t, b·sinh t) and trimmed to t ∈ [t0, t1].
1374/// A single rational quadratic Bézier is exact for any sweep on one branch:
1375/// endpoints on the curve, middle control point at the intersection of the
1376/// end tangents, and middle weight cosh((t1−t0)/2) chosen so the shoulder
1377/// point lands back on the branch.  Only the point set is hyperbola-exact
1378/// away from the ends; the NURBS parameter coincides with the hyperbolic
1379/// parameter t exactly at t0, (t0+t1)/2 and t1.
1380pub fn make_hyperbola(
1381    center: Vec3,
1382    major_axis: Vec3,
1383    minor_axis: Vec3,
1384    a: f64,
1385    b: f64,
1386    t0: f64,
1387    t1: f64,
1388) -> Result<NurbsCurve, String> {
1389    if !a.is_finite() || a <= EPS {
1390        return Err("make_hyperbola: semi-axis a must be positive".into());
1391    }
1392    if !b.is_finite() || b <= EPS {
1393        return Err("make_hyperbola: semi-axis b must be positive".into());
1394    }
1395    conic_range("make_hyperbola", t0, t1)?;
1396    let (x_axis, y_axis) = conic_frame("make_hyperbola", major_axis, minor_axis)?;
1397    let point_at = |t: f64| {
1398        center
1399            .add(x_axis.scale(a * t.cosh()))
1400            .add(y_axis.scale(b * t.sinh()))
1401    };
1402    let mid = 0.5 * (t0 + t1);
1403    let middle_weight = (0.5 * (t1 - t0)).cosh();
1404    // In the scaled frame (x/a, y/b) the branch is the unit hyperbola and the
1405    // tangent at t is the line X·cosh t − Y·sinh t = 1; Cramer's rule on the
1406    // two end-tangent lines collapses their intersection to
1407    // P(mid)/cosh(half-sweep), so no explicit line-line solve is needed.
1408    // With this middle point, weight cosh(half-sweep) puts the shoulder point
1409    // (P0 + 2w·P1 + P2)/(2 + 2w) back on the branch at P(mid).
1410    let apex = center
1411        .add(x_axis.scale(a * mid.cosh() / middle_weight))
1412        .add(y_axis.scale(b * mid.sinh() / middle_weight));
1413    let control_points = vec![
1414        Vec4::from_point(point_at(t0), 1.0),
1415        Vec4::from_point(apex, middle_weight),
1416        Vec4::from_point(point_at(t1), 1.0),
1417    ];
1418    conic_points_finite("make_hyperbola", &control_points)?;
1419    NurbsCurve::new(2, vec![t0, t0, t0, t1, t1, t1], control_points)
1420}
1421
1422pub fn uniform_clamped_knots(
1423    control_point_count: usize,
1424    degree: usize,
1425) -> Result<Vec<f64>, String> {
1426    if control_point_count == 0 || control_point_count - 1 < degree {
1427        return Err("uniformClampedKnots: need at least degree+1 control points".into());
1428    }
1429    let n = control_point_count - 1;
1430    let mut knots = vec![0.0; degree + 1];
1431    let interior = n - degree;
1432    for index in 1..=interior {
1433        knots.push(index as f64 / (interior + 1) as f64);
1434    }
1435    knots.extend(std::iter::repeat_n(1.0, degree + 1));
1436    Ok(knots)
1437}
1438
1439fn binomial(n: usize, k: usize) -> f64 {
1440    if k > n {
1441        return 0.0;
1442    }
1443    let k = k.min(n - k);
1444    (1..=k).fold(1.0, |value, index| {
1445        value * (n - k + index) as f64 / index as f64
1446    })
1447}
1448
1449
1450