ferravex_play/replay/
ghost.rs

1//! Presentation-only transforms. Ghosts never enter collision or game authority.
2//!
3//! [`GhostTrack::sample_checked`] distinguishes missing history from invalid
4//! queries and exposes exact keys, interpolation and holds before teleports.
5//! Queries never advance replay time or mutate the recorded samples.
6use super::ReplayError;
7use ferravex_math::{Quat, Vec3};
8pub const MAX_SAMPLES: usize = 120_000;
9/// Recorded pose at an integer simulation tick.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct Sample {
12    pub tick: u64,
13    pub position: Vec3,
14    pub rotation: Quat,
15    /// This key starts a discontinuity: hold the preceding key until this tick.
16    /// Motion from this key to the next is continuous unless that next key also
17    /// has `teleport` set. The recorder must mark teleports explicitly.
18    pub teleport: bool,
19}
20
21/// Placement and presentation pose of a checked ghost query.
22///
23/// Exact keys retain their stored teleport flag. Synthesized poses clear it;
24/// [`Held`](Self::Held) explicitly identifies a discontinuous interval instead.
25/// These states describe the requested time, not an event stream: repeating an
26/// exact query returns the same key, including its teleport flag.
27/// See [`GhostTrack::sample_checked`] for a complete example.
28#[derive(Clone, Copy, Debug, PartialEq)]
29pub enum SampleState {
30    /// No recorded poses, including a zero-capacity track.
31    Empty,
32    /// Earlier than the first recorded tick; no pose is synthesized.
33    BeforeStart {
34        /// First recorded pose, available for an explicit caller-owned hold.
35        first: Sample,
36    },
37    /// Later than the last recorded tick; no pose is synthesized.
38    AfterEnd {
39        /// Last recorded pose, available for an explicit caller-owned hold.
40        last: Sample,
41    },
42    /// Exactly a recorded tick with zero alpha; the stored pose is unchanged.
43    Exact(Sample),
44    /// Continuous motion between two distinct recorded ticks.
45    Interpolated {
46        /// Interpolated pose, with the query's integer tick and no teleport flag.
47        sample: Sample,
48        /// Recorded tick preceding the query.
49        from_tick: u64,
50        /// Recorded tick following the query.
51        to_tick: u64,
52    },
53    /// Holding the preceding pose until a marked teleport; neither position nor
54    /// rotation is blended across the discontinuity.
55    Held {
56        /// Held pose, with the query's integer tick and no teleport flag.
57        sample: Sample,
58        /// Tick of the recorded pose being held.
59        from_tick: u64,
60        /// Tick at which the new pose becomes visible.
61        teleport_tick: u64,
62    },
63}
64
65impl SampleState {
66    /// Return an in-range presentation pose without clamping or extrapolation.
67    ///
68    /// ```
69    /// use ferravex_play::replay::ghost::{GhostTrack, Sample};
70    /// use ferravex_math::{Quat, Vec3};
71    ///
72    /// let mut track = GhostTrack::new(7, 60, 1)?;
73    /// track.push(Sample {
74    ///     tick: 10, position: Vec3::ZERO, rotation: Quat::IDENTITY, teleport: true,
75    /// })?;
76    /// assert!(track.sample_checked(10, 0.0)?.sample().unwrap().teleport);
77    /// assert!(track.sample_checked(10, 0.5)?.sample().is_none());
78    /// # Ok::<(), ferravex_play::replay::ReplayError>(())
79    /// ```
80    pub fn sample(self) -> Option<Sample> {
81        match self {
82            Self::Exact(sample) | Self::Interpolated { sample, .. } | Self::Held { sample, .. } => {
83                Some(sample)
84            }
85            Self::Empty | Self::BeforeStart { .. } | Self::AfterEnd { .. } => None,
86        }
87    }
88}
89
90#[derive(Clone, Debug)]
91pub struct GhostTrack {
92    context: u64,
93    tick_hz: u16,
94    samples: Vec<Sample>,
95    capacity: usize,
96}
97impl GhostTrack {
98    pub fn new(context: u64, tick_hz: u16, capacity: usize) -> Result<Self, ReplayError> {
99        if !(1..=1000).contains(&tick_hz) || capacity > MAX_SAMPLES {
100            return Err(ReplayError::InvalidLimits);
101        }
102        Ok(Self {
103            context,
104            tick_hz,
105            samples: Vec::with_capacity(capacity),
106            capacity,
107        })
108    }
109    pub fn context(&self) -> u64 {
110        self.context
111    }
112    pub fn tick_hz(&self) -> u16 {
113        self.tick_hz
114    }
115    pub fn samples(&self) -> &[Sample] {
116        &self.samples
117    }
118    /// Append a pose at a strictly newer tick, normalizing its rotation.
119    ///
120    /// Duplicate, decreasing and wrapped ticks return [`ReplayError::TickOrder`]
121    /// while space remains; a full track returns [`ReplayError::Capacity`] first.
122    /// Rejections leave all recorded poses unchanged, including teleport flags.
123    /// A teleport must use its own newer tick, never replace an existing key.
124    ///
125    /// ```
126    /// use ferravex_play::replay::{ReplayError, ghost::{GhostTrack, Sample}};
127    /// use ferravex_math::{Quat, Vec3};
128    ///
129    /// let mut track = GhostTrack::new(7, 60, 2)?;
130    /// let pose = Sample {
131    ///     tick: 10, position: Vec3::ZERO, rotation: Quat::IDENTITY, teleport: false,
132    /// };
133    /// track.push(pose)?;
134    /// assert_eq!(track.push(Sample { teleport: true, ..pose }), Err(ReplayError::TickOrder));
135    /// assert_eq!(track.samples(), &[pose]);
136    /// # Ok::<(), ReplayError>(())
137    /// ```
138    pub fn push(&mut self, mut sample: Sample) -> Result<(), ReplayError> {
139        if self.samples.len() == self.capacity {
140            return Err(ReplayError::Capacity);
141        }
142        if self.samples.last().is_some_and(|s| s.tick >= sample.tick) {
143            return Err(ReplayError::TickOrder);
144        }
145        if !sample.position.is_finite()
146            || sample.position.abs().max_element() > 1e6
147            || !sample.rotation.is_finite()
148            || sample.rotation.length_squared() < 1e-8
149        {
150            return Err(ReplayError::InvalidData);
151        }
152        sample.rotation = sample.rotation.normalize();
153        self.samples.push(sample);
154        Ok(())
155    }
156    /// Integer ticks retain precision even after long sessions. Alpha is the
157    /// fractional simulation tick, not a fraction between sparse samples.
158    ///
159    /// This compatibility API retains its original synthesized teleport flags.
160    /// Use [`Self::sample_checked`] for exact stored keys and explicit states.
161    pub fn sample(&self, tick: u64, alpha: f32) -> Option<Sample> {
162        if !alpha.is_finite() || !(0.0..1.0).contains(&alpha) {
163            return None;
164        }
165        let first = self.samples.first()?;
166        let last = self.samples.last()?;
167        if tick < first.tick || tick > last.tick || (tick == last.tick && alpha > 0.) {
168            return None;
169        }
170        let i = self.samples.partition_point(|s| s.tick <= tick) - 1;
171        let a = self.samples[i];
172        let Some(b) = self.samples.get(i + 1).copied() else {
173            return Some(a);
174        };
175        if b.teleport {
176            return Some(Sample { tick, ..a });
177        }
178        Some(interpolate(a, b, tick, alpha))
179    }
180
181    /// Sample `tick + alpha` with explicit range and discontinuity states.
182    ///
183    /// Alpha is a fractional simulation tick in `[0, 1)`, not a fraction of the
184    /// gap between recorded keys. Invalid alpha (including NaN, infinity or `1`)
185    /// returns [`ReplayError::InvalidData`], even for an empty track. No input is
186    /// clamped. A positive alpha at the final tick is [`AfterEnd`](SampleState::AfterEnd),
187    /// including at `u64::MAX`; ticks never wrap or convert wholesale to floats.
188    ///
189    /// Exact queries return stored keys unchanged, including teleport flags and
190    /// quaternion signs. Between keys, an upcoming teleport holds both position
191    /// and rotation until its exact tick. Interpolation resumes from that key
192    /// unless the next key is also marked. Only exact keys retain teleport flags;
193    /// a hold is reported as [`Held`](SampleState::Held), not a repeated teleport.
194    ///
195    /// Duplicate/decreasing keys are rejected by [`Self::push`], so every
196    /// interpolation interval has positive length. Queries allocate nothing,
197    /// take `O(log(samples.len()))` time and may repeat or seek in either direction.
198    /// Interpolation uses relative `f64` tick differences, then `f32` poses;
199    /// rounding can produce an endpoint pose for a strictly interior query.
200    ///
201    /// ```
202    /// use ferravex_play::replay::{ReplayError, ghost::{GhostTrack, Sample, SampleState}};
203    /// use ferravex_math::{Quat, Vec3};
204    ///
205    /// let mut track = GhostTrack::new(7, 60, 3)?;
206    /// for (tick, x, teleport) in [(10, 0.0, false), (20, 100.0, true), (30, 110.0, false)] {
207    ///     track.push(Sample {
208    ///         tick, position: Vec3::X * x, rotation: Quat::IDENTITY, teleport,
209    ///     })?;
210    /// }
211    /// assert!(matches!(track.sample_checked(9, 0.5)?, SampleState::BeforeStart { .. }));
212    /// assert!(matches!(track.sample_checked(19, 0.5)?, SampleState::Held {
213    ///     from_tick: 10, teleport_tick: 20, ..
214    /// }));
215    /// assert_eq!(track.sample_checked(19, 0.5)?.sample().unwrap().position.x, 0.0);
216    /// assert_eq!(track.sample_checked(20, 0.0)?, SampleState::Exact(track.samples()[1]));
217    /// let moving = track.sample_checked(20, 0.5)?;
218    /// assert!(matches!(moving, SampleState::Interpolated { from_tick: 20, to_tick: 30, .. }));
219    /// assert_eq!(moving.sample().unwrap().position.x, 100.5);
220    /// assert!(matches!(track.sample_checked(30, 0.5)?, SampleState::AfterEnd { .. }));
221    /// assert_eq!(track.sample_checked(20, f32::NAN), Err(ReplayError::InvalidData));
222    /// # Ok::<(), ReplayError>(())
223    /// ```
224    pub fn sample_checked(&self, tick: u64, alpha: f32) -> Result<SampleState, ReplayError> {
225        if !alpha.is_finite() || !(0.0..1.0).contains(&alpha) {
226            return Err(ReplayError::InvalidData);
227        }
228        let Some(&first) = self.samples.first() else {
229            return Ok(SampleState::Empty);
230        };
231        if tick < first.tick {
232            return Ok(SampleState::BeforeStart { first });
233        }
234        let last = self.samples[self.samples.len() - 1];
235        if tick > last.tick || (tick == last.tick && alpha > 0.) {
236            return Ok(SampleState::AfterEnd { last });
237        }
238        let i = self.samples.partition_point(|s| s.tick <= tick) - 1;
239        let a = self.samples[i];
240        if tick == a.tick && alpha == 0. {
241            return Ok(SampleState::Exact(a));
242        }
243        // The final key was handled above; an in-range nonexact query has a successor.
244        let b = self.samples[i + 1];
245        if b.teleport {
246            return Ok(SampleState::Held {
247                sample: Sample {
248                    tick,
249                    teleport: false,
250                    ..a
251                },
252                from_tick: a.tick,
253                teleport_tick: b.tick,
254            });
255        }
256        Ok(SampleState::Interpolated {
257            sample: interpolate(a, b, tick, alpha),
258            from_tick: a.tick,
259            to_tick: b.tick,
260        })
261    }
262}
263
264fn interpolate(a: Sample, b: Sample, tick: u64, alpha: f32) -> Sample {
265    let t = ((tick - a.tick) as f64 + f64::from(alpha)) / (b.tick - a.tick) as f64;
266    Sample {
267        tick,
268        position: a.position.lerp(b.position, t as f32),
269        rotation: a.rotation.slerp(b.rotation, t as f32),
270        teleport: false,
271    }
272}
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    fn pose(tick: u64, x: f32, teleport: bool) -> Sample {
278        Sample {
279            tick,
280            position: Vec3::X * x,
281            rotation: Quat::IDENTITY,
282            teleport,
283        }
284    }
285
286    #[test]
287    fn checked_empty_and_invalid_fractions_are_distinct() {
288        let mut empty = GhostTrack::new(4, 64, 0).unwrap();
289        let mut populated = GhostTrack::new(4, 64, 1).unwrap();
290        populated.push(pose(10, 1., false)).unwrap();
291        assert_eq!(empty.push(pose(10, 1., false)), Err(ReplayError::Capacity));
292        for track in [&empty, &populated] {
293            for tick in [0, 10, u64::MAX] {
294                for alpha in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.1, 1., 2.] {
295                    assert_eq!(
296                        track.sample_checked(tick, alpha),
297                        Err(ReplayError::InvalidData)
298                    );
299                    assert_eq!(track.sample(tick, alpha), None);
300                }
301            }
302        }
303        for tick in [0, 10, u64::MAX] {
304            for alpha in [0., -0., 0.5] {
305                assert_eq!(empty.sample_checked(tick, alpha), Ok(SampleState::Empty));
306            }
307        }
308        assert_eq!(SampleState::Empty.sample(), None);
309        assert!(empty.samples().is_empty());
310    }
311
312    #[test]
313    fn checked_single_key_has_inclusive_exact_and_exclusive_fractional_end() {
314        for tick in [0, 10, u64::MAX] {
315            let mut track = GhostTrack::new(4, 64, 1).unwrap();
316            track.push(pose(tick, 7., true)).unwrap();
317            let key = track.samples()[0];
318            for alpha in [0., -0.] {
319                let state = track.sample_checked(tick, alpha).unwrap();
320                assert_eq!(state, SampleState::Exact(key));
321                assert_eq!(state.sample(), Some(key));
322            }
323            for alpha in [
324                f32::from_bits(1),
325                0.5,
326                f32::from_bits(1.0_f32.to_bits() - 1),
327            ] {
328                let state = track.sample_checked(tick, alpha).unwrap();
329                assert_eq!(state, SampleState::AfterEnd { last: key });
330                assert_eq!(state.sample(), None);
331            }
332            if let Some(before) = tick.checked_sub(1) {
333                let state = track.sample_checked(before, 0.999).unwrap();
334                assert_eq!(state, SampleState::BeforeStart { first: key });
335                assert_eq!(state.sample(), None);
336            }
337            if let Some(after) = tick.checked_add(1) {
338                assert_eq!(
339                    track.sample_checked(after, 0.),
340                    Ok(SampleState::AfterEnd { last: key })
341                );
342            }
343        }
344    }
345
346    #[test]
347    fn checked_exact_keys_preserve_quaternion_sign_and_teleport_flag() {
348        let mut track = GhostTrack::new(4, 64, 3).unwrap();
349        for tick in [10, 20, 30] {
350            track
351                .push(Sample {
352                    rotation: if tick == 20 {
353                        -Quat::IDENTITY
354                    } else {
355                        Quat::IDENTITY
356                    },
357                    ..pose(tick, tick as f32, tick != 30)
358                })
359                .unwrap();
360        }
361        for &key in track.samples() {
362            assert_eq!(
363                track.sample_checked(key.tick, 0.),
364                Ok(SampleState::Exact(key))
365            );
366        }
367        // The additive API does not change the legacy interior-key flag behavior.
368        assert!(!track.sample(20, 0.).unwrap().teleport);
369        assert!(
370            track
371                .sample_checked(20, 0.)
372                .unwrap()
373                .sample()
374                .unwrap()
375                .teleport
376        );
377        assert!(track.sample(15, 0.).unwrap().teleport);
378        assert!(
379            !track
380                .sample_checked(15, 0.)
381                .unwrap()
382                .sample()
383                .unwrap()
384                .teleport
385        );
386        assert_eq!(
387            track.sample_checked(9, 0.5),
388            Ok(SampleState::BeforeStart {
389                first: track.samples()[0]
390            })
391        );
392        assert_eq!(
393            track.sample_checked(30, 0.5),
394            Ok(SampleState::AfterEnd {
395                last: track.samples()[2]
396            })
397        );
398    }
399
400    #[test]
401    fn checked_teleports_hold_both_components_then_resume_continuous_motion() {
402        let mut track = GhostTrack::new(4, 64, 4).unwrap();
403        let turn = Quat::from_rotation_y(std::f32::consts::FRAC_PI_2);
404        for key in [
405            pose(10, 0., false),
406            Sample {
407                rotation: turn,
408                ..pose(20, 100., true)
409            },
410            pose(21, -100., true),
411            pose(25, -92., false),
412        ] {
413            track.push(key).unwrap();
414        }
415        let original = track.samples().to_vec();
416        // Seek in both directions and repeat a query: sampling has no cursor.
417        for (tick, alpha, from, to) in [
418            (20, 0.5, 1, 2),
419            (19, 0.999, 0, 1),
420            (10, 0.5, 0, 1),
421            (15, 0., 0, 1),
422            (20, 0.5, 1, 2),
423        ] {
424            let expected = Sample {
425                tick,
426                teleport: false,
427                ..original[from]
428            };
429            let state = track.sample_checked(tick, alpha).unwrap();
430            assert_eq!(
431                state,
432                SampleState::Held {
433                    sample: expected,
434                    from_tick: original[from].tick,
435                    teleport_tick: original[to].tick,
436                }
437            );
438            assert_eq!(state.sample(), Some(expected));
439        }
440        for index in [1, 2] {
441            assert_eq!(
442                track.sample_checked(original[index].tick, 0.),
443                Ok(SampleState::Exact(original[index]))
444            );
445        }
446        assert_eq!(
447            track.sample_checked(21, 0.5),
448            Ok(SampleState::Interpolated {
449                sample: pose(21, -99., false),
450                from_tick: 21,
451                to_tick: 25,
452            })
453        );
454        assert_eq!(track.samples(), original);
455    }
456
457    #[test]
458    fn checked_sparse_interpolation_uses_tick_gap_and_shortest_rotation() {
459        let mut track = GhostTrack::new(4, 64, 3).unwrap();
460        let start = u64::MAX - 20;
461        track.push(pose(start, 0., false)).unwrap();
462        track
463            .push(Sample {
464                rotation: -Quat::from_rotation_y(std::f32::consts::FRAC_PI_2),
465                ..pose(start + 10, 10., false)
466            })
467            .unwrap();
468        track.push(pose(u64::MAX, 50., true)).unwrap();
469        let state = track.sample_checked(start + 5, 0.5).unwrap();
470        assert!(
471            matches!(state, SampleState::Interpolated { from_tick, to_tick, .. }
472            if from_tick == start && to_tick == start + 10)
473        );
474        let sample = state.sample().unwrap();
475        assert_eq!(sample.position.x, 5.5);
476        assert_eq!(sample.tick, start + 5);
477        assert!(!sample.teleport);
478        assert!((sample.rotation.length_squared() - 1.).abs() < 1e-6);
479        let expected = Quat::from_rotation_y(std::f32::consts::FRAC_PI_2 * 0.55) * Vec3::X;
480        assert!((sample.rotation * Vec3::X - expected).length() < 1e-6);
481        assert_eq!(track.sample(start + 5, 0.5), Some(sample));
482        assert!(matches!(
483            track.sample_checked(u64::MAX - 1, 0.999).unwrap(),
484            SampleState::Held {
485                teleport_tick: u64::MAX,
486                ..
487            }
488        ));
489        assert_eq!(
490            track.sample_checked(u64::MAX, 0.),
491            Ok(SampleState::Exact(track.samples()[2]))
492        );
493    }
494
495    #[test]
496    fn checked_full_tick_span_never_wraps_or_extrapolates() {
497        let mut track = GhostTrack::new(4, 64, 2).unwrap();
498        track.push(pose(0, -1e6, false)).unwrap();
499        track.push(pose(u64::MAX, 1e6, false)).unwrap();
500        for tick in [0, 1, u64::MAX / 2, u64::MAX - 1] {
501            let state = track.sample_checked(tick, 0.5).unwrap();
502            assert!(matches!(
503                state,
504                SampleState::Interpolated {
505                    from_tick: 0,
506                    to_tick: u64::MAX,
507                    ..
508                }
509            ));
510            let sample = state.sample().unwrap();
511            assert!(sample.position.is_finite());
512            assert!(sample.position.x.abs() <= 1e6);
513            assert!(sample.rotation.is_finite());
514        }
515        assert_eq!(
516            track.sample_checked(u64::MAX, 0.5),
517            Ok(SampleState::AfterEnd {
518                last: track.samples()[1]
519            })
520        );
521    }
522
523    #[test]
524    fn rejected_duplicate_decreasing_and_wrapped_ticks_preserve_history() {
525        let mut track = GhostTrack::new(4, 64, 3).unwrap();
526        track.push(pose(10, 0., false)).unwrap();
527        track.push(pose(20, 10., false)).unwrap();
528        let original = track.samples().to_vec();
529        let before = track.sample_checked(15, 0.5).unwrap();
530        for tick in [20, 19, 10, 0] {
531            assert_eq!(
532                track.push(pose(tick, 99., true)),
533                Err(ReplayError::TickOrder)
534            );
535            assert_eq!(track.samples(), original);
536            assert_eq!(track.sample_checked(15, 0.5), Ok(before));
537        }
538        track.push(pose(30, 20., false)).unwrap();
539        // Full-track error precedence stays compatible, even for a duplicate.
540        for tick in [30, 31] {
541            assert_eq!(
542                track.push(pose(tick, 99., true)),
543                Err(ReplayError::Capacity)
544            );
545        }
546        assert_eq!(track.samples().len(), 3);
547        let mut wrapping = GhostTrack::new(4, 64, 2).unwrap();
548        wrapping.push(pose(u64::MAX, 0., false)).unwrap();
549        assert_eq!(
550            wrapping.push(pose(0, 99., true)),
551            Err(ReplayError::TickOrder)
552        );
553        assert_eq!(wrapping.samples(), &[pose(u64::MAX, 0., false)]);
554    }
555
556    #[test]
557    fn rejected_invalid_poses_do_not_create_discontinuities() {
558        let mut track = GhostTrack::new(4, 64, 2).unwrap();
559        track.push(pose(10, 0., false)).unwrap();
560        let valid = pose(20, 10., true);
561        for invalid in [
562            Sample {
563                position: Vec3::NAN,
564                ..valid
565            },
566            Sample {
567                position: Vec3::X * 1_000_001.,
568                ..valid
569            },
570            Sample {
571                rotation: Quat::NAN,
572                ..valid
573            },
574            Sample {
575                rotation: Quat::from_xyzw(0., 0., 0., 0.),
576                ..valid
577            },
578        ] {
579            assert_eq!(track.push(invalid), Err(ReplayError::InvalidData));
580            assert_eq!(track.samples(), &[pose(10, 0., false)]);
581        }
582        track
583            .push(Sample {
584                rotation: Quat::IDENTITY * 2.,
585                ..valid
586            })
587            .unwrap();
588        assert_eq!(track.samples()[1], valid);
589        assert!(matches!(
590            track.sample_checked(15, 0.).unwrap(),
591            SampleState::Held {
592                teleport_tick: 20,
593                ..
594            }
595        ));
596    }
597
598    #[test]
599    fn sparse_interpolation_and_discontinuities() {
600        let mut g = GhostTrack::new(4, 64, 3).unwrap();
601        for (tick, x, teleport) in [
602            (u64::MAX - 20, 0., false),
603            (u64::MAX - 10, 10., false),
604            (u64::MAX, 50., true),
605        ] {
606            g.push(Sample {
607                tick,
608                position: Vec3::X * x,
609                rotation: Quat::IDENTITY,
610                teleport,
611            })
612            .unwrap();
613        }
614        assert_eq!(g.sample(u64::MAX - 15, 0.5).unwrap().position.x, 5.5);
615        assert_eq!(g.sample(u64::MAX - 5, 0.).unwrap().position.x, 10.);
616        assert!(g.sample(u64::MAX, 0.5).is_none());
617        assert!(g.sample(u64::MAX - 21, 0.).is_none());
618    }
619}