ferravex_play/animation/
playback.rs

1use super::{AnimationError, LoopMode, SpriteClip};
2
3pub const MAX_CLIP_SECONDS: f32 = 3600.;
4pub const MAX_ANIMATION_EVENTS: usize = 256;
5/// Large host stalls must be split explicitly; each update does bounded event work.
6pub const MAX_ANIMATION_DT: f32 = 60.;
7
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct AnimationEvent {
10    /// Seconds in [0, duration], including the end of a one-shot clip.
11    pub time: f32,
12    pub id: u32,
13}
14#[derive(Clone, Debug)]
15pub struct EventTrack {
16    duration: f32,
17    events: Vec<AnimationEvent>,
18}
19impl EventTrack {
20    pub fn new(duration: f32, events: Vec<AnimationEvent>) -> Result<Self, AnimationError> {
21        valid_duration(duration)?;
22        if events.len() > MAX_ANIMATION_EVENTS {
23            return Err(AnimationError::Capacity);
24        }
25        if events
26            .iter()
27            .any(|e| !e.time.is_finite() || e.time < 0. || e.time > duration)
28            || events.windows(2).any(|p| p[0].time > p[1].time)
29        {
30            return Err(AnimationError::InvalidKey);
31        }
32        Ok(Self { duration, events })
33    }
34    pub fn duration(&self) -> f32 {
35        self.duration
36    }
37    pub fn events(&self) -> &[AnimationEvent] {
38        &self.events
39    }
40}
41#[derive(Clone, Copy, Debug, Default, PartialEq)]
42pub struct EventHit {
43    pub id: u32,
44    pub time: f32,
45    /// Stable index into an AnimationBank, or zero for a standalone timeline.
46    pub clip: u16,
47    pub cycle: u64,
48}
49/// Per-update catch-up diagnostics from [`EventBuffer::report`]. Counts describe
50/// event crossings, including repeated IDs and keys with identical timestamps.
51/// Dropped crossings are consumed: they are never replayed on a later update.
52#[derive(Clone, Copy, Debug, Default, PartialEq)]
53pub struct EventCatchUpReport {
54    /// Earliest crossings retained in the output buffer.
55    pub emitted: usize,
56    /// Later crossings omitted because the buffer was full.
57    pub dropped: u64,
58    /// Repeat seams crossed, even when the event track is empty. Clamp is zero.
59    pub crossed_cycles: u64,
60    /// Event-bearing cycles with no retained crossing in this update. A cycle
61    /// with some retained and some dropped hits is not counted; `dropped` still
62    /// includes its missing hits. Empty cycles are never counted.
63    pub skipped_event_cycles: u64,
64    /// Earliest omitted crossing, including its clip and saturating cycle ID.
65    pub first_dropped: Option<EventHit>,
66    /// The timeline's cycle counter has reached `u64::MAX`. Cycle labels can no
67    /// longer distinguish subsequent loops; the per-update counts remain exact.
68    pub cycle_saturated: bool,
69}
70/// Fixed caller-owned event queue. Overflow drops the latest events, reports the
71/// exact number dropped, and never prevents the clock/pose from advancing.
72#[derive(Clone, Debug)]
73pub struct EventBuffer<const N: usize = 64> {
74    hits: [EventHit; N],
75    len: usize,
76    report: EventCatchUpReport,
77}
78impl<const N: usize> Default for EventBuffer<N> {
79    fn default() -> Self {
80        Self {
81            hits: [EventHit::default(); N],
82            len: 0,
83            report: EventCatchUpReport::default(),
84        }
85    }
86}
87impl<const N: usize> EventBuffer<N> {
88    pub fn hits(&self) -> &[EventHit] {
89        &self.hits[..self.len]
90    }
91    pub fn dropped(&self) -> u64 {
92        self.report.dropped
93    }
94    /// Returns diagnostics for the latest successful event update. Paused,
95    /// zero-speed, zero-dt and finished updates replace the previous report with
96    /// zero counts; invalid updates preserve both hits and report. [`Self::clear`]
97    /// resets it. Sprite, skeletal and graph players populate the same report.
98    /// Iterating [`Self::hits`] visits at most `N` retained crossings.
99    ///
100    /// ```
101    /// use ferravex_play::animation::{
102    ///     AnimationEvent, EventBuffer, EventCatchUpReport, EventTrack, LoopMode, Timeline,
103    /// };
104    /// let track = EventTrack::new(1.0, vec![AnimationEvent { time: 0.5, id: 7 }])?;
105    /// let mut clock = Timeline::new(1.0, LoopMode::Repeat)?;
106    /// let mut output = EventBuffer::<2>::default();
107    /// clock.advance_events(4.0, &track, &mut output)?;
108    /// let report: EventCatchUpReport = output.report();
109    /// assert_eq!((report.emitted, report.dropped), (2, 2));
110    /// assert_eq!(report.crossed_cycles, 4);
111    /// assert_eq!(report.skipped_event_cycles, 2);
112    /// assert_eq!(report.first_dropped.unwrap().cycle, 2);
113    /// assert!(!report.cycle_saturated);
114    /// assert_eq!(output.dropped(), report.dropped);
115    /// assert_eq!(output.hits().iter().map(|hit| hit.id).sum::<u32>(), 14);
116    /// // Overflow does not defer events or prevent clock progression.
117    /// clock.advance_events(0.25, &track, &mut output)?;
118    /// assert_eq!(output.report(), EventCatchUpReport::default());
119    /// # Ok::<(), ferravex_play::animation::AnimationError>(())
120    /// ```
121    pub fn report(&self) -> EventCatchUpReport {
122        self.report
123    }
124    pub fn clear(&mut self) {
125        self.len = 0;
126        self.report = EventCatchUpReport::default();
127    }
128    fn push(&mut self, event: AnimationEvent, clip: u16, cycle: u64) {
129        self.hits[self.len] = EventHit {
130            id: event.id,
131            time: event.time,
132            clip,
133            cycle,
134        };
135        self.len += 1;
136    }
137}
138fn valid_duration(duration: f32) -> Result<(), AnimationError> {
139    if !duration.is_finite() || !(0.0001..=MAX_CLIP_SECONDS).contains(&duration) {
140        Err(AnimationError::InvalidClip)
141    } else {
142        Ok(())
143    }
144}
145/// Forward playback at 0..=8x, with f64 phase accumulation and saturating loop
146/// counts. Pausing, zero speed and zero dt preserve pending start events. Seeking
147/// is silent. Resuming never re-emits an already crossed event.
148#[derive(Clone, Debug)]
149pub struct Timeline {
150    duration: f32,
151    mode: LoopMode,
152    phase: f64,
153    cycles: u64,
154    speed: f32,
155    paused: bool,
156    start: bool,
157}
158impl Timeline {
159    pub fn new(duration: f32, mode: LoopMode) -> Result<Self, AnimationError> {
160        valid_duration(duration)?;
161        Ok(Self {
162            duration,
163            mode,
164            phase: 0.,
165            cycles: 0,
166            speed: 1.,
167            paused: false,
168            start: true,
169        })
170    }
171    pub fn time(&self) -> f32 {
172        self.phase as f32
173    }
174    pub fn normalized_time(&self) -> f32 {
175        (self.phase / f64::from(self.duration)) as f32
176    }
177    pub fn cycles(&self) -> u64 {
178        self.cycles
179    }
180    pub fn speed(&self) -> f32 {
181        self.speed
182    }
183    pub fn paused(&self) -> bool {
184        self.paused
185    }
186    pub fn finished(&self) -> bool {
187        self.mode == LoopMode::Clamp && self.phase >= f64::from(self.duration)
188    }
189    pub fn set_paused(&mut self, paused: bool) {
190        self.paused = paused;
191    }
192    pub fn set_speed(&mut self, speed: f32) -> Result<(), AnimationError> {
193        if !speed.is_finite() || !(0.0..=8.).contains(&speed) {
194            return Err(AnimationError::InvalidTime);
195        }
196        self.speed = speed;
197        Ok(())
198    }
199    pub fn seek(&mut self, time: f32) -> Result<(), AnimationError> {
200        if !time.is_finite() || time < 0. {
201            return Err(AnimationError::InvalidTime);
202        }
203        self.phase = if self.mode == LoopMode::Repeat {
204            f64::from(time) % f64::from(self.duration)
205        } else {
206            f64::from(time.min(self.duration))
207        };
208        self.cycles = 0;
209        self.start = false;
210        Ok(())
211    }
212    pub fn restart(&mut self) {
213        self.phase = 0.;
214        self.cycles = 0;
215        self.start = true;
216    }
217    fn end(&self, dt: f32) -> Result<f64, AnimationError> {
218        if !dt.is_finite() || !(0.0..=MAX_ANIMATION_DT).contains(&dt) {
219            return Err(AnimationError::InvalidTime);
220        }
221        let delta = if self.paused {
222            0.
223        } else {
224            f64::from(dt) * f64::from(self.speed)
225        };
226        let end = self.phase + delta;
227        Ok(if self.mode == LoopMode::Clamp {
228            end.min(f64::from(self.duration))
229        } else {
230            end
231        })
232    }
233    fn commit(&mut self, end: f64) {
234        if end > self.phase {
235            self.start = false;
236        }
237        let (cycles, phase) = self.position(end);
238        self.cycles = self.cycles.saturating_add(cycles);
239        self.phase = phase;
240    }
241    fn position(&self, end: f64) -> (u64, f64) {
242        if self.mode == LoopMode::Repeat {
243            let duration = f64::from(self.duration);
244            ((end / duration).floor() as u64, end % duration)
245        } else {
246            (0, end)
247        }
248    }
249    pub fn advance(&mut self, dt: f32) -> Result<(), AnimationError> {
250        let end = self.end(dt)?;
251        self.commit(end);
252        Ok(())
253    }
254    /// Clears output on success, emits chronological events in (old,new], plus
255    /// initial time-zero events. Repeat seams emit the old cycle's end before
256    /// the new cycle's start; equal-time keys retain authored order. Work is
257    /// O(log(event count) + output capacity), even if millions of loops were
258    /// crossed, without allocating. [`EventBuffer::report`] describes overflow
259    /// and skipped event-bearing cycles. Invalid input leaves clock/queue intact.
260    pub fn advance_events<const N: usize>(
261        &mut self,
262        dt: f32,
263        events: &EventTrack,
264        out: &mut EventBuffer<N>,
265    ) -> Result<(), AnimationError> {
266        self.advance_tagged(dt, events, 0, out)
267    }
268    pub(super) fn advance_tagged<const N: usize>(
269        &mut self,
270        dt: f32,
271        events: &EventTrack,
272        clip: u16,
273        out: &mut EventBuffer<N>,
274    ) -> Result<(), AnimationError> {
275        if events.duration != self.duration {
276            return Err(AnimationError::InvalidClip);
277        }
278        let end = self.end(dt)?;
279        out.clear();
280        let (crossed_cycles, phase) = self.position(end);
281        out.report.crossed_cycles = crossed_cycles;
282        out.report.cycle_saturated = self.cycles.saturating_add(crossed_cycles) == u64::MAX;
283        if end <= self.phase {
284            return Ok(());
285        }
286        let mut index = events.events.partition_point(|e| {
287            f64::from(e.time) < self.phase || (!self.start && f64::from(e.time) == self.phase)
288        });
289        let end_index = events
290            .events
291            .partition_point(|e| f64::from(e.time) <= phase);
292        let event_count = events.events.len();
293        // Count the initial tail, whole middle cycles and final prefix. Compare
294        // local phases directly: (end - event.time) / duration can round tiny
295        // positive keys onto the preceding seam and deliver them twice.
296        let total = if crossed_cycles == 0 {
297            (end_index - index) as u64
298        } else {
299            (event_count - index) as u64
300                + (crossed_cycles - 1) * event_count as u64
301                + end_index as u64
302        };
303        let first_event_cycle = u64::from(index == event_count);
304        let mut cycle = 0_u64;
305        for _ in 0..total.min(N as u64) {
306            if index == event_count {
307                index = 0;
308                cycle += 1;
309            }
310            out.push(
311                events.events[index],
312                clip,
313                self.cycles.saturating_add(cycle),
314            );
315            index += 1;
316        }
317        out.report.emitted = out.len;
318        out.report.dropped = total - out.len as u64;
319        if total > 0 {
320            let last_event_cycle = if end_index > 0 {
321                crossed_cycles
322            } else {
323                crossed_cycles.saturating_sub(1)
324            };
325            let emitted_cycles = if out.len == 0 {
326                0
327            } else {
328                cycle - first_event_cycle + 1
329            };
330            out.report.skipped_event_cycles =
331                last_event_cycle - first_event_cycle + 1 - emitted_cycles;
332        }
333        if out.report.dropped > 0 {
334            if index == event_count {
335                index = 0;
336                cycle += 1;
337            }
338            let event = events.events[index];
339            out.report.first_dropped = Some(EventHit {
340                id: event.id,
341                time: event.time,
342                clip,
343                cycle: self.cycles.saturating_add(cycle),
344            });
345        }
346        self.commit(end);
347        Ok(())
348    }
349}
350
351/// Uses the same clock, pause/speed/seek semantics and bounded events as skeletal
352/// animation. Frame IDs are authored drawing/atlas IDs; no texture API is required.
353#[derive(Clone, Debug)]
354pub struct SpritePlayer {
355    clip: SpriteClip,
356    events: EventTrack,
357    clock: Timeline,
358}
359impl SpritePlayer {
360    pub fn new(
361        clip: SpriteClip,
362        mode: LoopMode,
363        events: Vec<AnimationEvent>,
364    ) -> Result<Self, AnimationError> {
365        let clock = Timeline::new(clip.duration(), mode)?;
366        let events = EventTrack::new(clip.duration(), events)?;
367        Ok(Self {
368            clip,
369            events,
370            clock,
371        })
372    }
373    pub fn frame(&self) -> u32 {
374        self.clip
375            .frame(self.clock.time(), LoopMode::Clamp)
376            .expect("validated sprite clock")
377    }
378    pub fn timeline(&self) -> &Timeline {
379        &self.clock
380    }
381    pub fn timeline_mut(&mut self) -> &mut Timeline {
382        &mut self.clock
383    }
384    pub fn advance<const N: usize>(
385        &mut self,
386        dt: f32,
387        out: &mut EventBuffer<N>,
388    ) -> Result<(), AnimationError> {
389        self.clock.advance_events(dt, &self.events, out)
390    }
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    fn event(time: f32, id: u32) -> AnimationEvent {
398        AnimationEvent { time, id }
399    }
400
401    #[test]
402    fn tiny_positive_key_is_not_rounded_onto_the_previous_seam() {
403        let tiny = f32::MIN_POSITIVE;
404        let events = EventTrack::new(1., vec![event(0., 0), event(tiny, 1), event(1., 2)]).unwrap();
405        let mut clock = Timeline::new(1., LoopMode::Repeat).unwrap();
406        let mut out = EventBuffer::<8>::default();
407        clock.advance_events(1., &events, &mut out).unwrap();
408        assert_eq!(
409            out.hits()
410                .iter()
411                .map(|hit| (hit.id, hit.cycle))
412                .collect::<Vec<_>>(),
413            [(0, 0), (1, 0), (2, 0), (0, 1)]
414        );
415        clock.advance_events(tiny, &events, &mut out).unwrap();
416        assert_eq!(
417            out.hits(),
418            &[EventHit {
419                id: 1,
420                time: tiny,
421                clip: 0,
422                cycle: 1
423            }]
424        );
425        clock.advance_events(tiny, &events, &mut out).unwrap();
426        assert!(out.hits().is_empty());
427    }
428
429    #[test]
430    fn large_and_partitioned_updates_deliver_identical_crossings() {
431        let duration = 0.1;
432        let track = EventTrack::new(
433            duration,
434            vec![
435                event(0., 1),
436                event(f32::MIN_POSITIVE, 2),
437                event(duration / 2., 3),
438                event(duration, 4),
439            ],
440        )
441        .unwrap();
442        let mut full = Timeline::new(duration, LoopMode::Repeat).unwrap();
443        let mut parts = full.clone();
444        let mut out = EventBuffer::<64>::default();
445        full.advance_events(duration * 8., &track, &mut out)
446            .unwrap();
447        let expected = out.hits().to_vec();
448        let report = out.report();
449        let mut actual = Vec::new();
450        let mut crossed_cycles = 0;
451        for _ in 0..64 {
452            parts
453                .advance_events(duration / 8., &track, &mut out)
454                .unwrap();
455            actual.extend_from_slice(out.hits());
456            crossed_cycles += out.report().crossed_cycles;
457            assert_eq!(out.dropped(), 0);
458        }
459        assert_eq!(actual, expected);
460        assert_eq!(actual.len(), report.emitted);
461        assert_eq!(crossed_cycles, report.crossed_cycles);
462        assert_eq!((parts.phase, parts.cycles()), (full.phase, full.cycles()));
463    }
464
465    fn compare_with_enumerated_crossings<const N: usize>(
466        mut clock: Timeline,
467        track: &EventTrack,
468        dt: f32,
469    ) {
470        // Small dyadic times keep this deliberately unbounded test oracle exact.
471        // Production instead counts whole cycles without visiting their events.
472        let end = clock.end(dt).unwrap();
473        let crossed_cycles = if clock.mode == LoopMode::Repeat {
474            end.floor() as u64
475        } else {
476            0
477        };
478        let mut expected = Vec::new();
479        if end > clock.phase {
480            for cycle in 0..=crossed_cycles {
481                for event in track.events() {
482                    let time = cycle as f64 + f64::from(event.time);
483                    if (time > clock.phase || (clock.start && time == clock.phase)) && time <= end {
484                        expected.push(EventHit {
485                            id: event.id,
486                            time: event.time,
487                            clip: 19,
488                            cycle,
489                        });
490                    }
491                }
492            }
493        }
494        let emitted = expected.len().min(N);
495        let event_cycles = expected
496            .iter()
497            .map(|hit| hit.cycle)
498            .collect::<std::collections::BTreeSet<_>>();
499        let retained_cycles = expected[..emitted]
500            .iter()
501            .map(|hit| hit.cycle)
502            .collect::<std::collections::BTreeSet<_>>();
503        let mut out = EventBuffer::<N>::default();
504        clock.advance_tagged(dt, track, 19, &mut out).unwrap();
505        assert_eq!(out.hits(), &expected[..emitted]);
506        assert_eq!(
507            out.report(),
508            EventCatchUpReport {
509                emitted,
510                dropped: (expected.len() - emitted) as u64,
511                crossed_cycles,
512                skipped_event_cycles: (event_cycles.len() - retained_cycles.len()) as u64,
513                first_dropped: expected.get(emitted).copied(),
514                cycle_saturated: false,
515            }
516        );
517        assert_eq!(out.dropped(), (expected.len() - emitted) as u64);
518        assert_eq!(clock.cycles(), crossed_cycles);
519        assert_eq!(
520            clock.phase,
521            if clock.mode == LoopMode::Repeat {
522                end % 1.
523            } else {
524                end
525            }
526        );
527    }
528
529    #[test]
530    fn bounded_output_and_reports_match_enumerated_crossings() {
531        for keys in [
532            vec![],
533            vec![event(0., 1)],
534            vec![event(1., 1)],
535            vec![event(0.5, 1)],
536            vec![
537                event(0., 1),
538                event(0., 1),
539                event(0.25, 2),
540                event(0.5, 3),
541                event(1., 4),
542                event(1., 5),
543            ],
544        ] {
545            let track = EventTrack::new(1., keys).unwrap();
546            for mode in [LoopMode::Repeat, LoopMode::Clamp] {
547                for seek in [None, Some(0.), Some(0.125), Some(0.5), Some(0.75), Some(1.)] {
548                    for speed in [0., 0.5, 2., 8.] {
549                        for paused in [false, true] {
550                            let mut clock = Timeline::new(1., mode).unwrap();
551                            if let Some(time) = seek {
552                                clock.seek(time).unwrap();
553                            }
554                            clock.set_speed(speed).unwrap();
555                            clock.set_paused(paused);
556                            for dt in [0., 0.125, 0.5, 1., 3.75] {
557                                compare_with_enumerated_crossings::<0>(clock.clone(), &track, dt);
558                                compare_with_enumerated_crossings::<1>(clock.clone(), &track, dt);
559                                compare_with_enumerated_crossings::<4>(clock.clone(), &track, dt);
560                                compare_with_enumerated_crossings::<256>(clock.clone(), &track, dt);
561                            }
562                        }
563                    }
564                }
565            }
566        }
567    }
568
569    #[test]
570    fn overflow_reports_partial_and_fully_skipped_cycles_without_replay() {
571        let track = EventTrack::new(1., vec![event(0., 1), event(0.5, 2), event(1., 3)]).unwrap();
572        let mut clock = Timeline::new(1., LoopMode::Repeat).unwrap();
573        let mut out = EventBuffer::<4>::default();
574        clock.advance_events(3., &track, &mut out).unwrap();
575        assert_eq!(
576            out.report(),
577            EventCatchUpReport {
578                emitted: 4,
579                dropped: 6,
580                crossed_cycles: 3,
581                skipped_event_cycles: 2,
582                first_dropped: Some(EventHit {
583                    id: 2,
584                    time: 0.5,
585                    clip: 0,
586                    cycle: 1
587                }),
588                cycle_saturated: false,
589            }
590        );
591        assert_eq!((clock.time(), clock.cycles()), (0., 3));
592        clock.advance_events(0.25, &track, &mut out).unwrap();
593        assert!(out.hits().is_empty());
594        assert_eq!(out.report(), EventCatchUpReport::default());
595        clock.advance_events(0.25, &track, &mut out).unwrap();
596        assert_eq!(
597            out.hits(),
598            &[EventHit {
599                id: 2,
600                time: 0.5,
601                clip: 0,
602                cycle: 3
603            }]
604        );
605        out.clear();
606        assert!(out.hits().is_empty());
607        assert_eq!(out.report(), EventCatchUpReport::default());
608    }
609
610    #[test]
611    fn seek_restart_pause_and_speed_preserve_crossing_boundaries() {
612        let track = EventTrack::new(1., vec![event(0., 1), event(0.5, 2), event(1., 3)]).unwrap();
613        let mut clock = Timeline::new(1., LoopMode::Repeat).unwrap();
614        let mut out = EventBuffer::<8>::default();
615        clock.set_paused(true);
616        clock.advance_events(60., &track, &mut out).unwrap();
617        clock.set_paused(false);
618        clock.set_speed(0.).unwrap();
619        clock.advance_events(60., &track, &mut out).unwrap();
620        clock.set_speed(2.).unwrap();
621        clock.advance_events(0., &track, &mut out).unwrap();
622        clock.advance_events(0.25, &track, &mut out).unwrap();
623        assert_eq!(
624            out.hits().iter().map(|hit| hit.id).collect::<Vec<_>>(),
625            [1, 2]
626        );
627        clock.set_paused(true);
628        clock.advance_events(60., &track, &mut out).unwrap();
629        assert_eq!(out.report(), EventCatchUpReport::default());
630        clock.set_paused(false);
631        clock.set_speed(0.5).unwrap();
632        clock.advance_events(1., &track, &mut out).unwrap();
633        assert_eq!(
634            out.hits()
635                .iter()
636                .map(|hit| (hit.id, hit.cycle))
637                .collect::<Vec<_>>(),
638            [(3, 0), (1, 1)]
639        );
640        // Seeking onto a key is silent, including wrapping an exact end to zero.
641        for time in [0.5, 1., 10.] {
642            clock.seek(time).unwrap();
643            clock.advance_events(0.25, &track, &mut out).unwrap();
644            assert!(out.hits().is_empty());
645            assert_eq!(clock.cycles(), 0);
646        }
647        clock.restart();
648        clock.advance_events(0.25, &track, &mut out).unwrap();
649        assert_eq!(out.hits().iter().map(|hit| hit.id).collect::<Vec<_>>(), [1]);
650        // Silent clock-only progression consumes start/crossings as before.
651        clock.restart();
652        clock.advance(1.).unwrap();
653        clock.advance_events(0.25, &track, &mut out).unwrap();
654        assert!(out.hits().is_empty());
655    }
656
657    #[test]
658    fn maximum_catch_up_has_exact_counts_and_empty_tracks_still_report_cycles() {
659        let duration = 0.0001;
660        let mut clock = Timeline::new(duration, LoopMode::Repeat).unwrap();
661        clock.set_speed(8.).unwrap();
662        let track = EventTrack::new(duration, vec![event(0., 1); MAX_ANIMATION_EVENTS]).unwrap();
663        let mut out = EventBuffer::<3>::default();
664        clock
665            .advance_events(MAX_ANIMATION_DT, &track, &mut out)
666            .unwrap();
667        let cycles = (480. / f64::from(duration)).floor() as u64;
668        assert_eq!(out.report().crossed_cycles, cycles);
669        assert_eq!(
670            out.dropped(),
671            (cycles + 1) * MAX_ANIMATION_EVENTS as u64 - 3
672        );
673        assert_eq!(out.report().skipped_event_cycles, cycles);
674        assert_eq!(out.report().first_dropped, out.hits().first().copied());
675        assert_eq!(clock.phase, 480. % f64::from(duration));
676        let empty = EventTrack::new(duration, vec![]).unwrap();
677        clock.restart();
678        let mut no_storage = EventBuffer::<0>::default();
679        clock
680            .advance_events(MAX_ANIMATION_DT, &empty, &mut no_storage)
681            .unwrap();
682        assert_eq!(
683            no_storage.report(),
684            EventCatchUpReport {
685                crossed_cycles: cycles,
686                ..Default::default()
687            }
688        );
689        clock.restart();
690        clock
691            .advance_events(MAX_ANIMATION_DT, &track, &mut no_storage)
692            .unwrap();
693        assert_eq!(
694            no_storage.dropped(),
695            (cycles + 1) * MAX_ANIMATION_EVENTS as u64
696        );
697        assert_eq!(no_storage.report().skipped_event_cycles, cycles + 1);
698    }
699
700    #[test]
701    fn saturated_cycle_labels_do_not_corrupt_relative_counts() {
702        let track = EventTrack::new(1., vec![event(0.5, 1)]).unwrap();
703        let mut clock = Timeline::new(1., LoopMode::Repeat).unwrap();
704        clock.cycles = u64::MAX - 1;
705        let mut out = EventBuffer::<2>::default();
706        clock.advance_events(4., &track, &mut out).unwrap();
707        assert_eq!(clock.cycles(), u64::MAX);
708        assert_eq!(
709            out.hits().iter().map(|hit| hit.cycle).collect::<Vec<_>>(),
710            [u64::MAX - 1, u64::MAX]
711        );
712        assert_eq!(
713            out.report(),
714            EventCatchUpReport {
715                emitted: 2,
716                dropped: 2,
717                crossed_cycles: 4,
718                skipped_event_cycles: 2,
719                first_dropped: Some(EventHit {
720                    id: 1,
721                    time: 0.5,
722                    clip: 0,
723                    cycle: u64::MAX
724                }),
725                cycle_saturated: true,
726            }
727        );
728        clock.advance_events(0., &track, &mut out).unwrap();
729        assert_eq!(
730            out.report(),
731            EventCatchUpReport {
732                cycle_saturated: true,
733                ..Default::default()
734            }
735        );
736    }
737
738    #[test]
739    fn invalid_input_preserves_clock_hits_and_report() {
740        let track = EventTrack::new(1., vec![event(0.5, 1)]).unwrap();
741        let wrong_duration = EventTrack::new(2., vec![]).unwrap();
742        let mut clock = Timeline::new(1., LoopMode::Repeat).unwrap();
743        let mut out = EventBuffer::<1>::default();
744        clock.advance_events(2., &track, &mut out).unwrap();
745        let hits = out.hits().to_vec();
746        let report = out.report();
747        let state = format!("{clock:?}");
748        for dt in [f32::NAN, f32::INFINITY, -1., MAX_ANIMATION_DT + 1.] {
749            assert_eq!(
750                clock.advance_events(dt, &track, &mut out),
751                Err(AnimationError::InvalidTime)
752            );
753            assert_eq!(out.hits(), hits);
754            assert_eq!(out.report(), report);
755            assert_eq!(format!("{clock:?}"), state);
756        }
757        assert_eq!(
758            clock.advance_events(1., &wrong_duration, &mut out),
759            Err(AnimationError::InvalidClip)
760        );
761        for value in [f32::NAN, f32::INFINITY, -1.] {
762            assert_eq!(clock.seek(value), Err(AnimationError::InvalidTime));
763            assert_eq!(clock.set_speed(value), Err(AnimationError::InvalidTime));
764        }
765        assert_eq!(clock.set_speed(8.01), Err(AnimationError::InvalidTime));
766        assert_eq!(format!("{clock:?}"), state);
767        assert_eq!(out.hits(), hits);
768        assert_eq!(out.report(), report);
769    }
770
771    #[test]
772    fn sprite_player_populates_the_shared_report_and_finishes_once() {
773        let clip = SpriteClip::new(vec![super::super::SpriteFrame {
774            index: 4,
775            duration: 1.,
776        }])
777        .unwrap();
778        let mut sprite =
779            SpritePlayer::new(clip, LoopMode::Clamp, vec![event(0., 1), event(1., 2)]).unwrap();
780        let mut out = EventBuffer::<1>::default();
781        sprite.advance(60., &mut out).unwrap();
782        assert!(sprite.timeline().finished());
783        assert_eq!(sprite.frame(), 4);
784        assert_eq!(
785            out.report(),
786            EventCatchUpReport {
787                emitted: 1,
788                dropped: 1,
789                first_dropped: Some(EventHit {
790                    id: 2,
791                    time: 1.,
792                    clip: 0,
793                    cycle: 0
794                }),
795                ..Default::default()
796            }
797        );
798        sprite.advance(60., &mut out).unwrap();
799        assert_eq!(out.report(), EventCatchUpReport::default());
800        assert!(out.hits().is_empty());
801    }
802}