ferravex_play/
animation.rs

1//! Tracks, bounded playback/events, pose blending and reusable animation controllers.
2mod contact;
3pub use contact::*;
4mod graph;
5mod playback;
6mod pose;
7pub mod retarget;
8pub use graph::*;
9pub use playback::*;
10pub use pose::*;
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum AnimationError {
13    Empty,
14    InvalidKey,
15    UnorderedKeys,
16    InvalidTime,
17    InvalidClip,
18    InvalidPose,
19    InvalidWeight,
20    JointCount,
21    Capacity,
22}
23/// An authoring error with the zero-based position of the offending key/frame.
24///
25/// `index` is `None` only for empty input. For unordered keys it identifies the
26/// second key of the first non-increasing adjacent pair. Invalid keys take
27/// precedence over ordering errors, just as in [`Track::new`].
28///
29/// ```
30/// use ferravex_play::animation::{AnimationError, Keyframe, ScalarTrack};
31/// let keys = [Keyframe { time: 1.0, value: 2.0 }; 2];
32/// let diagnostic = ScalarTrack::validate_keys(&keys).unwrap_err();
33/// assert_eq!(diagnostic.error, AnimationError::UnorderedKeys);
34/// assert_eq!(diagnostic.index, Some(1));
35/// ```
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct AnimationDiagnostic {
38    /// The error category returned by the existing constructor.
39    pub error: AnimationError,
40    /// Offending key/frame index, or `None` for empty input.
41    pub index: Option<usize>,
42}
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum LoopMode {
45    Clamp,
46    Repeat,
47}
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum Interpolation {
50    Step,
51    Linear,
52}
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct Keyframe<T> {
55    pub time: f32,
56    pub value: T,
57}
58mod sealed {
59    pub trait Sample {}
60}
61pub trait Sample: sealed::Sample + Copy {
62    fn valid(self) -> bool;
63    fn blend(a: Self, b: Self, amount: f32) -> Self;
64}
65impl sealed::Sample for f32 {}
66impl Sample for f32 {
67    fn valid(self) -> bool {
68        self.is_finite()
69    }
70    fn blend(a: Self, b: Self, amount: f32) -> Self {
71        lerp(a, b, amount)
72    }
73}
74impl sealed::Sample for [f32; 3] {}
75impl Sample for [f32; 3] {
76    fn valid(self) -> bool {
77        self.into_iter().all(f32::is_finite)
78    }
79    fn blend(a: Self, b: Self, amount: f32) -> Self {
80        [
81            lerp(a[0], b[0], amount),
82            lerp(a[1], b[1], amount),
83            lerp(a[2], b[2], amount),
84        ]
85    }
86}
87impl sealed::Sample for [f32; 4] {}
88impl Sample for [f32; 4] {
89    fn valid(self) -> bool {
90        self.into_iter().all(f32::is_finite)
91            && self.into_iter().map(|v| f64::from(v).powi(2)).sum::<f64>() > 1e-20
92    }
93    fn blend(a: Self, b: Self, amount: f32) -> Self {
94        slerp(a, b, amount)
95    }
96}
97
98#[derive(Clone, Debug)]
99pub struct Track<T: Sample> {
100    keys: Vec<Keyframe<T>>,
101    interpolation: Interpolation,
102}
103impl<T: Sample> Track<T> {
104    pub fn new(
105        keys: Vec<Keyframe<T>>,
106        interpolation: Interpolation,
107    ) -> Result<Self, AnimationError> {
108        Self::validate_keys(&keys).map_err(|diagnostic| diagnostic.error)?;
109        Ok(Self {
110            keys,
111            interpolation,
112        })
113    }
114    /// Check borrowed authoring data without allocating, sorting or consuming it.
115    ///
116    /// Keys must have finite, nonnegative times and valid values. Scalar/vector
117    /// values must be finite; quaternion squared length (computed in `f64`)
118    /// must also exceed `1e-20`, as required by [`Sample::valid`]. Times must be strictly increasing:
119    /// duplicates and descending pairs return `UnorderedKeys` at the latter key.
120    /// The first invalid key is reported before checking ordering, preserving
121    /// [`Self::new`]'s error precedence. A single key at time zero is valid.
122    /// Work is O(keys.len()) with constant scratch space.
123    ///
124    /// ```
125    /// use ferravex_play::animation::{Interpolation, Keyframe, ScalarTrack};
126    /// let keys = [Keyframe { time: 0.0, value: 3.0 }];
127    /// ScalarTrack::validate_keys(&keys).unwrap();
128    /// let track = ScalarTrack::new(keys.to_vec(), Interpolation::Step).unwrap();
129    /// assert_eq!(track.keys(), &keys);
130    /// assert_eq!(track.interpolation(), Interpolation::Step);
131    /// ```
132    pub fn validate_keys(keys: &[Keyframe<T>]) -> Result<(), AnimationDiagnostic> {
133        if keys.is_empty() {
134            return Err(AnimationDiagnostic {
135                error: AnimationError::Empty,
136                index: None,
137            });
138        }
139        if let Some(index) = keys
140            .iter()
141            .position(|key| !key.time.is_finite() || key.time < 0.0 || !key.value.valid())
142        {
143            return Err(AnimationDiagnostic {
144                error: AnimationError::InvalidKey,
145                index: Some(index),
146            });
147        }
148        if let Some(index) = keys
149            .windows(2)
150            .position(|pair| pair[0].time >= pair[1].time)
151        {
152            return Err(AnimationDiagnostic {
153                error: AnimationError::UnorderedKeys,
154                index: Some(index + 1),
155            });
156        }
157        Ok(())
158    }
159    /// Borrow the original keys in authoring order, without normalizing values.
160    /// See [`Self::validate_keys`] for an inspection example.
161    pub fn keys(&self) -> &[Keyframe<T>] {
162        &self.keys
163    }
164    /// Inspect the interpolation selected at construction.
165    /// See [`Self::validate_keys`] for an example.
166    pub fn interpolation(&self) -> Interpolation {
167        self.interpolation
168    }
169    pub fn duration(&self) -> f32 {
170        self.keys.last().expect("nonempty track").time
171    }
172    pub fn sample(&self, time: f32, mode: LoopMode) -> Result<T, AnimationError> {
173        let time = playback_time(time, self.duration(), mode)?;
174        let upper = self.keys.partition_point(|key| key.time <= time);
175        if upper == 0 {
176            return Ok(T::blend(self.keys[0].value, self.keys[0].value, 0.0));
177        }
178        let a = &self.keys[upper - 1];
179        if upper == self.keys.len() || self.interpolation == Interpolation::Step {
180            return Ok(T::blend(a.value, a.value, 0.0));
181        }
182        let b = &self.keys[upper];
183        Ok(T::blend(
184            a.value,
185            b.value,
186            (time - a.time) / (b.time - a.time),
187        ))
188    }
189    /// Sample arbitrary times into a reusable output prefix without allocating.
190    ///
191    /// Returns the number written (`times.len()`); any remaining output elements
192    /// are untouched. Empty input succeeds without writes. A short output returns
193    /// `Capacity`, before checking for nonfinite times (`InvalidTime`). Either
194    /// error leaves the entire output unchanged. Negative and unsorted times are
195    /// supported and each result is identical to [`Self::sample`].
196    /// Work is O(times.len() * log(keys.len())) with constant scratch space.
197    ///
198    /// ```
199    /// use ferravex_play::animation::{Interpolation, Keyframe, LoopMode, ScalarTrack};
200    /// let track = ScalarTrack::new(vec![
201    ///     Keyframe { time: 0.0, value: 0.0 },
202    ///     Keyframe { time: 1.0, value: 4.0 },
203    /// ], Interpolation::Linear).unwrap();
204    /// let mut out = [-1.0; 4];
205    /// let count = track.sample_into(&[0.5, 1.0, -0.25], LoopMode::Repeat, &mut out).unwrap();
206    /// assert_eq!(&out[..count], &[2.0, 0.0, 3.0]);
207    /// assert_eq!(out[3], -1.0);
208    /// assert!(track.sample_into(&[0.0, f32::NAN], LoopMode::Clamp, &mut out).is_err());
209    /// assert_eq!(out, [2.0, 0.0, 3.0, -1.0]);
210    /// ```
211    pub fn sample_into(
212        &self,
213        times: &[f32],
214        mode: LoopMode,
215        out: &mut [T],
216    ) -> Result<usize, AnimationError> {
217        validate_sample_output(times, out.len())?;
218        for (&time, value) in times.iter().zip(out) {
219            *value = self.sample(time, mode)?;
220        }
221        Ok(times.len())
222    }
223}
224pub type ScalarTrack = Track<f32>;
225pub type Vec3Track = Track<[f32; 3]>;
226/// Quaternion order is [x, y, z, w]. Samples are normalized, including exact keys.
227pub type QuatTrack = Track<[f32; 4]>;
228
229#[derive(Clone, Copy, Debug, PartialEq)]
230pub struct SpriteFrame {
231    pub index: u32,
232    pub duration: f32,
233}
234#[derive(Clone, Debug)]
235pub struct SpriteClip {
236    frames: Vec<SpriteFrame>,
237    ends: Vec<f32>,
238    duration: f32,
239}
240impl SpriteClip {
241    pub fn new(frames: Vec<SpriteFrame>) -> Result<Self, AnimationError> {
242        let duration = Self::validate_frames(&frames).map_err(|diagnostic| diagnostic.error)?;
243        let mut end = 0.0;
244        let ends = frames
245            .iter()
246            .map(|frame| {
247                end += frame.duration;
248                end
249            })
250            .collect();
251        Ok(Self {
252            frames,
253            ends,
254            duration,
255        })
256    }
257    /// Check borrowed frames and return their accumulated duration, without
258    /// allocating or consuming the authoring data.
259    ///
260    /// Reports the first frame with a nonfinite/nonpositive duration or whose
261    /// addition overflows or fails to advance the accumulated `f32` end time.
262    /// All such cases have category `InvalidKey`; empty input has category
263    /// `Empty` and no index. Frame indices may repeat and need not be ordered.
264    /// Work is O(frames.len()) with constant scratch space.
265    ///
266    /// ```
267    /// use ferravex_play::animation::{SpriteClip, SpriteFrame};
268    /// let frames = [
269    ///     SpriteFrame { index: 7, duration: 0.25 },
270    ///     SpriteFrame { index: 2, duration: 0.75 },
271    /// ];
272    /// assert_eq!(SpriteClip::validate_frames(&frames), Ok(1.0));
273    /// let clip = SpriteClip::new(frames.to_vec()).unwrap();
274    /// assert_eq!(clip.frames(), &frames);
275    /// ```
276    pub fn validate_frames(frames: &[SpriteFrame]) -> Result<f32, AnimationDiagnostic> {
277        if frames.is_empty() {
278            return Err(AnimationDiagnostic {
279                error: AnimationError::Empty,
280                index: None,
281            });
282        }
283        let mut duration = 0.0_f32;
284        for (index, frame) in frames.iter().enumerate() {
285            if !frame.duration.is_finite() || frame.duration <= 0.0 {
286                return Err(AnimationDiagnostic {
287                    error: AnimationError::InvalidKey,
288                    index: Some(index),
289                });
290            }
291            let end = duration + frame.duration;
292            if !end.is_finite() || end <= duration {
293                return Err(AnimationDiagnostic {
294                    error: AnimationError::InvalidKey,
295                    index: Some(index),
296                });
297            }
298            duration = end;
299        }
300        Ok(duration)
301    }
302    /// Borrow the original frame indices and durations in playback order.
303    /// See [`Self::validate_frames`] for an inspection example.
304    pub fn frames(&self) -> &[SpriteFrame] {
305        &self.frames
306    }
307    pub fn duration(&self) -> f32 {
308        self.duration
309    }
310    pub fn frame(&self, time: f32, mode: LoopMode) -> Result<u32, AnimationError> {
311        let time = playback_time(time, self.duration, mode)?;
312        let index = self
313            .ends
314            .partition_point(|end| *end <= time)
315            .min(self.frames.len() - 1);
316        Ok(self.frames[index].index)
317    }
318    /// Sample sprite indices into a reusable output prefix without allocating.
319    ///
320    /// Returns `times.len()`, leaving the output tail untouched. Empty input
321    /// succeeds. A short output returns `Capacity` before nonfinite times are
322    /// checked (`InvalidTime`); either error leaves output unchanged. Times may
323    /// be negative or unsorted. Each result is identical to [`Self::frame`],
324    /// including exact frame/loop boundaries. Work is
325    /// O(times.len() * log(frames.len())) with constant scratch space.
326    ///
327    /// ```
328    /// use ferravex_play::animation::{LoopMode, SpriteClip, SpriteFrame};
329    /// let clip = SpriteClip::new(vec![
330    ///     SpriteFrame { index: 4, duration: 0.25 },
331    ///     SpriteFrame { index: 7, duration: 0.75 },
332    /// ]).unwrap();
333    /// let mut out = [99; 4];
334    /// assert_eq!(clip.sample_into(&[0.0, 0.25, 1.0], LoopMode::Repeat, &mut out), Ok(3));
335    /// assert_eq!(out, [4, 7, 4, 99]);
336    /// ```
337    pub fn sample_into(
338        &self,
339        times: &[f32],
340        mode: LoopMode,
341        out: &mut [u32],
342    ) -> Result<usize, AnimationError> {
343        validate_sample_output(times, out.len())?;
344        for (&time, value) in times.iter().zip(out) {
345            *value = self.frame(time, mode)?;
346        }
347        Ok(times.len())
348    }
349}
350fn validate_sample_output(times: &[f32], capacity: usize) -> Result<(), AnimationError> {
351    if times.len() > capacity {
352        return Err(AnimationError::Capacity);
353    }
354    if times.iter().any(|time| !time.is_finite()) {
355        return Err(AnimationError::InvalidTime);
356    }
357    Ok(())
358}
359fn playback_time(time: f32, duration: f32, mode: LoopMode) -> Result<f32, AnimationError> {
360    if !time.is_finite() {
361        return Err(AnimationError::InvalidTime);
362    }
363    Ok(if mode == LoopMode::Repeat && duration > 0.0 {
364        time.rem_euclid(duration)
365    } else {
366        time.clamp(0.0, duration)
367    })
368}
369fn lerp(a: f32, b: f32, amount: f32) -> f32 {
370    (f64::from(a) * (1.0 - f64::from(amount)) + f64::from(b) * f64::from(amount)) as f32
371}
372fn normalize(q: [f32; 4]) -> [f32; 4] {
373    let length = q
374        .into_iter()
375        .map(|v| f64::from(v).powi(2))
376        .sum::<f64>()
377        .sqrt();
378    q.map(|v| (f64::from(v) / length) as f32)
379}
380fn slerp(a: [f32; 4], b: [f32; 4], amount: f32) -> [f32; 4] {
381    let a = normalize(a);
382    let mut b = normalize(b);
383    let mut dot = a.iter().zip(b).map(|(a, b)| a * b).sum::<f32>();
384    if dot < 0.0 {
385        b = b.map(|v| -v);
386        dot = -dot;
387    }
388    dot = dot.clamp(-1.0, 1.0);
389    let (wa, wb) = if dot > 0.9995 {
390        (1.0 - amount, amount)
391    } else {
392        let angle = dot.acos();
393        (
394            ((1.0 - amount) * angle).sin() / angle.sin(),
395            (amount * angle).sin() / angle.sin(),
396        )
397    };
398    normalize(std::array::from_fn(|i| a[i] * wa + b[i] * wb))
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404    #[test]
405    fn vector_keys_clamp_interpolate_and_repeat() {
406        let track = Vec3Track::new(
407            vec![
408                Keyframe {
409                    time: 0.0,
410                    value: [0.0; 3],
411                },
412                Keyframe {
413                    time: 2.0,
414                    value: [2.0, 4.0, 6.0],
415                },
416            ],
417            Interpolation::Linear,
418        )
419        .unwrap();
420        assert_eq!(track.sample(1.0, LoopMode::Clamp).unwrap(), [1.0, 2.0, 3.0]);
421        assert_eq!(track.sample(-1.0, LoopMode::Clamp).unwrap(), [0.0; 3]);
422        assert_eq!(
423            track.sample(10.0, LoopMode::Clamp).unwrap(),
424            [2.0, 4.0, 6.0]
425        );
426        assert_eq!(
427            track.sample(3.0, LoopMode::Repeat).unwrap(),
428            [1.0, 2.0, 3.0]
429        );
430        assert_eq!(
431            track.sample(f32::NAN, LoopMode::Clamp),
432            Err(AnimationError::InvalidTime)
433        );
434    }
435    #[test]
436    fn quaternion_uses_shortest_arc_and_normalizes_keys() {
437        let track = QuatTrack::new(
438            vec![
439                Keyframe {
440                    time: 0.0,
441                    value: [0.0, 0.0, 0.0, 2.0],
442                },
443                Keyframe {
444                    time: 1.0,
445                    value: [0.0, 0.0, 0.0, -3.0],
446                },
447            ],
448            Interpolation::Linear,
449        )
450        .unwrap();
451        for time in [0.0, 0.5, 1.0] {
452            assert!((track.sample(time, LoopMode::Clamp).unwrap()[3].abs() - 1.0).abs() < 1e-6);
453        }
454        let half_turn = QuatTrack::new(
455            vec![
456                Keyframe {
457                    time: 0.0,
458                    value: [0.0, 0.0, 0.0, 1.0],
459                },
460                Keyframe {
461                    time: 1.0,
462                    value: [0.0, 0.0, 1.0, 0.0],
463                },
464            ],
465            Interpolation::Linear,
466        )
467        .unwrap();
468        let q = half_turn.sample(0.5, LoopMode::Clamp).unwrap();
469        assert!((q[2] - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-5);
470        assert!((q[3] - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-5);
471    }
472    #[test]
473    fn sprite_frames_use_individual_durations_and_exact_boundaries() {
474        let clip = SpriteClip::new(vec![
475            SpriteFrame {
476                index: 4,
477                duration: 0.25,
478            },
479            SpriteFrame {
480                index: 7,
481                duration: 0.75,
482            },
483        ])
484        .unwrap();
485        assert_eq!(clip.frame(0.24, LoopMode::Clamp).unwrap(), 4);
486        assert_eq!(clip.frame(0.25, LoopMode::Clamp).unwrap(), 7);
487        assert_eq!(clip.frame(1.0, LoopMode::Clamp).unwrap(), 7);
488        assert_eq!(clip.frame(1.0, LoopMode::Repeat).unwrap(), 4);
489    }
490    #[test]
491    fn malformed_keys_and_zero_quaternions_are_rejected() {
492        assert!(matches!(
493            QuatTrack::new(
494                vec![Keyframe {
495                    time: 0.0,
496                    value: [0.0; 4]
497                }],
498                Interpolation::Linear
499            ),
500            Err(AnimationError::InvalidKey)
501        ));
502        assert!(matches!(
503            ScalarTrack::new(
504                vec![
505                    Keyframe {
506                        time: 1.0,
507                        value: 1.0
508                    },
509                    Keyframe {
510                        time: 1.0,
511                        value: 2.0
512                    }
513                ],
514                Interpolation::Linear
515            ),
516            Err(AnimationError::UnorderedKeys)
517        ));
518        assert!(matches!(
519            SpriteClip::new(vec![SpriteFrame {
520                index: 0,
521                duration: 0.0
522            }]),
523            Err(AnimationError::InvalidKey)
524        ));
525    }
526
527    #[test]
528    fn authoring_diagnostics_locate_empty_duplicate_and_descending_keys() {
529        assert_eq!(
530            ScalarTrack::validate_keys(&[]),
531            Err(AnimationDiagnostic {
532                error: AnimationError::Empty,
533                index: None,
534            })
535        );
536        assert!(matches!(
537            ScalarTrack::new(vec![], Interpolation::Step),
538            Err(AnimationError::Empty)
539        ));
540        for times in [[0.0, 1.0, 1.0, 0.5], [0.0, 2.0, 1.0, 0.5]] {
541            let keys = times.map(|time| Keyframe { time, value: 4.0 });
542            let original = keys;
543            assert_eq!(
544                ScalarTrack::validate_keys(&keys),
545                Err(AnimationDiagnostic {
546                    error: AnimationError::UnorderedKeys,
547                    index: Some(2),
548                })
549            );
550            assert_eq!(keys, original);
551            assert!(matches!(
552                ScalarTrack::new(keys.to_vec(), Interpolation::Linear),
553                Err(AnimationError::UnorderedKeys)
554            ));
555        }
556        let zeros = [0.0, -0.0].map(|time| Keyframe { time, value: 4.0 });
557        assert_eq!(
558            ScalarTrack::validate_keys(&zeros).unwrap_err().index,
559            Some(1)
560        );
561        assert!(ScalarTrack::validate_keys(&zeros[..1]).is_ok());
562    }
563
564    #[test]
565    fn invalid_key_diagnostics_preserve_constructor_error_precedence() {
566        for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.5] {
567            let keys = [1.0, 0.0, invalid].map(|time| Keyframe { time, value: 4.0 });
568            assert_eq!(
569                ScalarTrack::validate_keys(&keys),
570                Err(AnimationDiagnostic {
571                    error: AnimationError::InvalidKey,
572                    index: Some(2),
573                })
574            );
575            assert!(matches!(
576                ScalarTrack::new(keys.to_vec(), Interpolation::Linear),
577                Err(AnimationError::InvalidKey)
578            ));
579        }
580        for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
581            let keys = [
582                Keyframe {
583                    time: 0.0,
584                    value: 2.0,
585                },
586                Keyframe {
587                    time: 1.0,
588                    value: invalid,
589                },
590                Keyframe {
591                    time: 2.0,
592                    value: invalid,
593                },
594            ];
595            assert_eq!(
596                ScalarTrack::validate_keys(&keys),
597                Err(AnimationDiagnostic {
598                    error: AnimationError::InvalidKey,
599                    index: Some(1),
600                })
601            );
602            let vectors = keys.map(|key| Keyframe {
603                time: key.time,
604                value: [key.value; 3],
605            });
606            assert_eq!(
607                Vec3Track::validate_keys(&vectors),
608                ScalarTrack::validate_keys(&keys)
609            );
610        }
611        for value in [[0.0; 4], [1e-12; 4], [f32::NAN; 4], [f32::INFINITY; 4]] {
612            assert_eq!(
613                QuatTrack::validate_keys(&[Keyframe { time: 0.0, value }]),
614                Err(AnimationDiagnostic {
615                    error: AnimationError::InvalidKey,
616                    index: Some(0),
617                })
618            );
619        }
620    }
621
622    #[test]
623    fn key_inspection_preserves_original_quaternions_and_interpolation() {
624        let keys = [Keyframe {
625            time: 0.0,
626            value: [0.0, 0.0, 0.0, 2.0],
627        }];
628        for interpolation in [Interpolation::Step, Interpolation::Linear] {
629            let track = QuatTrack::new(keys.to_vec(), interpolation).unwrap();
630            assert_eq!(track.keys(), keys);
631            assert_eq!(track.interpolation(), interpolation);
632            assert_eq!(track.duration(), 0.0);
633            assert_eq!(
634                track.sample(0.0, LoopMode::Repeat).unwrap(),
635                [0.0, 0.0, 0.0, 1.0]
636            );
637        }
638    }
639
640    #[test]
641    fn sprite_authoring_diagnostics_locate_invalid_and_unrepresentable_ends() {
642        assert_eq!(
643            SpriteClip::validate_frames(&[]),
644            Err(AnimationDiagnostic {
645                error: AnimationError::Empty,
646                index: None
647            })
648        );
649        assert!(matches!(
650            SpriteClip::new(vec![]),
651            Err(AnimationError::Empty)
652        ));
653        for durations in [
654            [0.25, 0.0],
655            [0.25, -1.0],
656            [0.25, f32::NAN],
657            [0.25, f32::INFINITY],
658            [0.25, f32::NEG_INFINITY],
659            [f32::MAX, f32::MAX],
660            [1.0, f32::MIN_POSITIVE],
661        ] {
662            let frames = durations.map(|duration| SpriteFrame { index: 3, duration });
663            assert_eq!(
664                SpriteClip::validate_frames(&frames),
665                Err(AnimationDiagnostic {
666                    error: AnimationError::InvalidKey,
667                    index: Some(1),
668                })
669            );
670            assert!(matches!(
671                SpriteClip::new(frames.to_vec()),
672                Err(AnimationError::InvalidKey)
673            ));
674        }
675        let frames = [
676            SpriteFrame {
677                index: 7,
678                duration: 0.25,
679            },
680            SpriteFrame {
681                index: 2,
682                duration: 0.5,
683            },
684            SpriteFrame {
685                index: 2,
686                duration: 0.25,
687            },
688        ];
689        let clip = SpriteClip::new(frames.to_vec()).unwrap();
690        assert_eq!(SpriteClip::validate_frames(&frames), Ok(clip.duration()));
691        assert_eq!(clip.frames(), frames);
692        let subnormal = [SpriteFrame {
693            index: u32::MAX,
694            duration: f32::from_bits(1),
695        }];
696        assert_eq!(
697            SpriteClip::validate_frames(&subnormal),
698            Ok(f32::from_bits(1))
699        );
700        assert!(SpriteClip::new(subnormal.to_vec()).is_ok());
701    }
702
703    fn check_batch_matches_samples<T: Sample + PartialEq + std::fmt::Debug>(
704        keys: Vec<Keyframe<T>>,
705    ) {
706        let sentinel = keys[0].value;
707        for interpolation in [Interpolation::Step, Interpolation::Linear] {
708            let track = Track::new(keys.clone(), interpolation).unwrap();
709            let times = [f32::MAX, 0.25, -1.0, 0.0, 1.0, 0.5, 0.75, -f32::MAX, 2.0];
710            let mut output = [sentinel; 11];
711            for mode in [LoopMode::Clamp, LoopMode::Repeat] {
712                assert_eq!(
713                    track.sample_into(&times, mode, &mut output),
714                    Ok(times.len())
715                );
716                for (&time, &value) in times.iter().zip(&output) {
717                    assert_eq!(value, track.sample(time, mode).unwrap());
718                    assert!(value.valid());
719                }
720                assert_eq!(&output[times.len()..], &[sentinel; 2]);
721                let previous = output;
722                assert_eq!(track.sample_into(&[], mode, &mut output), Ok(0));
723                assert_eq!(output, previous);
724                assert_eq!(track.sample_into(&[], mode, &mut []), Ok(0));
725                assert_eq!(
726                    track.sample_into(&times, mode, &mut output[..1]),
727                    Err(AnimationError::Capacity)
728                );
729                assert_eq!(output, previous);
730                assert_eq!(
731                    track.sample_into(&[f32::NAN], mode, &mut []),
732                    Err(AnimationError::Capacity)
733                );
734                for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
735                    for invalid_index in [0, 1, 2] {
736                        let mut times = [0.0, 0.5, 1.0];
737                        times[invalid_index] = invalid;
738                        assert_eq!(
739                            track.sample_into(&times, mode, &mut output),
740                            Err(AnimationError::InvalidTime)
741                        );
742                        assert_eq!(output, previous);
743                    }
744                }
745                assert_eq!(track.sample_into(&[0.5], mode, &mut output), Ok(1));
746                assert_eq!(output[0], track.sample(0.5, mode).unwrap());
747                assert_eq!(output[1..], previous[1..]);
748            }
749        }
750    }
751
752    #[test]
753    fn batch_tracks_preserve_sampling_and_reuse_output_for_all_value_types() {
754        check_batch_matches_samples(vec![
755            Keyframe {
756                time: 0.25,
757                value: -f32::MAX,
758            },
759            Keyframe {
760                time: 0.5,
761                value: 0.0,
762            },
763            Keyframe {
764                time: 1.0,
765                value: f32::MAX,
766            },
767        ]);
768        check_batch_matches_samples(vec![
769            Keyframe {
770                time: 0.0,
771                value: [0.0; 3],
772            },
773            Keyframe {
774                time: 1.0,
775                value: [2.0, 4.0, 6.0],
776            },
777        ]);
778        check_batch_matches_samples(vec![
779            Keyframe {
780                time: 0.0,
781                value: [0.0, 0.0, 0.0, 2.0],
782            },
783            Keyframe {
784                time: 1.0,
785                value: [0.0, 0.0, -3.0, 0.0],
786            },
787        ]);
788        check_batch_matches_samples(vec![Keyframe {
789            time: 0.0,
790            value: 7.0,
791        }]);
792        check_batch_matches_samples(vec![Keyframe {
793            time: 0.5,
794            value: [0.0, 0.0, 0.0, 2.0],
795        }]);
796    }
797
798    #[test]
799    fn batch_sprite_frames_preserve_boundaries_and_output_on_errors() {
800        let clip = SpriteClip::new(vec![
801            SpriteFrame {
802                index: 4,
803                duration: 0.25,
804            },
805            SpriteFrame {
806                index: 7,
807                duration: 0.75,
808            },
809        ])
810        .unwrap();
811        let times = [1.0, 0.0, 0.25, -0.25, f32::MAX, -f32::MAX];
812        let mut output = [99; 8];
813        for mode in [LoopMode::Repeat, LoopMode::Clamp] {
814            assert_eq!(clip.sample_into(&times, mode, &mut output), Ok(times.len()));
815            for (&time, &frame) in times.iter().zip(&output) {
816                assert_eq!(frame, clip.frame(time, mode).unwrap());
817            }
818            assert_eq!(
819                &output[..3],
820                if mode == LoopMode::Repeat {
821                    &[4, 4, 7]
822                } else {
823                    &[7, 4, 7]
824                }
825            );
826            assert_eq!(&output[times.len()..], &[99; 2]);
827            let previous = output;
828            assert_eq!(clip.sample_into(&[], mode, &mut output), Ok(0));
829            assert_eq!(output, previous);
830            assert_eq!(clip.sample_into(&[], mode, &mut []), Ok(0));
831            assert_eq!(
832                clip.sample_into(&times, mode, &mut output[..1]),
833                Err(AnimationError::Capacity)
834            );
835            assert_eq!(output, previous);
836            assert_eq!(
837                clip.sample_into(&[f32::NAN], mode, &mut []),
838                Err(AnimationError::Capacity)
839            );
840            for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
841                for invalid_index in [0, 1, 2] {
842                    let mut times = [0.0, 0.25, 1.0];
843                    times[invalid_index] = invalid;
844                    assert_eq!(
845                        clip.sample_into(&times, mode, &mut output),
846                        Err(AnimationError::InvalidTime)
847                    );
848                    assert_eq!(output, previous);
849                }
850            }
851            assert_eq!(clip.sample_into(&[0.25], mode, &mut output), Ok(1));
852            assert_eq!(output[0], 7);
853            assert_eq!(output[1..], previous[1..]);
854        }
855    }
856}