bevy_math/curve/iterable.rs
1//! Iterable curves, which sample in the form of an iterator in order to support `Vec`-like
2//! output whose length cannot be known statically.
3
4use super::Interval;
5
6#[cfg(feature = "alloc")]
7use {super::ConstantCurve, alloc::vec::Vec};
8
9/// A curve which provides samples in the form of [`Iterator`]s.
10///
11/// This is an abstraction that provides an interface for curves which look like `Curve<Vec<T>>`
12/// but side-stepping issues with allocation on sampling. This happens when the size of an output
13/// array cannot be known statically.
14pub trait IterableCurve<T> {
15 /// The interval over which this curve is parametrized.
16 fn domain(&self) -> Interval;
17
18 /// Sample a point on this curve at the parameter value `t`, producing an iterator over values.
19 /// This is the unchecked version of sampling, which should only be used if the sample time `t`
20 /// is already known to lie within the curve's domain.
21 ///
22 /// Values sampled from outside of a curve's domain are generally considered invalid; data which
23 /// is nonsensical or otherwise useless may be returned in such a circumstance, and extrapolation
24 /// beyond a curve's domain should not be relied upon.
25 fn sample_iter_unchecked(&self, t: f32) -> impl Iterator<Item = T>;
26
27 /// Sample this curve at a specified time `t`, producing an iterator over sampled values.
28 /// The parameter `t` is clamped to the domain of the curve.
29 fn sample_iter_clamped(&self, t: f32) -> impl Iterator<Item = T> {
30 let t_clamped = self.domain().clamp(t);
31 self.sample_iter_unchecked(t_clamped)
32 }
33
34 /// Sample this curve at a specified time `t`, producing an iterator over sampled values.
35 /// If the parameter `t` does not lie in the curve's domain, `None` is returned.
36 fn sample_iter(&self, t: f32) -> Option<impl Iterator<Item = T>> {
37 if self.domain().contains(t) {
38 Some(self.sample_iter_unchecked(t))
39 } else {
40 None
41 }
42 }
43}
44
45#[cfg(feature = "alloc")]
46impl<T> IterableCurve<T> for ConstantCurve<Vec<T>>
47where
48 T: Clone,
49{
50 fn domain(&self) -> Interval {
51 self.domain
52 }
53
54 fn sample_iter_unchecked(&self, _t: f32) -> impl Iterator<Item = T> {
55 self.value.iter().cloned()
56 }
57}