Skip to main content

brep_geometry/geometry/
curve.rs

1pub use crate::Vec3;
2use serde::{Deserialize, Serialize};
3
4const EPS: f64 = crate::tolerance::FP_FLOOR;
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 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 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 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 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 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 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/// Public stack capacity used by prepared readers and optional algorithms.
130/// Keep this bound stable: those algorithms may use different arithmetic.
131pub const MAX_STACK_DEGREE: usize = 7;
132pub const MAX_STACK_ORDER: usize = MAX_STACK_DEGREE + 1;
133
134// The scalar surface evaluator also carries degree-nine screw walls. Its
135// larger scratch must not enable other algorithms or resize public fields.
136pub(crate) const EVALUATOR_STACK_DEGREE: usize = 9;
137pub(crate) const EVALUATOR_STACK_ORDER: usize = EVALUATOR_STACK_DEGREE + 1;
138
139/// `BREP_DEBUG_KNOTS=1` diagnostic for a rejected knot vector: dumps the whole
140/// vector (plus a backtrace) to stderr and appends it to the returned message,
141/// so a knot failure buried behind a `Result` that a caller only prints —
142/// STEP import's `first_error`, say — still names the offending construction
143/// site. Off by default; the message stays byte-identical without the var.
144fn knot_reject(reason: &str, knots: &[f64], degree: usize) -> String {
145    if std::env::var("BREP_DEBUG_KNOTS").is_err() {
146        return reason.to_string();
147    }
148    let mut worst_descent = f64::NEG_INFINITY;
149    let mut worst_index = 0usize;
150    for (index, pair) in knots.windows(2).enumerate() {
151        let descent = pair[0] - pair[1];
152        if descent > worst_descent {
153            worst_descent = descent;
154            worst_index = index;
155        }
156    }
157    let detail = format!(
158        "{reason} [degree={degree} count={} worst_descent={worst_descent:.6e} at index \
159         {worst_index} knots={knots:?}]",
160        knots.len()
161    );
162    eprintln!(
163        "KNOT-REJECT {detail}\n{}",
164        std::backtrace::Backtrace::force_capture()
165    );
166    detail
167}
168
169/// Validation shared by `KnotVector::new` and the lazily-validated
170/// curve/surface types. Must stay the single source of truth so cached
171/// validation and eager validation reject exactly the same inputs.
172pub fn validate_knots(knots: &[f64], degree: usize) -> Result<(), String> {
173    if degree < 1 {
174        return Err("KnotVector: degree must be >= 1".into());
175    }
176    if knots.len() < 2 * (degree + 1) {
177        return Err(format!(
178            "KnotVector: need at least {} knots for degree {}, got {}",
179            2 * (degree + 1),
180            degree,
181            knots.len()
182        ));
183    }
184    if knots.iter().any(|value| !value.is_finite()) {
185        return Err("KnotVector: knots must be finite".into());
186    }
187    if knots
188        .windows(2)
189        .any(|pair| pair[1] < pair[0] - KNOT_IDENTITY_TOL)
190    {
191        return Err(knot_reject(
192            "KnotVector: knots must be non-decreasing",
193            knots,
194            degree,
195        ));
196    }
197    let first = knots[0];
198    let last = knots[knots.len() - 1];
199    for index in 0..=degree {
200        if (knots[index] - first).abs() > KNOT_IDENTITY_TOL {
201            return Err(knot_reject(
202                "KnotVector: expected clamped start",
203                knots,
204                degree,
205            ));
206        }
207        if (knots[knots.len() - 1 - index] - last).abs() > KNOT_IDENTITY_TOL {
208            return Err(knot_reject("KnotVector: expected clamped end", knots, degree));
209        }
210    }
211    if last - first <= KNOT_IDENTITY_TOL {
212        return Err(knot_reject(
213            "KnotVector: degenerate parameter range",
214            knots,
215            degree,
216        ));
217    }
218    Ok(())
219}
220
221pub fn knot_domain(knots: &[f64], degree: usize) -> [f64; 2] {
222    [knots[degree], knots[knots.len() - 1 - degree]]
223}
224
225pub fn knot_clamp(knots: &[f64], degree: usize, parameter: f64) -> f64 {
226    let [start, end] = knot_domain(knots, degree);
227    parameter.clamp(start, end)
228}
229
230pub fn knot_find_span(knots: &[f64], degree: usize, parameter: f64) -> usize {
231    let parameter = knot_clamp(knots, degree, parameter);
232    let n = knots.len() - degree - 2;
233    if parameter >= knots[n + 1] {
234        // At/after the domain end.  A properly clamped vector has the end knot
235        // at multiplicity exactly `degree + 1`, so span `n` is the last
236        // non-empty interval.  An over-clamped end (a vendor exporter can emit
237        // multiplicity > degree + 1, e.g. two coincident knot VALUES) leaves
238        // span `n` pointing at a zero-width interval whose basis functions are
239        // all zero.  Walk back to the last interval that actually has width.
240        let mut span = n;
241        while span > degree && knots[span] >= knots[span + 1] {
242            span -= 1;
243        }
244        return span;
245    }
246    if parameter <= knots[degree] {
247        // At/before the domain start — the mirror of the case above.  For a
248        // properly clamped start (multiplicity degree + 1) this returns
249        // `degree`; for an over-clamped start it advances past the extra
250        // coincident knots to the first non-empty interval so evaluation never
251        // lands on a zero-width span (which would yield an all-zero,
252        // zero-weight homogeneous point).
253        let mut span = degree;
254        while span < n && knots[span + 1] <= parameter {
255            span += 1;
256        }
257        return span;
258    }
259    let mut low = degree;
260    let mut high = n + 1;
261    let mut middle = (low + high) / 2;
262    while parameter < knots[middle] || parameter >= knots[middle + 1] {
263        if parameter < knots[middle] {
264            high = middle;
265        } else {
266            low = middle;
267        }
268        middle = (low + high) / 2;
269    }
270    middle
271}
272
273/// Cox–de Boor basis functions into a caller-provided stack array.
274/// Requires `degree <= MAX_STACK_DEGREE`; entries `0..=degree` are written.
275#[inline]
276pub fn basis_functions_into(
277    knots: &[f64], degree: usize, span: usize, parameter: f64,
278    basis: &mut [f64; MAX_STACK_ORDER],
279) {
280    debug_assert!(degree <= MAX_STACK_DEGREE);
281    basis_functions_wide(knots, degree, span, parameter, basis);
282}
283
284/// Internal surface scratch, including ninth-degree screw walls.
285pub(crate) fn basis_functions_wide<const WIDTH: usize>(
286    knots: &[f64],
287    degree: usize,
288    span: usize,
289    parameter: f64,
290    basis: &mut [f64; WIDTH],
291) {
292    debug_assert!(degree <= EVALUATOR_STACK_DEGREE);
293    debug_assert!(degree < WIDTH);
294    // Common carrier degrees (1..=5, 8 and 9) run the same
295    // recurrence with the degree and the scratch size fixed at compile time:
296    // the same operations in the same order on the same operands, so the same
297    // bits, without the full-width scratch fill and runtime loop bounds.
298    // Degrees 0, 6 and 7 retain the public eight-wide scratch.
299    match degree {
300        1 => basis_functions_scratch::<2>(knots, 1, span, parameter, basis),
301        2 => basis_functions_scratch::<3>(knots, 2, span, parameter, basis),
302        3 => basis_functions_scratch::<4>(knots, 3, span, parameter, basis),
303        4 => basis_functions_scratch::<5>(knots, 4, span, parameter, basis),
304        5 => basis_functions_scratch::<6>(knots, 5, span, parameter, basis),
305        8 => basis_functions_scratch::<9>(knots, 8, span, parameter, basis),
306        9 => basis_functions_scratch::<10>(knots, 9, span, parameter, basis),
307        _ => basis_functions_scratch::<MAX_STACK_ORDER>(knots, degree, span, parameter, basis),
308    }
309}
310
311/// [`basis_functions_into`]'s body with `left`/`right` scratch of `ORDER`
312/// entries (`degree < ORDER`). The recurrence reads only entries `..=degree`
313/// of either, so the scratch width changes no value.
314#[inline(always)]
315fn basis_functions_scratch<const ORDER: usize>(
316    knots: &[f64],
317    degree: usize,
318    span: usize,
319    parameter: f64,
320    basis: &mut [f64],
321) {
322    debug_assert!(degree < ORDER);
323    let mut left = [0.0f64; ORDER];
324    let mut right = [0.0f64; ORDER];
325    basis_functions_raw_into(knots, degree, span, parameter, EPS, basis, &mut left, &mut right);
326}
327
328/// Basis derivatives (The NURBS Book A2.3) into caller-provided stack rows.
329/// Writes rows `0..=min(derivative_count, degree)` of `out`; rows above the
330/// degree keep whatever the caller initialized them to (callers zero-fill,
331/// matching the heap implementation's zero rows). Requires
332/// `degree <= MAX_STACK_DEGREE` and `out.len() > derivative_count`.
333#[inline]
334pub fn basis_derivatives_into(
335    knots: &[f64], degree: usize, span: usize, parameter: f64,
336    derivative_count: usize, out: &mut [[f64; MAX_STACK_ORDER]],
337) {
338    debug_assert!(degree <= MAX_STACK_DEGREE);
339    basis_derivatives_wide(knots, degree, span, parameter, derivative_count, out);
340}
341
342/// Internal surface scratch, with the public helper's arithmetic.
343pub(crate) fn basis_derivatives_wide<const WIDTH: usize>(
344    knots: &[f64],
345    degree: usize,
346    span: usize,
347    parameter: f64,
348    derivative_count: usize,
349    out: &mut [[f64; WIDTH]],
350) {
351    debug_assert!(degree <= EVALUATOR_STACK_DEGREE);
352    debug_assert!(degree < WIDTH);
353    debug_assert!(out.len() > derivative_count);
354    // A value-only request needs only the current basis column. A2.2 uses
355    // the same scalar recurrence as A2.3's zeroth row, without its square
356    // derivative scratch table or the final column copy.
357    if derivative_count == 0 {
358        basis_functions_wide(knots, degree, span, parameter, &mut out[0]);
359        return;
360    }
361    // The degree is already fixed below, but A2.3's inner k loop still
362    // receives a runtime derivative count. Fix the common counts too,
363    // without changing the recurrence or the higher-order fallback.
364    if switch!("BREP_BASIS_DERIVATIVE_COUNT_FIXED", true) {
365        match derivative_count {
366            0 => return basis_derivatives_count_fixed::<0, WIDTH>(knots, degree, span, parameter, out),
367            1 => return basis_derivatives_count_fixed::<1, WIDTH>(knots, degree, span, parameter, out),
368            2 => return basis_derivatives_count_fixed::<2, WIDTH>(knots, degree, span, parameter, out),
369            _ => {}
370        }
371    }
372    // Degrees 1..=5, 8 and 9 with degree and scratch size fixed at compile
373    // time (see `basis_functions_into`): the same operations in the same
374    // order, so the same bits; `ndu`, `left`, `right` and `a` shrink from
375    // full-width to `degree + 1`-wide and the loop bounds fold.
376    match degree {
377        1 => basis_derivatives_scratch::<2, WIDTH>(knots, 1, span, parameter, derivative_count, out),
378        2 => basis_derivatives_scratch::<3, WIDTH>(knots, 2, span, parameter, derivative_count, out),
379        3 => basis_derivatives_scratch::<4, WIDTH>(knots, 3, span, parameter, derivative_count, out),
380        4 => basis_derivatives_scratch::<5, WIDTH>(knots, 4, span, parameter, derivative_count, out),
381        5 => basis_derivatives_scratch::<6, WIDTH>(knots, 5, span, parameter, derivative_count, out),
382        8 => basis_derivatives_scratch::<9, WIDTH>(knots, 8, span, parameter, derivative_count, out),
383        9 => basis_derivatives_scratch::<10, WIDTH>(knots, 9, span, parameter, derivative_count, out),
384        _ => basis_derivatives_scratch::<MAX_STACK_ORDER, WIDTH>(knots, degree, span, parameter, derivative_count, out),
385    }
386}
387
388#[inline(always)]
389fn basis_derivatives_count_fixed<const COUNT: usize, const WIDTH: usize>(
390    knots: &[f64], degree: usize, span: usize, parameter: f64,
391    out: &mut [[f64; WIDTH]],
392) {
393    match degree {
394        1 => basis_derivatives_scratch::<2, WIDTH>(knots, 1, span, parameter, COUNT, out),
395        2 => basis_derivatives_scratch::<3, WIDTH>(knots, 2, span, parameter, COUNT, out),
396        3 => basis_derivatives_scratch::<4, WIDTH>(knots, 3, span, parameter, COUNT, out),
397        4 => basis_derivatives_scratch::<5, WIDTH>(knots, 4, span, parameter, COUNT, out),
398        5 => basis_derivatives_scratch::<6, WIDTH>(knots, 5, span, parameter, COUNT, out),
399        8 => basis_derivatives_scratch::<9, WIDTH>(knots, 8, span, parameter, COUNT, out),
400        9 => basis_derivatives_scratch::<10, WIDTH>(knots, 9, span, parameter, COUNT, out),
401        _ => basis_derivatives_scratch::<MAX_STACK_ORDER, WIDTH>(knots, degree, span, parameter, COUNT, out),
402    }
403}
404
405/// [`basis_derivatives_into`]'s body (The NURBS Book A2.3) with every scratch
406/// array `ORDER` wide (`degree < ORDER`). The recurrence reads scratch entries
407/// `..=degree` only, and the per-order zero fill of `a[s2]` is kept (its
408/// unwritten entries are read as zero by the next order), so the width
409/// changes no value.
410#[inline(always)]
411fn basis_derivatives_scratch<const ORDER: usize, const WIDTH: usize>(
412    knots: &[f64],
413    degree: usize,
414    span: usize,
415    parameter: f64,
416    derivative_count: usize,
417    out: &mut [[f64; WIDTH]],
418) {
419        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
420    debug_assert!(degree < ORDER);
421    let p = degree;
422    let n = derivative_count.min(p);
423    let mut ndu = [[0.0f64; ORDER]; ORDER];
424    let mut left = [0.0f64; ORDER];
425    let mut right = [0.0f64; ORDER];
426    ndu[0][0] = 1.0;
427
428    for j in 1..=p {
429        left[j] = parameter - knots[span + 1 - j];
430        right[j] = knots[span + j] - parameter;
431        let mut saved = 0.0;
432        for r in 0..j {
433            ndu[j][r] = right[r + 1] + left[j - r];
434            let temporary = if ndu[j][r].abs() <= EPS {
435                0.0
436            } else {
437                ndu[r][j - 1] / ndu[j][r]
438            };
439            ndu[r][j] = saved + right[r + 1] * temporary;
440            saved = left[j - r] * temporary;
441        }
442        ndu[j][j] = saved;
443    }
444
445    for j in 0..=p {
446        out[0][j] = ndu[j][p];
447    }
448    let mut a = [[0.0f64; ORDER]; 2];
449    for r in 0..=p {
450        let mut s1 = 0;
451        let mut s2 = 1;
452        a[0][0] = 1.0;
453        for k in 1..=n {
454            a[s2] = [0.0; ORDER];
455            let mut value = 0.0;
456            let rk = r as isize - k as isize;
457            let pk = p - k;
458            if r >= k {
459                let denominator = ndu[pk + 1][rk as usize];
460                a[s2][0] = a[s1][0] / denominator;
461                value = a[s2][0] * ndu[rk as usize][pk];
462            }
463            let j1 = if rk >= -1 { 1 } else { (-rk) as usize };
464            let j2 = if r <= pk + 1 { k - 1 } else { p - r };
465            if j1 <= j2 {
466                for j in j1..=j2 {
467                    let index = (rk + j as isize) as usize;
468                    a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][index];
469                    value += a[s2][j] * ndu[index][pk];
470                }
471            }
472            if r <= pk {
473                a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r];
474                value += a[s2][k] * ndu[r][pk];
475            }
476            out[k][r] = value;
477            std::mem::swap(&mut s1, &mut s2);
478        }
479    }
480    let mut factor = p as f64;
481    for k in 1..=n {
482        for value in out[k][..=p].iter_mut() {
483            *value *= factor;
484        }
485        factor *= (p - k) as f64;
486    }
487}
488
489#[derive(Clone, Debug, Deserialize, Serialize)]
490pub struct KnotVector {
491    pub knots: Vec<f64>,
492    pub degree: usize,
493}
494
495/// Distinct interior knots, excluding endpoint neighborhoods within `1e-12`.
496pub fn interior_knots(knots: &[f64], degree: usize) -> Vec<f64> {
497    distinct_interior_knots(knots, degree).collect()
498}
499
500impl KnotVector {
501    pub fn new(knots: Vec<f64>, degree: usize) -> Result<Self, String> {
502        validate_knots(&knots, degree)?;
503        Ok(Self { knots, degree })
504    }
505
506    pub fn control_point_count(&self) -> usize {
507        self.knots.len() - self.degree - 1
508    }
509
510    pub fn domain(&self) -> [f64; 2] {
511        [
512            self.knots[self.degree],
513            self.knots[self.knots.len() - 1 - self.degree],
514        ]
515    }
516
517    pub fn clamp_param(&self, parameter: f64) -> f64 {
518        knot_clamp(&self.knots, self.degree, parameter)
519    }
520
521    pub fn find_span(&self, parameter: f64) -> usize {
522        knot_find_span(&self.knots, self.degree, parameter)
523    }
524
525    pub fn basis_functions(&self, span: usize, parameter: f64) -> Vec<f64> {
526        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
527        if self.degree <= MAX_STACK_DEGREE {
528            let mut basis = [0.0f64; MAX_STACK_ORDER];
529            basis_functions_into(&self.knots, self.degree, span, parameter, &mut basis);
530            return basis[..=self.degree].to_vec();
531        }
532        basis_functions_raw(&self.knots, self.degree, span, parameter, EPS)
533    }
534
535    /// [`Self::basis_functions`] read in place: the same values, handed to
536    /// `read` without a heap copy when the degree fits the stack rows.
537    pub fn with_basis_functions<T>(&self, span: usize, parameter: f64, read: impl FnOnce(&[f64]) -> T) -> T {
538        if self.degree <= MAX_STACK_DEGREE {
539            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
540            let mut basis = [0.0f64; MAX_STACK_ORDER];
541            basis_functions_into(&self.knots, self.degree, span, parameter, &mut basis);
542            drop(_reader_part);
543            return read(&basis[..=self.degree]);
544        }
545        read(&self.basis_functions(span, parameter))
546    }
547
548    pub fn basis_derivatives(
549        &self,
550        span: usize,
551        parameter: f64,
552        derivative_count: usize,
553    ) -> Vec<Vec<f64>> {
554        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
555        if self.degree <= MAX_STACK_DEGREE && derivative_count <= MAX_STACK_DEGREE {
556            let mut rows = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
557            basis_derivatives_into(
558                &self.knots,
559                self.degree,
560                span,
561                parameter,
562                derivative_count,
563                &mut rows[..=derivative_count],
564            );
565            return rows[..=derivative_count]
566                .iter()
567                .map(|row| row[..=self.degree].to_vec())
568                .collect();
569        }
570        let p = self.degree;
571        let n = derivative_count.min(p);
572        let mut ndu = vec![vec![0.0; p + 1]; p + 1];
573        let mut left = vec![0.0; p + 1];
574        let mut right = vec![0.0; p + 1];
575        ndu[0][0] = 1.0;
576
577        for j in 1..=p {
578            left[j] = parameter - self.knots[span + 1 - j];
579            right[j] = self.knots[span + j] - parameter;
580            let mut saved = 0.0;
581            for r in 0..j {
582                ndu[j][r] = right[r + 1] + left[j - r];
583                let temporary = if ndu[j][r].abs() <= EPS {
584                    0.0
585                } else {
586                    ndu[r][j - 1] / ndu[j][r]
587                };
588                ndu[r][j] = saved + right[r + 1] * temporary;
589                saved = left[j - r] * temporary;
590            }
591            ndu[j][j] = saved;
592        }
593
594        let mut derivatives = vec![vec![0.0; p + 1]; derivative_count + 1];
595        for j in 0..=p {
596            derivatives[0][j] = ndu[j][p];
597        }
598        let mut a = vec![vec![0.0; p + 1]; 2];
599        for r in 0..=p {
600            let mut s1 = 0;
601            let mut s2 = 1;
602            a[0][0] = 1.0;
603            for k in 1..=n {
604                a[s2].fill(0.0);
605                let mut value = 0.0;
606                let rk = r as isize - k as isize;
607                let pk = p - k;
608                if r >= k {
609                    let denominator = ndu[pk + 1][rk as usize];
610                    a[s2][0] = a[s1][0] / denominator;
611                    value = a[s2][0] * ndu[rk as usize][pk];
612                }
613                let j1 = if rk >= -1 { 1 } else { (-rk) as usize };
614                let j2 = if r <= pk + 1 { k - 1 } else { p - r };
615                if j1 <= j2 {
616                    for j in j1..=j2 {
617                        let index = (rk + j as isize) as usize;
618                        a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][index];
619                        value += a[s2][j] * ndu[index][pk];
620                    }
621                }
622                if r <= pk {
623                    a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r];
624                    value += a[s2][k] * ndu[r][pk];
625                }
626                derivatives[k][r] = value;
627                std::mem::swap(&mut s1, &mut s2);
628            }
629        }
630        let mut factor = p as f64;
631        for (k, row) in derivatives.iter_mut().enumerate().take(n + 1).skip(1) {
632            for value in row {
633                *value *= factor;
634            }
635            factor *= (p - k) as f64;
636        }
637        derivatives
638    }
639}
640
641/// A rational B-spline curve.
642///
643/// **Invariant: an in-place edit of the public fields must keep the curve
644/// valid.** The curve caches that it passed validation (finite values,
645/// positive weights, a clamped knot vector with a positive domain), and
646/// `Clone` copies that flag; nothing re-checks a field edited in place. Prefer
647/// building a new value with [`NurbsCurve::new`].
648#[derive(Clone, Debug, Deserialize, Serialize)]
649pub struct NurbsCurve {
650    pub degree: usize,
651    pub knots: Vec<f64>,
652    pub control_points: Vec<Vec4>,
653    /// One-time validation cache. Deserialized curves (which bypass `new`)
654    /// run the full `new`-equivalent checks on first geometric use instead of
655    /// re-validating the knot vector on every evaluation.
656    #[serde(skip, default)]
657    validated: std::cell::Cell<bool>,
658    /// Read from a file (STEP, Parasolid, IGES) rather than built by the
659    /// kernel. The strict edge/pcurve bar judges only coedges whose edge
660    /// curve and pcurve are both kernel-built. Carried by `Clone` and by the
661    /// curve's own derivations (`reversed`, `insert_knot`, `split`); a curve
662    /// built afresh with [`NurbsCurve::new`] is kernel-built. Never part of
663    /// the geometry: no comparison or identity hash reads it. Serialized
664    /// only when set, so a kernel-built curve's JSON is unchanged.
665    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
666    imported: bool,
667}
668
669impl NurbsCurve {
670    /// Whether the one-time validation has run. For the boolean's
671    /// operand-state instrument (`BREP_DEBUG_OPERAND_STATE`).
672    pub fn is_validated(&self) -> bool {
673        self.validated.get()
674    }
675
676    /// Sets the validation cache: for the operand-state instrument only.
677    pub fn set_validated(&mut self, validated: bool) {
678        self.validated = std::cell::Cell::new(validated);
679    }
680
681    pub fn new(degree: usize, knots: Vec<f64>, control_points: Vec<Vec4>) -> Result<Self, String> {
682        let curve = Self {
683            degree,
684            knots,
685            control_points,
686            validated: std::cell::Cell::new(false),
687            imported: false,
688        };
689        curve.ensure_valid()?;
690        Ok(curve)
691    }
692
693    /// Whether this curve was read from a file (see the `imported` field).
694    pub fn is_imported(&self) -> bool {
695        self.imported
696    }
697
698    /// Marks this curve as read from a file, or as kernel-built.
699    pub fn set_imported(&mut self, imported: bool) {
700        self.imported = imported;
701    }
702
703    /// This curve carrying `source`'s provenance: for a curve derived from
704    /// `source` (a piece, a reversal, a transform of it).
705    pub fn with_provenance_of(mut self, source: &NurbsCurve) -> Self {
706        self.imported = source.imported;
707        self
708    }
709
710    /// The full construction-time checks, run at most once per instance.
711    fn ensure_valid(&self) -> Result<(), String> {
712        if self.validated.get() {
713            return Ok(());
714        }
715        validate_knots(&self.knots, self.degree)?;
716        let expected = self.knots.len() - self.degree - 1;
717        if self.control_points.len() != expected {
718            return Err(format!(
719                "NurbsCurve: knot vector implies {} control points, got {}",
720                expected,
721                self.control_points.len()
722            ));
723        }
724        if self.control_points.iter().any(|point| {
725            point.w <= EPS
726                || ![point.x, point.y, point.z, point.w]
727                    .iter()
728                    .all(|value| value.is_finite())
729        }) {
730            return Err("NurbsCurve: control points must be finite with positive weights".into());
731        }
732        self.validated.set(true);
733        Ok(())
734    }
735
736    fn knot_vector(&self) -> Result<KnotVector, String> {
737        KnotVector::new(self.knots.clone(), self.degree)
738    }
739
740    pub fn domain(&self) -> Result<[f64; 2], String> {
741        self.ensure_valid()?;
742        Ok(knot_domain(&self.knots, self.degree))
743    }
744
745    #[cfg_attr(feature = "profile-wall", track_caller)]
746    pub fn evaluate_homogeneous(&self, parameter: f64) -> Result<Vec4, String> {
747        let _reader = crate::reader_profile::Point::open(crate::reader_profile::CURVE, std::panic::Location::caller());
748    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
749        if crate::switch!("BREP_CURVE_POINT_FIXED", true) {
750            match self.degree {
751                1 => return self.evaluate_homogeneous_fixed::<1, 2>(parameter),
752                2 => return self.evaluate_homogeneous_fixed::<2, 3>(parameter),
753                3 => return self.evaluate_homogeneous_fixed::<3, 4>(parameter),
754                _ => {}
755            }
756        }
757        self.ensure_valid()?;
758        let span = knot_find_span(&self.knots, self.degree, parameter);
759        let parameter = knot_clamp(&self.knots, self.degree, parameter);
760        let mut point = Vec4 {
761            x: 0.0,
762            y: 0.0,
763            z: 0.0,
764            w: 0.0,
765        };
766        if self.degree <= MAX_STACK_DEGREE {
767            let mut basis = [0.0f64; MAX_STACK_ORDER];
768            basis_functions_into(&self.knots, self.degree, span, parameter, &mut basis);
769            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
770            for (index, value) in basis[..=self.degree].iter().enumerate() {
771                point = point.add(self.control_points[span - self.degree + index].scale(*value));
772            }
773        } else {
774            let knot_vector = self.knot_vector()?;
775            let basis = knot_vector.basis_functions(span, parameter);
776            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
777            for (index, value) in basis.iter().enumerate() {
778                point = point.add(self.control_points[span - self.degree + index].scale(*value));
779            }
780        }
781        Ok(point)
782    }
783
784    // Same Cox–de Boor recurrence and accumulation order as the general
785    // reader, with the common degrees and scratch widths known at compile time.
786    fn evaluate_homogeneous_fixed<const DEGREE: usize, const ORDER: usize>(&self, parameter: f64) -> Result<Vec4, String> {
787        self.ensure_valid()?;
788        let span = knot_find_span(&self.knots, DEGREE, parameter);
789        let parameter = knot_clamp(&self.knots, DEGREE, parameter);
790        let mut basis = [0.0f64; ORDER];
791        let mut left = [0.0f64; ORDER];
792        let mut right = [0.0f64; ORDER];
793        {
794            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
795            basis[0] = 1.0;
796            for j in 1..=DEGREE {
797                left[j] = parameter - self.knots[span + 1 - j];
798                right[j] = self.knots[span + j] - parameter;
799                let mut saved = 0.0;
800                for r in 0..j {
801                    let denominator = right[r + 1] + left[j - r];
802                    let temporary = if denominator.abs() <= EPS { 0.0 } else { basis[r] / denominator };
803                    basis[r] = saved + right[r + 1] * temporary;
804                    saved = left[j - r] * temporary;
805                }
806                basis[j] = saved;
807            }
808        }
809        let mut point = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
810        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
811        for (index, value) in basis.iter().enumerate() {
812            point = point.add(self.control_points[span - DEGREE + index].scale(*value));
813        }
814        Ok(point)
815    }
816
817    #[cfg_attr(feature = "profile-wall", track_caller)]
818    pub fn evaluate(&self, parameter: f64) -> Result<Vec3, String> {
819        let _reader = crate::reader_profile::Point::open(crate::reader_profile::CURVE, std::panic::Location::caller());
820    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
821        self.evaluate_homogeneous(parameter)?.point()
822    }
823
824    /// The straight segment this curve traces, as `(start, end)`, or `None`
825    /// when it genuinely bends.
826    ///
827    /// What a direct-edit heal actually needs to know about an edge is
828    /// *geometric* — "is this a straight segment I may rebuild between two
829    /// re-solved corners?" — but it used to be answered by the
830    /// *representation* `degree == 1 && control_points.len() == 2`. That
831    /// answer is wrong for a line that carries an interior knot, which is what
832    /// an offset shell or a boolean leaves behind when it splits a box edge and
833    /// rejoins the pieces: the same line, three control points, and every heal
834    /// that asked the representation question called it "curved".
835    ///
836    /// Weights are strictly positive (`ensure_valid`), so every point of the
837    /// curve is a convex combination of its control points and the curve is a
838    /// straight segment **iff** those control points are collinear — for any
839    /// degree, not just degree 1. Monotone projections onto the chord are
840    /// required too, so a polyline that doubles back along its own line (it
841    /// covers the segment but does not parameterise it) is not mistaken for
842    /// one.
843    pub fn straight_segment(&self, tolerance: f64) -> Option<(Vec3, Vec3)> {
844        self.ensure_valid().ok()?;
845        let points = self
846            .control_points
847            .iter()
848            .map(|point| point.point().ok())
849            .collect::<Option<Vec<Vec3>>>()?;
850        let start = *points.first()?;
851        let end = *points.last()?;
852        let chord = end.sub(start);
853        let length = chord.length();
854        if length <= tolerance {
855            return None;
856        }
857        let direction = chord.scale(1.0 / length);
858        let mut reached = 0.0f64;
859        for point in &points {
860            let offset = point.sub(start);
861            let axial = offset.dot(direction);
862            if offset.sub(direction.scale(axial)).length() > tolerance {
863                return None; // off the chord — the curve genuinely bends
864            }
865            if axial < reached - tolerance {
866                return None; // collinear, but the polygon doubles back
867            }
868            reached = reached.max(axial);
869        }
870        Some((start, end))
871    }
872
873    /// Value beyond the domain (Golovanov §2.15): every curve must answer
874    /// out-of-domain queries because intersection and projection
875    /// algorithms probe there.  Closed curves wrap the parameter
876    /// cyclically; open curves extend linearly along the end tangent.
877    #[cfg_attr(feature = "profile-wall", track_caller)]
878    pub fn evaluate_extended(&self, parameter: f64) -> Result<Vec3, String> {
879        let _reader = crate::reader_profile::Point::open(crate::reader_profile::CURVE, std::panic::Location::caller());
880    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
881        Ok(self.derivatives_extended(parameter, 0)?[0])
882    }
883
884    /// Derivatives beyond the domain (§2.15).  The open-end extension is
885    /// linear: the first derivative is the boundary tangent and higher
886    /// derivatives vanish.
887    pub fn derivatives_extended(
888        &self,
889        parameter: f64,
890        derivative_count: usize,
891    ) -> Result<Vec<Vec3>, String> {
892        let [start, end] = self.domain()?;
893        if parameter >= start && parameter <= end {
894            return self.derivatives(parameter, derivative_count);
895        }
896        let period = end - start;
897        if period > 0.0 {
898            let closed =
899                self.evaluate(start)?.sub(self.evaluate(end)?).length() <= 1e-9 * (1.0 + period);
900            if closed {
901                let wrapped = start + (parameter - start).rem_euclid(period);
902                return self.derivatives(wrapped, derivative_count);
903            }
904        }
905        let boundary = if parameter < start { start } else { end };
906        let base = self.derivatives(boundary, derivative_count.max(1))?;
907        let mut result = Vec::with_capacity(derivative_count + 1);
908        result.push(base[0].add(base[1].scale(parameter - boundary)));
909        if derivative_count >= 1 {
910            result.push(base[1]);
911        }
912        for _ in 2..=derivative_count {
913            result.push(Vec3::default());
914        }
915        Ok(result)
916    }
917
918    pub fn derivatives(
919        &self,
920        parameter: f64,
921        derivative_count: usize,
922    ) -> Result<Vec<Vec3>, String> {
923        if derivative_count <= 2 && small_curve_derivatives_enabled() {
924            return Ok(self.derivatives_small(parameter, derivative_count)?[..=derivative_count].to_vec());
925        }
926        self.ensure_valid()?;
927        let parameter = knot_clamp(&self.knots, self.degree, parameter);
928        let span = knot_find_span(&self.knots, self.degree, parameter);
929        let calculated_count = derivative_count.min(self.degree);
930        let mut homogeneous: Vec<Vec4> = Vec::with_capacity(calculated_count + 1);
931        if self.degree <= MAX_STACK_DEGREE {
932            let mut rows = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
933            basis_derivatives_into(
934                &self.knots,
935                self.degree,
936                span,
937                parameter,
938                calculated_count,
939                &mut rows[..=calculated_count],
940            );
941            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
942            for row in rows.iter().take(calculated_count + 1) {
943                let mut point = Vec4 {
944                    x: 0.0,
945                    y: 0.0,
946                    z: 0.0,
947                    w: 0.0,
948                };
949                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
950                    point =
951                        point.add(self.control_points[span - self.degree + index].scale(*value));
952                }
953                homogeneous.push(point);
954            }
955        } else {
956            let knot_vector = self.knot_vector()?;
957            let basis = knot_vector.basis_derivatives(span, parameter, calculated_count);
958            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
959            for row in basis.iter().take(calculated_count + 1) {
960                let mut point = Vec4 {
961                    x: 0.0,
962                    y: 0.0,
963                    z: 0.0,
964                    w: 0.0,
965                };
966                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
967                    point =
968                        point.add(self.control_points[span - self.degree + index].scale(*value));
969                }
970                homogeneous.push(point);
971            }
972        }
973
974        let mut result: Vec<Vec3> = Vec::with_capacity(derivative_count + 1);
975        for k in 0..=calculated_count {
976            let mut value = Vec3::new(homogeneous[k].x, homogeneous[k].y, homogeneous[k].z);
977            for i in 1..=k {
978                value = value.sub(result[k - i].scale(binomial(k, i) * homogeneous[i].w));
979            }
980            result.push(value.scale(1.0 / homogeneous[0].w));
981        }
982        result.resize(derivative_count + 1, Vec3::default());
983        Ok(result)
984    }
985
986    /// The curve's unit TANGENT at `parameter`, read as the one-sided limit
987    /// when the first derivative vanishes there.
988    ///
989    /// This is what `derivatives(t, 1)?[1].normalized()?` should always have
990    /// been. That shape refuses on a curve class that is not exotic at all —
991    /// any Hermite segment whose end tangent is the zero vector, of which an
992    /// INVOLUTE flank is the standard source (speed `r_base * t`, so a profile
993    /// sampled from the base circle outwards carries an exactly zero tangent at
994    /// its start, one per flank per tooth). The direction of travel is still
995    /// defined there, as the limit from inside the range, and
996    /// [`Self::stationary_tangent_rescue`] reads it.
997    ///
998    /// Pass the range the CALLER owns — an edge's `[t0, t1]`, not the curve's
999    /// domain, where the two differ (an `EdgeRecord` keeps the whole curve and
1000    /// records the sub-range it uses), so the probe never reads geometry
1001    /// outside the caller's own span.
1002    ///
1003    /// The error names the parameter and the range it probed, because the only
1004    /// curve that reaches it is stationary EVERYWHERE the range allows, and the
1005    /// caller's own identifier is the half this function cannot supply.
1006    ///
1007    /// Escape hatch for tamper-verification: `BREP_CUSP_TANGENT_RESCUE=0`
1008    /// restores the bare `normalized()` refusal, the same hatch the imprint
1009    /// driver's seed loop carries.
1010    pub fn unit_tangent(
1011        &self,
1012        parameter: f64,
1013        range_start: f64,
1014        range_end: f64,
1015    ) -> Result<Vec3, String> {
1016        let derivative = self.derivatives(parameter, 1)?[1];
1017        self.tangent_or_one_sided_limit(derivative, parameter, range_start, range_end)
1018    }
1019
1020    /// The point and unit tangent that `derivatives_extended(parameter, 1)`
1021    /// reads, with the tangent taken as [`Self::unit_tangent`] takes it.
1022    ///
1023    /// The blend march reads its section plane — the point and the edge's
1024    /// unit tangent — through the EXTENDED evaluation at every station,
1025    /// overshoot stations past the edge's ends included, and `unit_tangent`
1026    /// cannot stand in for that read: it evaluates `derivatives`, which CLAMPS
1027    /// a parameter outside the domain, where `derivatives_extended` WRAPS it on
1028    /// a closed curve. A closed rim's overshoot station would read a different
1029    /// tangent. This is the same one evaluation the march always made, so a
1030    /// non-zero derivative returns the vector `derivatives[1].normalized()`
1031    /// returned, to the bit, at no extra cost.
1032    ///
1033    /// Where the derivative vanishes, the one-sided limit is read at the
1034    /// parameter the extended evaluation actually took its derivative from —
1035    /// the parameter itself inside the domain, the wrapped one on a closed
1036    /// curve, the boundary past an open end, where the extension's direction
1037    /// IS the boundary's one-sided limit. The caller's range is widened to
1038    /// contain that parameter, because an overshoot station reads outside the
1039    /// caller's span on purpose; the ladder still probes from the side the
1040    /// range lies on.
1041    pub fn point_and_unit_tangent_extended(
1042        &self,
1043        parameter: f64,
1044        range_start: f64,
1045        range_end: f64,
1046    ) -> Result<(Vec3, Vec3), String> {
1047        let derivatives = self.derivatives_extended(parameter, 1)?;
1048        if let Ok(tangent) = derivatives[1].normalized() {
1049            return Ok((derivatives[0], tangent));
1050        }
1051        let read_at = self.extended_read_parameter(parameter)?;
1052        let low = range_start.min(range_end).min(read_at);
1053        let high = range_start.max(range_end).max(read_at);
1054        let tangent = self.tangent_or_one_sided_limit(derivatives[1], read_at, low, high)?;
1055        Ok((derivatives[0], tangent))
1056    }
1057
1058    /// The in-domain parameter whose derivatives `derivatives_extended` reads
1059    /// for `parameter`: itself inside the domain, wrapped on a closed curve,
1060    /// the nearer boundary past an open end. Mirrors that function's three
1061    /// cases; only the zero-derivative lane of
1062    /// [`Self::point_and_unit_tangent_extended`] pays for it.
1063    fn extended_read_parameter(&self, parameter: f64) -> Result<f64, String> {
1064        let [start, end] = self.domain()?;
1065        if parameter >= start && parameter <= end {
1066            return Ok(parameter);
1067        }
1068        if self.extension_wraps(start, end)? {
1069            return Ok(start + (parameter - start).rem_euclid(end - start));
1070        }
1071        Ok(if parameter < start { start } else { end })
1072    }
1073
1074    /// `derivatives_extended`'s closed test: a curve whose ends meet WRAPS an
1075    /// out-of-domain parameter instead of extending it.
1076    fn extension_wraps(&self, start: f64, end: f64) -> Result<bool, String> {
1077        let period = end - start;
1078        Ok(period > 0.0
1079            && self.evaluate(start)?.sub(self.evaluate(end)?).length() <= 1e-9 * (1.0 + period))
1080    }
1081
1082    /// The open end `parameter` lies past, when the first derivative VANISHES
1083    /// there — the one case in which `derivatives_extended`'s point does not
1084    /// move with its parameter: past an open end it returns
1085    /// `P(end) + C'(end)·(t − end)`, which is `P(end)` for every `t` when
1086    /// `C'(end) = 0`. `None` inside the domain, on a closed curve (which wraps
1087    /// onto the real curve), and past an end whose derivative is regular.
1088    ///
1089    /// The zero test is [`Self::point_and_unit_tangent_extended`]'s own: the
1090    /// derivative has no unit vector. A caller that extends past such an end
1091    /// supplies the SPEED the parameterization does not; the direction is the
1092    /// one-sided limit that function already reads there.
1093    pub fn stationary_open_end(&self, parameter: f64) -> Result<Option<f64>, String> {
1094        let [start, end] = self.domain()?;
1095        if parameter >= start && parameter <= end {
1096            return Ok(None);
1097        }
1098        let boundary = if parameter < start { start } else { end };
1099        if self.derivatives(boundary, 1)?[1].normalized().is_ok()
1100            || self.extension_wraps(start, end)?
1101        {
1102            return Ok(None);
1103        }
1104        Ok(Some(boundary))
1105    }
1106
1107    /// `derivative`, normalized — or, where it vanishes, the one-sided limit
1108    /// from inside `[range_start, range_end]` at `parameter`, or the named
1109    /// refusal. The one failure lane [`Self::unit_tangent`] and
1110    /// [`Self::point_and_unit_tangent_extended`] share.
1111    fn tangent_or_one_sided_limit(
1112        &self,
1113        derivative: Vec3,
1114        parameter: f64,
1115        range_start: f64,
1116        range_end: f64,
1117    ) -> Result<Vec3, String> {
1118        let error = match derivative.normalized() {
1119            Ok(tangent) => return Ok(tangent),
1120            Err(error) => error,
1121        };
1122        if std::env::var("BREP_CUSP_TANGENT_RESCUE").as_deref() == Ok("0") {
1123            return Err(error);
1124        }
1125        self.stationary_tangent_rescue(parameter, range_start, range_end)
1126            .ok_or_else(|| {
1127                format!(
1128                    "curve tangent: the first derivative vanishes at t = {parameter} and \
1129                     everywhere in [{range_start}, {range_end}] the probe can reach, so this \
1130                     curve has no direction of travel to report"
1131                )
1132            })
1133    }
1134
1135    /// The unit tangent just inside `[range_start, range_end]`, for a
1136    /// `parameter` where the first derivative VANISHES.
1137    ///
1138    /// A curve can be stationary at a parameter where the curve itself is
1139    /// perfectly well behaved, and the direction of travel is then still
1140    /// defined as the one-sided limit. The standard case is a cubic Bezier
1141    /// whose first two control points coincide — the shape a Hermite segment
1142    /// takes when its end tangent is the zero vector — and an INVOLUTE is the
1143    /// standard source of one: the involute's speed is `r_base * t`, so a gear
1144    /// flank sampled from the base circle outwards starts with an exactly zero
1145    /// tangent and every tooth profile carries one per flank. The 2026-09-14
1146    /// herringbone report is that shape: a hit landing exactly on the cusp
1147    /// parameter made `derivatives(t, 1)[1].normalized()` fail and killed the
1148    /// whole union.
1149    ///
1150    /// The range bounds the probe — pass an edge's own `[t0, t1]` and the
1151    /// rescue never reads the curve outside the span the caller owns. The
1152    /// ladder walks OUTWARDS, and it starts at 1e-6 of the span rather than at
1153    /// the smallest representable step: the rescued direction is a ONE-SIDED
1154    /// limit, so a nearer probe truncates less, but the derivative at a
1155    /// stationary point is a CANCELLING sum that shrinks with the step while
1156    /// its rounding error does not — at 1e-9 of the span the involute cusp
1157    /// below reads its own limit direction only to 1e-6, worse than at 1e-6 of
1158    /// the span. Later rungs exist for a higher-order stationary point, whose
1159    /// derivative is still under the zero-length floor at the first. `None`
1160    /// means the curve is stationary everywhere the range allows, where no
1161    /// direction exists to report at all.
1162    pub fn stationary_tangent_rescue(
1163        &self,
1164        parameter: f64,
1165        range_start: f64,
1166        range_end: f64,
1167    ) -> Option<Vec3> {
1168        let low = range_start.min(range_end);
1169        let high = range_start.max(range_end);
1170        let span = high - low;
1171        if !(span > 0.0) {
1172            return None;
1173        }
1174        for scale in [1e-6, 1e-4, 1e-2, 1e-1] {
1175            let step = span * scale;
1176            for probe in [parameter + step, parameter - step] {
1177                if probe < low || probe > high {
1178                    continue;
1179                }
1180                if let Some(unit) = self
1181                    .derivatives(probe, 1)
1182                    .ok()
1183                    .and_then(|derivatives| derivatives[1].normalized().ok())
1184                {
1185                    return Some(unit);
1186                }
1187            }
1188        }
1189        None
1190    }
1191
1192    /// Allocation-free twin of [`Self::derivatives`] for the hot
1193    /// `derivative_count <= 2` path.
1194    ///
1195    /// Byte-for-byte faithful copy of the arithmetic in [`Self::derivatives`]:
1196    /// identical basis evaluation, identical summation order, and the identical
1197    /// rational de-homogenization recurrence. Only the storage differs — a
1198    /// fixed-size `[Vec4; 3]` / `[Vec3; 3]` on the stack instead of the heap
1199    /// `Vec`s. Entries beyond `derivative_count.min(degree)` stay
1200    /// `Vec3::default()`, exactly as the heap version's trailing `resize` leaves
1201    /// them.
1202    pub fn derivatives_small(
1203        &self,
1204        parameter: f64,
1205        derivative_count: usize,
1206    ) -> Result<[Vec3; 3], String> {
1207        debug_assert!(derivative_count <= 2);
1208        self.ensure_valid()?;
1209        let parameter = knot_clamp(&self.knots, self.degree, parameter);
1210        let span = knot_find_span(&self.knots, self.degree, parameter);
1211        let calculated_count = derivative_count.min(self.degree);
1212        let zero = Vec4 {
1213            x: 0.0,
1214            y: 0.0,
1215            z: 0.0,
1216            w: 0.0,
1217        };
1218        let mut homogeneous = [zero; 3];
1219        if self.degree <= MAX_STACK_DEGREE {
1220            // Rows `..=calculated_count` (at most three) are the only ones
1221            // written or read; the eight-row fill was pure cost.
1222            let mut rows = [[0.0f64; MAX_STACK_ORDER]; 3];
1223            basis_derivatives_into(
1224                &self.knots,
1225                self.degree,
1226                span,
1227                parameter,
1228                calculated_count,
1229                &mut rows[..=calculated_count],
1230            );
1231            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
1232            for (k, row) in rows.iter().take(calculated_count + 1).enumerate() {
1233                let mut point = zero;
1234                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
1235                    point =
1236                        point.add(self.control_points[span - self.degree + index].scale(*value));
1237                }
1238                homogeneous[k] = point;
1239            }
1240        } else {
1241            let knot_vector = self.knot_vector()?;
1242            let basis = knot_vector.basis_derivatives(span, parameter, calculated_count);
1243            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
1244            for (k, row) in basis.iter().take(calculated_count + 1).enumerate() {
1245                let mut point = zero;
1246                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
1247                    point =
1248                        point.add(self.control_points[span - self.degree + index].scale(*value));
1249                }
1250                homogeneous[k] = point;
1251            }
1252        }
1253
1254        let mut result = [Vec3::default(); 3];
1255        for k in 0..=calculated_count {
1256            let mut value = Vec3::new(homogeneous[k].x, homogeneous[k].y, homogeneous[k].z);
1257            for i in 1..=k {
1258                value = value.sub(result[k - i].scale(binomial(k, i) * homogeneous[i].w));
1259            }
1260            result[k] = value.scale(1.0 / homogeneous[0].w);
1261        }
1262        Ok(result)
1263    }
1264
1265    /// First derivative with the low degree and recurrence width fixed at
1266    /// compile time. Accumulation and rational conversion keep the ordinary
1267    /// reader's operation order.
1268    fn deriv1_fixed<const DEGREE: usize, const ORDER: usize>(&self, parameter: f64) -> Result<(Vec3, Vec3), String> {
1269        self.ensure_valid()?;
1270        let parameter = knot_clamp(&self.knots, DEGREE, parameter);
1271        let span = knot_find_span(&self.knots, DEGREE, parameter);
1272        let mut rows = [[0.0; MAX_STACK_ORDER]; 2];
1273        basis_derivatives_scratch::<ORDER, MAX_STACK_ORDER>(&self.knots, DEGREE, span, parameter, 1, &mut rows);
1274        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1275        let mut homogeneous = [zero; 2];
1276        let reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
1277        for k in 0..2 {
1278            let mut point = zero;
1279            for index in 0..=DEGREE {
1280                point = point.add(self.control_points[span - DEGREE + index].scale(rows[k][index]));
1281            }
1282            homogeneous[k] = point;
1283        }
1284        drop(reader_part);
1285        let inverse = 1.0 / homogeneous[0].w;
1286        let point = Vec3::new(homogeneous[0].x, homogeneous[0].y, homogeneous[0].z).scale(inverse);
1287        let tangent = Vec3::new(homogeneous[1].x, homogeneous[1].y, homogeneous[1].z)
1288            .sub(point.scale(1.0 * homogeneous[1].w)).scale(inverse);
1289        Ok((point, tangent))
1290    }
1291
1292    /// Point and first derivative `(C, C')` with zero heap allocation.
1293    /// Bit-identical to `derivatives(t, 1)` at indices `[0]` and `[1]`.
1294    #[inline]
1295    pub fn deriv1(&self, parameter: f64) -> Result<(Vec3, Vec3), String> {
1296        if switch!("BREP_CURVE_DERIV1_FIXED", true) {
1297            match self.degree {
1298                1 => return self.deriv1_fixed::<1, 2>(parameter),
1299                2 => return self.deriv1_fixed::<2, 3>(parameter),
1300                3 => return self.deriv1_fixed::<3, 4>(parameter),
1301                _ => {}
1302            }
1303        }
1304        let d = self.derivatives_small(parameter, 1)?;
1305        Ok((d[0], d[1]))
1306    }
1307
1308    pub fn reversed(&self) -> Result<Self, String> {
1309        let start = self.knots[0];
1310        let end = self.knots[self.knots.len() - 1];
1311        let knots = self
1312            .knots
1313            .iter()
1314            .rev()
1315            .map(|knot| start + end - knot)
1316            .collect();
1317        let control_points = self.control_points.iter().rev().copied().collect();
1318        Ok(Self::new(self.degree, knots, control_points)?.with_provenance_of(self))
1319    }
1320
1321    pub fn insert_knot(&self, parameter: f64, requested: usize) -> Result<Self, String> {
1322        Ok(self.insert_knot_raw(parameter, requested)?.with_provenance_of(self))
1323    }
1324
1325    fn insert_knot_raw(&self, parameter: f64, requested: usize) -> Result<Self, String> {
1326        let knot_vector = self.knot_vector()?;
1327        let degree = self.degree;
1328        let parameter = knot_vector.clamp_param(parameter);
1329        // A parameter within knot tolerance of an existing knot must BE
1330        // that knot: counting it as a multiplicity while find_span places
1331        // it in the span below (parameter infinitesimally smaller) makes
1332        // the Boehm index bookkeeping inconsistent and corrupts the net.
1333        let parameter = self
1334            .knots
1335            .iter()
1336            .copied()
1337            .find(|knot| (knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1338            .unwrap_or(parameter);
1339        let multiplicity = self
1340            .knots
1341            .iter()
1342            .filter(|knot| (**knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1343            .count();
1344        let insertion_count = requested.min(degree.saturating_sub(multiplicity));
1345        if insertion_count == 0 {
1346            return Ok(self.clone());
1347        }
1348        let span = knot_vector.find_span(parameter);
1349        let last_control = self.control_points.len() - 1;
1350        let mut knots = Vec::with_capacity(self.knots.len() + insertion_count);
1351        knots.extend_from_slice(&self.knots[..=span]);
1352        knots.extend(std::iter::repeat_n(parameter, insertion_count));
1353        knots.extend_from_slice(&self.knots[span + 1..]);
1354
1355        let mut output = vec![
1356            Vec4 {
1357                x: 0.0,
1358                y: 0.0,
1359                z: 0.0,
1360                w: 1.0,
1361            };
1362            last_control + 1 + insertion_count
1363        ];
1364        output[..=span - degree].copy_from_slice(&self.control_points[..=span - degree]);
1365        for index in span - multiplicity..=last_control {
1366            output[index + insertion_count] = self.control_points[index];
1367        }
1368        let mut affected = vec![
1369            Vec4 {
1370                x: 0.0,
1371                y: 0.0,
1372                z: 0.0,
1373                w: 1.0,
1374            };
1375            degree + 1
1376        ];
1377        affected[..=degree - multiplicity]
1378            .copy_from_slice(&self.control_points[span - degree..=span - multiplicity]);
1379        let mut left = 0;
1380        for insertion in 1..=insertion_count {
1381            left = span - degree + insertion;
1382            for index in 0..=degree - insertion - multiplicity {
1383                let denominator = self.knots[index + span + 1] - self.knots[left + index];
1384                let alpha = (parameter - self.knots[left + index]) / denominator;
1385                affected[index] = affected[index + 1]
1386                    .scale(alpha)
1387                    .add(affected[index].scale(1.0 - alpha));
1388            }
1389            output[left] = affected[0];
1390            output[span + insertion_count - insertion - multiplicity] =
1391                affected[degree - insertion - multiplicity];
1392        }
1393        for index in left + 1..span - multiplicity {
1394            output[index] = affected[index - left];
1395        }
1396        Self::new(degree, knots, output)
1397    }
1398
1399    pub fn split(&self, parameter: f64) -> Result<(Self, Self), String> {
1400        let (left, right) = self.split_raw(parameter)?;
1401        Ok((left.with_provenance_of(self), right.with_provenance_of(self)))
1402    }
1403
1404    fn split_raw(&self, parameter: f64) -> Result<(Self, Self), String> {
1405        let [start, end] = self.domain()?;
1406        if parameter <= start + KNOT_IDENTITY_TOL || parameter >= end - KNOT_IDENTITY_TOL {
1407            return Err(format!(
1408                "NurbsCurve.split: parameter {parameter} must be strictly inside domain [{start}, {end}]"
1409            ));
1410        }
1411        // Snap onto a coincident knot so multiplicity and span agree (see
1412        // insert_knot).
1413        let parameter = self
1414            .knots
1415            .iter()
1416            .copied()
1417            .find(|knot| (knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1418            .unwrap_or(parameter);
1419        let multiplicity = self
1420            .knots
1421            .iter()
1422            .filter(|knot| (**knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1423            .count();
1424        let refined = self.insert_knot(parameter, self.degree.saturating_sub(multiplicity))?;
1425        let first = refined
1426            .knots
1427            .iter()
1428            .position(|knot| (*knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1429            .ok_or_else(|| "NurbsCurve.split: inserted knot not found".to_string())?;
1430        let mut left_knots = refined.knots[..first + self.degree].to_vec();
1431        left_knots.push(parameter);
1432        let left_points = refined.control_points[..first].to_vec();
1433        let mut right_knots = vec![parameter; self.degree + 1];
1434        right_knots.extend_from_slice(&refined.knots[first + self.degree..]);
1435        let right_points = refined.control_points[first - 1..].to_vec();
1436        Ok((
1437            Self::new(self.degree, left_knots, left_points)?,
1438            Self::new(self.degree, right_knots, right_points)?,
1439        ))
1440    }
1441}
1442
1443pub fn make_line(start: Vec3, end: Vec3) -> Result<NurbsCurve, String> {
1444    NurbsCurve::new(
1445        1,
1446        vec![0.0, 0.0, 1.0, 1.0],
1447        vec![Vec4::from_point(start, 1.0), Vec4::from_point(end, 1.0)],
1448    )
1449}
1450
1451pub fn make_arc(
1452    center: Vec3,
1453    x_axis: Vec3,
1454    y_axis: Vec3,
1455    radius: f64,
1456    start_angle: f64,
1457    end_angle: f64,
1458) -> Result<NurbsCurve, String> {
1459    if radius <= EPS {
1460        return Err("makeArc: radius must be positive".into());
1461    }
1462    let x_axis = x_axis.normalized()?;
1463    let y_axis = y_axis.normalized()?;
1464    if x_axis.dot(y_axis).abs() > 1e-9 {
1465        return Err("makeArc: xAxis and yAxis must be orthogonal".into());
1466    }
1467    let mut theta = end_angle - start_angle;
1468    if theta <= EPS {
1469        return Err("makeArc: endAngle must exceed startAngle".into());
1470    }
1471    if theta > std::f64::consts::TAU + EPS {
1472        return Err("makeArc: sweep exceeds full circle".into());
1473    }
1474    theta = theta.min(std::f64::consts::TAU);
1475    let segment_count = ((theta / std::f64::consts::FRAC_PI_2 - EPS).ceil() as usize).clamp(1, 4);
1476    let segment_angle = theta / segment_count as f64;
1477    let middle_weight = (segment_angle / 2.0).cos();
1478    let point_at = |angle: f64| {
1479        center
1480            .add(x_axis.scale(radius * angle.cos()))
1481            .add(y_axis.scale(radius * angle.sin()))
1482    };
1483    let tangent_at = |angle: f64| x_axis.scale(-angle.sin()).add(y_axis.scale(angle.cos()));
1484
1485    let mut points = Vec::with_capacity(2 * segment_count + 1);
1486    let mut angle = start_angle;
1487    let mut first_point = point_at(angle);
1488    let mut first_tangent = tangent_at(angle);
1489    points.push(Vec4::from_point(first_point, 1.0));
1490    for _ in 0..segment_count {
1491        angle += segment_angle;
1492        let end_point = point_at(angle);
1493        let end_tangent = tangent_at(angle);
1494        let cross = first_tangent.cross(end_tangent);
1495        let denominator = cross.length_squared();
1496        if denominator <= EPS {
1497            return Err("makeArc: arc tangents are parallel".into());
1498        }
1499        let distance = end_point.sub(first_point).cross(end_tangent).dot(cross) / denominator;
1500        let middle = first_point.add(first_tangent.scale(distance));
1501        points.push(Vec4::from_point(middle, middle_weight));
1502        points.push(Vec4::from_point(end_point, 1.0));
1503        first_point = end_point;
1504        first_tangent = end_tangent;
1505    }
1506    let mut knots = vec![0.0, 0.0, 0.0];
1507    for index in 1..segment_count {
1508        let knot = index as f64 / segment_count as f64;
1509        knots.extend([knot, knot]);
1510    }
1511    knots.extend([1.0, 1.0, 1.0]);
1512    NurbsCurve::new(2, knots, points)
1513}
1514
1515pub fn make_circle(center: Vec3, normal: Vec3, radius: f64) -> Result<NurbsCurve, String> {
1516    let normal = normal.normalized()?;
1517    let x_axis = normal.perpendicular()?;
1518    let y_axis = normal.cross(x_axis).normalized()?;
1519    make_arc(center, x_axis, y_axis, radius, 0.0, std::f64::consts::TAU)
1520}
1521
1522/// Build the exactly orthonormal local frame shared by the conic
1523/// constructors.  The conic algebra below (implicit equation, tangent
1524/// intersection, shoulder weight) is only exact in an orthonormal frame, so
1525/// the in-plane hint is Gram-Schmidt-projected against the primary direction
1526/// instead of trusted verbatim: callers only owe us non-parallel vectors.
1527fn conic_frame(fn_name: &str, primary: Vec3, hint: Vec3) -> Result<(Vec3, Vec3), String> {
1528    let x_axis = primary
1529        .normalized()
1530        .map_err(|_| format!("{fn_name}: primary axis must be non-zero"))?;
1531    if hint.length() <= EPS {
1532        return Err(format!("{fn_name}: in-plane direction must be non-zero"));
1533    }
1534    hint.sub(x_axis.scale(hint.dot(x_axis)))
1535        .normalized()
1536        .map(|y_axis| (x_axis, y_axis))
1537        .map_err(|_| format!("{fn_name}: frame directions must not be parallel"))
1538}
1539
1540/// Trim-range validation shared by the conic constructors.  The knot span IS
1541/// the conic parameter range, so it must clear the knot identity band or the
1542/// resulting curve would fail knot validation with an unhelpful message.
1543fn conic_range(fn_name: &str, t0: f64, t1: f64) -> Result<(), String> {
1544    if !t0.is_finite() || !t1.is_finite() {
1545        return Err(format!("{fn_name}: parameter range must be finite"));
1546    }
1547    if t1 - t0 <= KNOT_IDENTITY_TOL {
1548        return Err(format!("{fn_name}: t1 ({t1}) must exceed t0 ({t0})"));
1549    }
1550    Ok(())
1551}
1552
1553/// Extreme trim parameters overflow the conic point formulas (cosh exceeds
1554/// f64 near |t| ~ 710, focal·t² near |t| ~ 1e150); surface that as the
1555/// constructor's own honest error instead of the generic NurbsCurve
1556/// finiteness rejection.
1557fn conic_points_finite(fn_name: &str, points: &[Vec4]) -> Result<(), String> {
1558    if points.iter().any(|point| {
1559        ![point.x, point.y, point.z, point.w]
1560            .iter()
1561            .all(|value| value.is_finite())
1562    }) {
1563        return Err(format!(
1564            "{fn_name}: control points overflow f64 — parameter range too extreme"
1565        ));
1566    }
1567    Ok(())
1568}
1569
1570/// Exact parabola segment y² = 4·focal·x in the local frame (vertex at the
1571/// origin, `axis` = +x, `latus_direction` = +y), parametrized the standard
1572/// way P(t) = (focal·t², 2·focal·t) and trimmed to t ∈ [t0, t1].  A parabola
1573/// segment is a plain quadratic polynomial in t (all weights 1), so a single
1574/// degree-2 Bézier over the knot span [t0, t1] reproduces both the point set
1575/// AND the parametrization exactly — no fitting, and evaluate(t) == P(t) for
1576/// every t, not just at the ends.
1577pub fn make_parabola(
1578    vertex: Vec3,
1579    axis: Vec3,
1580    latus_direction: Vec3,
1581    focal: f64,
1582    t0: f64,
1583    t1: f64,
1584) -> Result<NurbsCurve, String> {
1585    if !focal.is_finite() || focal <= EPS {
1586        return Err("make_parabola: focal distance must be positive".into());
1587    }
1588    conic_range("make_parabola", t0, t1)?;
1589    let (x_axis, y_axis) = conic_frame("make_parabola", axis, latus_direction)?;
1590    let point_at = |t: f64| {
1591        vertex
1592            .add(x_axis.scale(focal * t * t))
1593            .add(y_axis.scale(2.0 * focal * t))
1594    };
1595    // Bernstein middle point of the quadratic polynomial,
1596    // P(t0) + (t1−t0)/2·P'(t0), collapses to local (focal·t0·t1,
1597    // focal·(t0+t1)) — which is also the intersection of the two end
1598    // tangents, as it must be for any parabola segment.
1599    let middle = vertex
1600        .add(x_axis.scale(focal * t0 * t1))
1601        .add(y_axis.scale(focal * (t0 + t1)));
1602    let control_points = vec![
1603        Vec4::from_point(point_at(t0), 1.0),
1604        Vec4::from_point(middle, 1.0),
1605        Vec4::from_point(point_at(t1), 1.0),
1606    ];
1607    conic_points_finite("make_parabola", &control_points)?;
1608    NurbsCurve::new(2, vec![t0, t0, t0, t1, t1, t1], control_points)
1609}
1610
1611/// Exact arc of the hyperbola branch x²/a² − y²/b² = 1, x > 0 in the local
1612/// frame (center at the origin, `major_axis` = +x, `minor_axis` = +y),
1613/// parametrized P(t) = (a·cosh t, b·sinh t) and trimmed to t ∈ [t0, t1].
1614/// A single rational quadratic Bézier is exact for any sweep on one branch:
1615/// endpoints on the curve, middle control point at the intersection of the
1616/// end tangents, and middle weight cosh((t1−t0)/2) chosen so the shoulder
1617/// point lands back on the branch.  Only the point set is hyperbola-exact
1618/// away from the ends; the NURBS parameter coincides with the hyperbolic
1619/// parameter t exactly at t0, (t0+t1)/2 and t1.
1620pub fn make_hyperbola(
1621    center: Vec3,
1622    major_axis: Vec3,
1623    minor_axis: Vec3,
1624    a: f64,
1625    b: f64,
1626    t0: f64,
1627    t1: f64,
1628) -> Result<NurbsCurve, String> {
1629    if !a.is_finite() || a <= EPS {
1630        return Err("make_hyperbola: semi-axis a must be positive".into());
1631    }
1632    if !b.is_finite() || b <= EPS {
1633        return Err("make_hyperbola: semi-axis b must be positive".into());
1634    }
1635    conic_range("make_hyperbola", t0, t1)?;
1636    let (x_axis, y_axis) = conic_frame("make_hyperbola", major_axis, minor_axis)?;
1637    let point_at = |t: f64| {
1638        center
1639            .add(x_axis.scale(a * t.cosh()))
1640            .add(y_axis.scale(b * t.sinh()))
1641    };
1642    let mid = 0.5 * (t0 + t1);
1643    let middle_weight = (0.5 * (t1 - t0)).cosh();
1644    // In the scaled frame (x/a, y/b) the branch is the unit hyperbola and the
1645    // tangent at t is the line X·cosh t − Y·sinh t = 1; Cramer's rule on the
1646    // two end-tangent lines collapses their intersection to
1647    // P(mid)/cosh(half-sweep), so no explicit line-line solve is needed.
1648    // With this middle point, weight cosh(half-sweep) puts the shoulder point
1649    // (P0 + 2w·P1 + P2)/(2 + 2w) back on the branch at P(mid).
1650    let apex = center
1651        .add(x_axis.scale(a * mid.cosh() / middle_weight))
1652        .add(y_axis.scale(b * mid.sinh() / middle_weight));
1653    let control_points = vec![
1654        Vec4::from_point(point_at(t0), 1.0),
1655        Vec4::from_point(apex, middle_weight),
1656        Vec4::from_point(point_at(t1), 1.0),
1657    ];
1658    conic_points_finite("make_hyperbola", &control_points)?;
1659    NurbsCurve::new(2, vec![t0, t0, t0, t1, t1, t1], control_points)
1660}
1661
1662pub fn uniform_clamped_knots(
1663    control_point_count: usize,
1664    degree: usize,
1665) -> Result<Vec<f64>, String> {
1666    if control_point_count == 0 || control_point_count - 1 < degree {
1667        return Err("uniformClampedKnots: need at least degree+1 control points".into());
1668    }
1669    let n = control_point_count - 1;
1670    let mut knots = vec![0.0; degree + 1];
1671    let interior = n - degree;
1672    for index in 1..=interior {
1673        knots.push(index as f64 / (interior + 1) as f64);
1674    }
1675    knots.extend(std::iter::repeat_n(1.0, degree + 1));
1676    Ok(knots)
1677}
1678
1679fn binomial(n: usize, k: usize) -> f64 {
1680    if k > n {
1681        return 0.0;
1682    }
1683    let k = k.min(n - k);
1684    (1..=k).fold(1.0, |value, index| {
1685        value * (n - k + index) as f64 / index as f64
1686    })
1687}
1688
1689
1690
1691
1692/// SMALL CURVE DERIVATIVES (lane O row 21, 2026-10-29; on by default since
1693/// the batch 5 promotion, `BREP_CURVE_SMALL_DERIVATIVES=0` reads the heap): `NurbsCurve::derivatives`
1694/// up to second order is read from the stack twin
1695/// [`NurbsCurve::derivatives_small`] (one allocation for the result instead of
1696/// two), and the hot callers — point-in-face's nearest-curve refinement, the
1697/// imprint's parameter tolerance and its pierce tangents — read the twin
1698/// directly. Same arithmetic, same bits.
1699pub fn small_curve_derivatives_enabled() -> bool {
1700    switch!("BREP_CURVE_SMALL_DERIVATIVES", true)
1701}
1702
1703
1704
1705/// Piegl–Tiller A5.6 with caller-selected homogeneous arithmetic.
1706pub fn bezier_decompose_raw<T: Copy>(knots: &[f64], points: &[T], degree: usize, zero: T, blend: impl Fn(T, T, f64) -> T) -> Option<Vec<Vec<T>>> {
1707    let p = degree;
1708    let n = points.len();
1709    if p == 0 || n < p + 1 || knots.len() != n + p + 1 || knots.iter().any(|k| !k.is_finite()) || knots.windows(2).any(|w| w[1] < w[0]) {
1710        return None;
1711    }
1712    let (a, b) = (knots[0], knots[knots.len() - 1]);
1713    if !(b > a) || knots[..=p].iter().any(|k| *k != a) || knots[knots.len() - p - 1..].iter().any(|k| *k != b) {
1714        return None;
1715    }
1716    let m = knots.len() - 1;
1717    let (mut a, mut b) = (p, p + 1);
1718    let mut spans = Vec::with_capacity(n);
1719    let mut span: Vec<T> = points[..=p].to_vec();
1720    let mut alphas = vec![0.; p];
1721    while b < m {
1722        let first = b;
1723        while b < m && knots[b + 1] == knots[b] {
1724            b += 1;
1725        }
1726        let mult = b - first + 1;
1727        if b < m && mult > p {
1728            return None;
1729        }
1730        let mut next = vec![zero; p + 1];
1731        if mult < p {
1732            let numer = knots[b] - knots[a];
1733            for j in (mult + 1..=p).rev() {
1734                alphas[j - mult - 1] = numer / (knots[a + j] - knots[a]);
1735            }
1736            let r = p - mult;
1737            for j in 1..=r {
1738                let s = mult + j;
1739                for k in (s..=p).rev() {
1740                    let alpha = alphas[k - s];
1741                    span[k] = blend(span[k], span[k - 1], alpha);
1742                }
1743                if b < m {
1744                    next[r - j] = span[p];
1745                }
1746            }
1747        }
1748        spans.push(span);
1749        if b >= m {
1750            break;
1751        }
1752        for i in p - mult..=p {
1753            next[i] = points[b - p + i];
1754        }
1755        span = next;
1756        a = b;
1757        b += 1;
1758    }
1759    Some(spans)
1760}
1761
1762/// One raw Boehm insertion. Span selection and the denominator policy belong
1763/// to the caller, as does the interpolation expression's operand order.
1764pub fn boehm_insert_raw<T: Copy>(
1765    points: &[T], knots: &[f64], degree: usize, parameter: f64, span: usize,
1766    blend: impl Fn(T, T, f64, f64) -> T,
1767) -> (Vec<T>, Vec<f64>) {
1768    let mut out = Vec::with_capacity(points.len() + 1);
1769    out.extend_from_slice(&points[..=span - degree]);
1770    for i in span - degree + 1..=span {
1771        out.push(blend(points[i - 1], points[i], parameter - knots[i], knots[i + degree] - knots[i]));
1772    }
1773    out.extend_from_slice(&points[span..]);
1774    let mut fresh_knots = knots.to_vec();
1775    fresh_knots.insert(span + 1, parameter);
1776    (out, fresh_knots)
1777}
1778
1779
1780/// Heap basis for raw/unclamped knots or degrees beyond the stack specialization.
1781pub fn basis_functions_raw(knots: &[f64], degree: usize, span: usize, parameter: f64, guard: f64) -> Vec<f64> {
1782    let mut basis = vec![0.0; degree + 1];
1783    let mut left = vec![0.0; degree + 1];
1784    let mut right = vec![0.0; degree + 1];
1785    basis_functions_raw_into(knots, degree, span, parameter, guard, &mut basis, &mut left, &mut right);
1786    basis
1787}
1788
1789#[inline(always)]
1790pub fn basis_functions_raw_into(knots: &[f64], degree: usize, span: usize, parameter: f64,
1791    guard: f64, basis: &mut [f64], left: &mut [f64], right: &mut [f64]) {
1792        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
1793    basis[0] = 1.0;
1794    for j in 1..=degree {
1795        left[j] = parameter - knots[span + 1 - j];
1796        right[j] = knots[span + j] - parameter;
1797        let mut saved = 0.0;
1798        for r in 0..j {
1799            let denominator = right[r + 1] + left[j - r];
1800            let temporary = if denominator.abs() <= guard {
1801                0.0
1802            } else {
1803                basis[r] / denominator
1804            };
1805            basis[r] = saved + right[r + 1] * temporary;
1806            saved = left[j - r] * temporary;
1807        }
1808        basis[j] = saved;
1809    }
1810}