ferravex_math/
curves.rs

1//! Checked cubic Bezier authoring with allocation-free, bounded tessellation.
2//!
3//! [`CubicBezier3`] stores four finite f32 control points. Sampling uses f64
4//! intermediates; positions round to Vec3, while tangents retain f64 derivative
5//! components (not unit directions). A constant curve has zero tangent; a zero
6//! computed derivative at a cusp stays zero, without a fallback direction.
7//! Samples use ordinary floating-point arithmetic, not exact polynomial values.
8//!
9//! Tessellation emits an ordered **prefix**, beginning at control point zero.
10//! Only accepted chords are written. [`TessellationStatus::Complete`] certifies
11//! the whole curve; a limit leaves an incomplete prefix, never an unchecked
12//! coarse chord to the final endpoint. Reuse caller storage on the next call;
13//! there is no retained state, append mode, resume cursor, clock or reset.
14//!
15//! The error test uses outward-rounded f64 intervals for dyadic de Casteljau
16//! subdivision. It bounds the L1 norm of the difference between each subcurve's
17//! four control points and the degree-elevated control points of its **rounded
18//! output chord**. Convexity then bounds Euclidean distance at paired local
19//! parameters, in either direction, by that value. This includes subdivision
20//! arithmetic and f32 endpoint rounding. It is conservative: a curved or even
21//! collinear, nonuniformly parameterized curve can need extra subdivisions.
22//! Tiny tolerances can saturate because output quantization/interval width
23//! cannot be resolved. Tolerance is in control-point world units, not pixels,
24//! angle, arc length or error in route-progress parameterization.
25//!
26//! # Runnable native authoring recipe
27//!
28//! This uses only math. A route owner can pass `&points[..result.written]` to
29//! the existing `ferravex_play::navigation::Route3::set` **after** checking
30//! `Complete`; Route3 continues to own arc-length sampling and progression.
31//!
32//! ```rust
33//! use ferravex_math::{Vec3, vec3};
34//! use ferravex_math::curves::{
35//!     CubicBezier3, CurveError, TessellationOptions, TessellationStatus,
36//! };
37//!
38//! fn main() -> Result<(), CurveError> {
39//!     let curve = CubicBezier3::new([
40//!         Vec3::ZERO, vec3(0., 2., 0.), vec3(4., 2., 0.), vec3(4., 0., 0.),
41//!     ])?;
42//!     assert_eq!(curve.position(0.)?, curve.control_points()[0]);
43//!     assert_eq!(curve.position(1.)?, curve.control_points()[3]);
44//!     assert_eq!(curve.tangent(0.)?, [0., 6., 0.]);
45//!     let mut points = [Vec3::ZERO; 128];
46//!     let result = curve.tessellate_into(&mut points, TessellationOptions {
47//!         tolerance: 0.01, max_depth: 16, max_work: 1023,
48//!     })?;
49//!     assert_eq!(result.status, TessellationStatus::Complete);
50//!     assert_eq!(result.covered_until, 1.);
51//!     assert!(result.max_error_bound <= 0.01);
52//!     assert_eq!(points[result.written - 1], curve.position(1.)?);
53//!     Ok(())
54//! }
55//! ```
56
57use crate::Vec3;
58
59/// Largest permitted subdivision depth; bounds the internal DFS stack to 33
60/// nodes. The independently supplied work limit bounds the number examined.
61pub const MAX_TESSELLATION_DEPTH: u8 = 32;
62
63/// Invalid authoring input. Errors are distinct from successful partial output.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub enum CurveError {
67    /// All coordinates of all four control points must be finite.
68    NonFiniteControl,
69    /// Sampling requires a finite parameter in `0..=1`; it never clamps.
70    InvalidParameter,
71    /// Tolerance must be finite and strictly positive.
72    InvalidTolerance,
73    /// Depth must not exceed [`MAX_TESSELLATION_DEPTH`].
74    InvalidDepth,
75}
76
77impl std::fmt::Display for CurveError {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.write_str(match self {
80            Self::NonFiniteControl => "cubic control points must be finite",
81            Self::InvalidParameter => "cubic parameter must be finite and in 0..=1",
82            Self::InvalidTolerance => "cubic tolerance must be finite and positive",
83            Self::InvalidDepth => "cubic subdivision depth exceeds the fixed stack limit",
84        })
85    }
86}
87
88impl std::error::Error for CurveError {}
89
90/// Explicit geometric and resource budgets. See the module recipe.
91#[derive(Clone, Copy, Debug, PartialEq)]
92pub struct TessellationOptions {
93    /// Positive finite error tolerance in world units, including output rounding.
94    pub tolerance: f64,
95    /// Number of bisections along any branch, in `0..=MAX_TESSELLATION_DEPTH`.
96    /// Zero permits only testing the original curve's chord.
97    pub max_depth: u8,
98    /// Maximum nodes examined (one error test and at most one split per node).
99    /// Zero emits only the start if storage permits. Fixed validation and stack
100    /// initialization are constant overhead outside this node counter.
101    pub max_work: usize,
102}
103
104/// Why tessellation stopped. Limits return `Ok`, with only certified prefix
105/// chords. If multiple limits coincide, output capacity is checked before work;
106/// subdivision depth is checked only after a node fails its error test.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108#[non_exhaustive]
109pub enum TessellationStatus {
110    /// The prefix covers all of `0..=1`, including both original endpoints.
111    Complete,
112    /// Another endpoint could not fit; empty storage writes nothing.
113    OutputFull,
114    /// The next node would exceed the work budget.
115    WorkLimit,
116    /// A failed error test reached the requested depth. This may also reflect
117    /// f32 quantization or interval rounding, not just geometric curvature.
118    SubdivisionLimit,
119}
120
121/// Result of a valid tessellation request; see the module recipe.
122#[derive(Clone, Copy, Debug, PartialEq)]
123pub struct Tessellation {
124    /// Initialized output prefix length; the remaining slice is unchanged.
125    pub written: usize,
126    /// Number of nodes examined, at most `options.max_work`.
127    pub work: usize,
128    /// Number of actual bisections, at most `work`.
129    pub subdivisions: usize,
130    /// Deepest examined node, at most `options.max_depth`; zero if none.
131    pub depth_reached: u8,
132    /// End parameter of the last accepted chord; zero if none. No statement
133    /// about the unprocessed remainder is implied by a saturated result.
134    pub covered_until: f64,
135    /// Maximum certified Euclidean error bound of emitted chords, at most the
136    /// requested tolerance. Zero if no chord was emitted. See the module's
137    /// conservative L1 construction; this is not a measured worst deviation.
138    pub max_error_bound: f64,
139    /// Completion or the first limiting resource.
140    pub status: TessellationStatus,
141}
142
143/// One cubic Bezier in three dimensions, with checked finite control points.
144/// Construction and all operations use fixed storage and allocate nothing.
145/// See the module's executable recipe for every operation.
146#[derive(Clone, Copy, Debug, PartialEq)]
147pub struct CubicBezier3 {
148    control_points: [Vec3; 4],
149}
150
151impl CubicBezier3 {
152    /// Checks all four points, including for constant/degenerate curves.
153    pub fn new(control_points: [Vec3; 4]) -> Result<Self, CurveError> {
154        if control_points.iter().any(|point| !point.is_finite()) {
155            return Err(CurveError::NonFiniteControl);
156        }
157        Ok(Self { control_points })
158    }
159
160    /// Original ordered points, suitable for editing and checked reconstruction.
161    pub fn control_points(&self) -> [Vec3; 4] {
162        self.control_points
163    }
164
165    /// Samples a finite parameter in `0..=1`, using f64 de Casteljau
166    /// interpolation before rounding to Vec3. Endpoints preserve their original
167    /// bits, including signed zeros. No extrapolation or clamping occurs.
168    pub fn position(&self, parameter: f64) -> Result<Vec3, CurveError> {
169        check_parameter(parameter)?;
170        if parameter == 0. {
171            return Ok(self.control_points[0]);
172        }
173        if parameter == 1. {
174            return Ok(self.control_points[3]);
175        }
176        let mut points = self.control_points.map(|p| p.to_array().map(f64::from));
177        for count in (1..4).rev() {
178            for i in 0..count {
179                points[i] = lerp(points[i], points[i + 1], parameter);
180            }
181        }
182        Ok(Vec3::from_array(points[0].map(|x| x as f32)))
183    }
184
185    /// Unnormalized derivative of the authored polynomial, before position
186    /// rounding, as finite f64 components. Extreme f32 controls cannot overflow
187    /// the tangent. Exact computed zero at a cusp/constant curve remains zero;
188    /// small derivatives are not discarded by an epsilon. There is no
189    /// unit-tangent fallback.
190    pub fn tangent(&self, parameter: f64) -> Result<[f64; 3], CurveError> {
191        check_parameter(parameter)?;
192        let points = self.control_points.map(|p| p.to_array().map(f64::from));
193        let derivative: [[f64; 3]; 3] = std::array::from_fn(|i| {
194            std::array::from_fn(|axis| 3. * (points[i + 1][axis] - points[i][axis]))
195        });
196        if parameter == 0. {
197            return Ok(derivative[0]);
198        }
199        if parameter == 1. {
200            return Ok(derivative[2]);
201        }
202        Ok(lerp(
203            lerp(derivative[0], derivative[1], parameter),
204            lerp(derivative[1], derivative[2], parameter),
205            parameter,
206        ))
207    }
208
209    /// Adaptively bisects left-first into caller storage. Invalid options leave
210    /// the entire output unchanged. Valid requests overwrite only the reported
211    /// prefix, including on saturation. A constant curve emits two equal points
212    /// on completion, preserving both endpoint parameters.
213    ///
214    /// Only `Complete` is a whole-curve tolerance certificate. A partial result
215    /// is safe to inspect, but callers must explicitly choose whether to use
216    /// that shorter path. Increasing a budget starts a fresh run. Stack storage
217    /// is fixed (33 nodes); work and output never grow implicitly. See the
218    /// module recipe and the bound described in the module documentation.
219    pub fn tessellate_into(
220        &self,
221        output: &mut [Vec3],
222        options: TessellationOptions,
223    ) -> Result<Tessellation, CurveError> {
224        if !options.tolerance.is_finite() || options.tolerance <= 0. {
225            return Err(CurveError::InvalidTolerance);
226        }
227        if options.max_depth > MAX_TESSELLATION_DEPTH {
228            return Err(CurveError::InvalidDepth);
229        }
230        let mut result = Tessellation {
231            written: 0,
232            work: 0,
233            subdivisions: 0,
234            depth_reached: 0,
235            covered_until: 0.,
236            max_error_bound: 0.,
237            status: TessellationStatus::Complete,
238        };
239        if output.is_empty() {
240            result.status = TessellationStatus::OutputFull;
241            return Ok(result);
242        }
243        output[0] = self.control_points[0];
244        result.written = 1;
245        let root = Node {
246            points: self
247                .control_points
248                .map(|p| p.to_array().map(|x| Interval::exact(f64::from(x)))),
249            start: 0.,
250            end: 1.,
251            depth: 0,
252        };
253        let mut stack = [root; MAX_TESSELLATION_DEPTH as usize + 1];
254        let mut pending = 1;
255        while pending > 0 {
256            if result.written == output.len() {
257                result.status = TessellationStatus::OutputFull;
258                break;
259            }
260            if result.work == options.max_work {
261                result.status = TessellationStatus::WorkLimit;
262                break;
263            }
264            pending -= 1;
265            let node = stack[pending];
266            result.work += 1;
267            result.depth_reached = result.depth_reached.max(node.depth);
268            let end = if node.end == 1. {
269                self.control_points[3]
270            } else {
271                Vec3::from_array(node.points[3].map(|x| (x.low * 0.5 + x.high * 0.5) as f32))
272            };
273            let error = node.error_bound(output[result.written - 1], end);
274            if error <= options.tolerance {
275                output[result.written] = end;
276                result.written += 1;
277                result.covered_until = node.end;
278                result.max_error_bound = result.max_error_bound.max(error);
279            } else if node.depth == options.max_depth {
280                result.status = TessellationStatus::SubdivisionLimit;
281                break;
282            } else {
283                let (left, right) = node.split();
284                stack[pending] = right;
285                stack[pending + 1] = left;
286                pending += 2;
287                result.subdivisions += 1;
288            }
289        }
290        Ok(result)
291    }
292}
293
294fn check_parameter(parameter: f64) -> Result<(), CurveError> {
295    if !parameter.is_finite() || !(0. ..=1.).contains(&parameter) {
296        Err(CurveError::InvalidParameter)
297    } else {
298        Ok(())
299    }
300}
301
302fn lerp(a: [f64; 3], b: [f64; 3], t: f64) -> [f64; 3] {
303    std::array::from_fn(|axis| (1. - t) * a[axis] + t * b[axis])
304}
305
306// All interval operands originate as finite f32, with at most 32 bisections.
307// Outward steps can introduce f64 subnormals around zero; each operation is
308// enclosed separately, including division/multiplication that might underflow.
309#[derive(Clone, Copy, Debug, PartialEq)]
310struct Interval {
311    low: f64,
312    high: f64,
313}
314
315impl Interval {
316    fn exact(value: f64) -> Self {
317        Self {
318            low: value,
319            high: value,
320        }
321    }
322
323    fn midpoint(self, other: Self) -> Self {
324        if self == other {
325            return self;
326        }
327        Self {
328            low: ((self.low + other.low).next_down() * 0.5).next_down(),
329            high: ((self.high + other.high).next_up() * 0.5).next_up(),
330        }
331    }
332
333    // Exact line control point (2*a + b)/3 enclosed without assuming that 1/3
334    // is representable. The equal-endpoint shortcut is exact, not an epsilon.
335    fn third(a: f64, b: f64) -> Self {
336        if a == b {
337            return Self::exact(a);
338        }
339        Self {
340            low: (((a * 2.).next_down() + b).next_down() / 3.).next_down(),
341            high: (((a * 2.).next_up() + b).next_up() / 3.).next_up(),
342        }
343    }
344
345    fn difference_bound(self, other: Self) -> f64 {
346        if self.low == self.high && self == other {
347            return 0.;
348        }
349        (self.low - other.high)
350            .next_down()
351            .abs()
352            .max((self.high - other.low).next_up().abs())
353    }
354}
355
356#[derive(Clone, Copy)]
357struct Node {
358    points: [[Interval; 3]; 4],
359    start: f64,
360    end: f64,
361    depth: u8,
362}
363
364impl Node {
365    fn error_bound(self, start: Vec3, end: Vec3) -> f64 {
366        let start = start.to_array().map(f64::from);
367        let end = end.to_array().map(f64::from);
368        let mut bound = 0_f64;
369        for i in 0..4 {
370            let mut sum = 0_f64;
371            for axis in 0..3 {
372                let line = match i {
373                    0 => Interval::exact(start[axis]),
374                    1 => Interval::third(start[axis], end[axis]),
375                    2 => Interval::third(end[axis], start[axis]),
376                    _ => Interval::exact(end[axis]),
377                };
378                let difference = self.points[i][axis].difference_bound(line);
379                if difference > 0. {
380                    sum = (sum + difference).next_up();
381                }
382            }
383            bound = bound.max(sum);
384        }
385        bound
386    }
387
388    fn split(self) -> (Self, Self) {
389        let mid = |a: [Interval; 3], b: [Interval; 3]| {
390            std::array::from_fn(|axis| a[axis].midpoint(b[axis]))
391        };
392        let [a, b, c, d] = self.points;
393        let (ab, bc, cd) = (mid(a, b), mid(b, c), mid(c, d));
394        let (abc, bcd) = (mid(ab, bc), mid(bc, cd));
395        let center = mid(abc, bcd);
396        let parameter = (self.start + self.end) * 0.5;
397        (
398            Self {
399                points: [a, ab, abc, center],
400                end: parameter,
401                depth: self.depth + 1,
402                ..self
403            },
404            Self {
405                points: [center, bcd, cd, d],
406                start: parameter,
407                depth: self.depth + 1,
408                ..self
409            },
410        )
411    }
412}