Skip to main content

rayengine_core/
time.rs

1//! Fixed simulation timing with bounded catch-up and render interpolation.
2
3use std::time::Duration;
4
5/// Information for exactly one fixed simulation update.
6#[derive(Clone, Copy, Debug)]
7pub struct Tick {
8    /// Zero-based simulation tick index.
9    pub index: u64,
10    /// Duration of this tick in seconds, independent of render framerate.
11    pub dt: f32,
12}
13
14/// Updates to execute before drawing a frame.
15#[derive(Clone, Copy, Debug)]
16pub struct FramePlan {
17    /// Number of fixed updates to execute.
18    pub steps: u32,
19    /// Index of the first tick in this plan.
20    pub first_tick: u64,
21    /// Fraction between the previous and current simulation state, in `[0, 1)`.
22    pub alpha: f32,
23    /// Whole simulation time discarded to bound catch-up work.
24    pub dropped: Duration,
25}
26
27/// Accumulator clock that never requests an unbounded number of updates.
28///
29/// ```
30/// use std::time::Duration;
31/// use rayengine_core::time::FixedClock;
32/// let mut clock = FixedClock::new(60, 8);
33/// let frame = clock.advance(Duration::from_millis(20));
34/// assert_eq!(frame.steps, 1);
35/// assert!(frame.alpha > 0.0 && frame.alpha < 1.0);
36/// ```
37#[derive(Debug)]
38pub struct FixedClock {
39    step: Duration,
40    accumulator: Duration,
41    max_steps: u32,
42    tick: u64,
43}
44
45impl FixedClock {
46    /// Creates a clock. Panics for zero rates, zero limits, or rates above 1000 Hz.
47    pub fn new(hz: u32, max_steps: u32) -> Self {
48        assert!((1..=1000).contains(&hz), "fixed rate must be 1..=1000 Hz");
49        assert!(max_steps > 0, "catch-up limit must be positive");
50        Self {
51            step: Duration::from_secs_f64(1.0 / f64::from(hz)),
52            accumulator: Duration::ZERO,
53            max_steps,
54            tick: 0,
55        }
56    }
57
58    /// Fixed timestep duration, rounded to the nearest nanosecond.
59    pub fn step(&self) -> Duration {
60        self.step
61    }
62
63    /// Total number of requested simulation ticks.
64    pub fn ticks(&self) -> u64 {
65        self.tick
66    }
67
68    /// Adds elapsed wall time and returns the bounded work for this render frame.
69    /// Excess whole ticks are dropped, while the fractional remainder is kept.
70    pub fn advance(&mut self, elapsed: Duration) -> FramePlan {
71        self.accumulator = self.accumulator.saturating_add(elapsed);
72        let available = self.accumulator.as_nanos() / self.step.as_nanos();
73        let steps = available.min(u128::from(self.max_steps)) as u32;
74        let remainder = self.accumulator.as_nanos() % self.step.as_nanos();
75        let fraction = Duration::from_nanos(remainder as u64);
76        let dropped = self
77            .accumulator
78            .saturating_sub(self.step * steps + fraction);
79        self.accumulator = fraction;
80        let first_tick = self.tick;
81        self.tick = self.tick.saturating_add(u64::from(steps));
82        FramePlan {
83            steps,
84            first_tick,
85            // f32 rounding must not turn a fraction just below one into one.
86            alpha: (fraction.as_secs_f64() / self.step.as_secs_f64())
87                .min(f64::from(f32::from_bits(1.0f32.to_bits() - 1))) as f32,
88            dropped,
89        }
90    }
91}
92
93/// Game-owned timer, advanced explicitly by simulation or wall-clock time.
94///
95/// A repeated timer returns the number of crossed periods, so a long update
96/// cannot silently lose scheduled events. Pausing never queues elapsed time.
97#[derive(Clone, Debug)]
98pub struct Timer {
99    duration: Duration,
100    elapsed: Duration,
101    repeating: bool,
102    finished: bool,
103    paused: bool,
104}
105
106impl Timer {
107    /// Timer that completes once. A zero duration completes on its first advance.
108    pub fn once(duration: Duration) -> Self {
109        Self {
110            duration,
111            elapsed: Duration::ZERO,
112            repeating: false,
113            finished: false,
114            paused: false,
115        }
116    }
117    /// Repeated timer. Panics for a zero period.
118    pub fn repeating(duration: Duration) -> Self {
119        assert!(
120            !duration.is_zero(),
121            "repeating timer period must be nonzero"
122        );
123        Self {
124            repeating: true,
125            ..Self::once(duration)
126        }
127    }
128    /// Advances by a duration and returns completions (saturated at `u32::MAX`).
129    pub fn advance(&mut self, elapsed: Duration) -> u32 {
130        if self.paused || self.finished {
131            return 0;
132        }
133        self.elapsed = self.elapsed.saturating_add(elapsed);
134        if self.elapsed < self.duration {
135            return 0;
136        }
137        if self.repeating {
138            let completions = self.elapsed.as_nanos() / self.duration.as_nanos();
139            let remainder = self.elapsed.as_nanos() % self.duration.as_nanos();
140            self.elapsed = Duration::new(
141                (remainder / 1_000_000_000) as u64,
142                (remainder % 1_000_000_000) as u32,
143            );
144            completions.min(u128::from(u32::MAX)) as u32
145        } else {
146            self.elapsed = self.duration;
147            self.finished = true;
148            1
149        }
150    }
151    /// Whether a one-shot timer has completed. Repeated timers never finish.
152    pub fn finished(&self) -> bool {
153        self.finished
154    }
155    /// Progress from zero to one; repeated timers report their current period.
156    pub fn fraction(&self) -> f32 {
157        if self.duration.is_zero() {
158            return if self.finished { 1.0 } else { 0.0 };
159        }
160        (self.elapsed.as_secs_f64() / self.duration.as_secs_f64()).clamp(0.0, 1.0) as f32
161    }
162    /// Pauses/resumes the timer without accumulating elapsed time while paused.
163    pub fn set_paused(&mut self, paused: bool) {
164        self.paused = paused;
165    }
166    /// Restarts from zero, preserving the current paused state.
167    pub fn reset(&mut self) {
168        self.elapsed = Duration::ZERO;
169        self.finished = false;
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn render_partition_does_not_change_simulation_ticks() {
179        let mut whole = FixedClock::new(60, 1000);
180        let mut pieces = FixedClock::new(60, 1000);
181        whole.advance(Duration::from_secs(2));
182        for _ in 0..200 {
183            pieces.advance(Duration::from_millis(10));
184        }
185        assert_eq!(whole.ticks(), pieces.ticks());
186        assert_eq!(whole.accumulator, pieces.accumulator);
187    }
188
189    #[test]
190    fn catch_up_is_bounded_without_losing_fraction() {
191        let mut clock = FixedClock::new(100, 4);
192        let frame = clock.advance(Duration::from_millis(105));
193        assert_eq!(frame.steps, 4);
194        assert_eq!(frame.dropped, Duration::from_millis(60));
195        assert!((frame.alpha - 0.5).abs() < 0.00001);
196        let next = clock.advance(Duration::from_millis(5));
197        assert_eq!(next.first_tick, 4);
198        assert_eq!(next.steps, 1);
199    }
200
201    #[test]
202    fn zero_elapsed_never_invents_an_update() {
203        let mut clock = FixedClock::new(60, 8);
204        assert_eq!(clock.advance(Duration::ZERO).steps, 0);
205    }
206
207    #[test]
208    fn repeating_timer_keeps_multiple_completions_and_remainder() {
209        let mut timer = Timer::repeating(Duration::from_millis(100));
210        assert_eq!(timer.advance(Duration::from_millis(350)), 3);
211        assert_eq!(timer.fraction(), 0.5);
212        assert_eq!(timer.advance(Duration::from_millis(50)), 1);
213        assert!(!timer.finished());
214    }
215
216    #[test]
217    fn one_shot_pause_and_reset_have_explicit_behavior() {
218        let mut timer = Timer::once(Duration::from_millis(100));
219        timer.set_paused(true);
220        assert_eq!(timer.advance(Duration::from_secs(10)), 0);
221        timer.set_paused(false);
222        assert_eq!(timer.advance(Duration::from_millis(120)), 1);
223        assert!(timer.finished());
224        assert_eq!(timer.advance(Duration::from_secs(1)), 0);
225        timer.reset();
226        assert_eq!(timer.advance(Duration::from_millis(100)), 1);
227        let mut immediate = Timer::once(Duration::ZERO);
228        assert_eq!(immediate.advance(Duration::ZERO), 1);
229        assert_eq!(immediate.advance(Duration::ZERO), 0);
230    }
231}