Skip to main content

rusting_core/
time.rs

1use std::time::Duration;
2use std::{error::Error, fmt};
3
4use bevy_ecs::prelude::Resource;
5
6/// Frame and simulation timing visible to systems.
7#[derive(Resource, Clone, Copy, Debug)]
8pub struct FrameTime {
9    /// Number of successful application updates since the app started.
10    pub frame: u64,
11    /// Real time since the previous frame, even while paused.
12    pub real_delta: Duration,
13    /// Game time since the previous frame after pause and time scale.
14    pub delta: Duration,
15    /// Total game time, without time spent paused.
16    pub elapsed: Duration,
17    /// Time simulated by one fixed-schedule execution.
18    pub fixed_delta: Duration,
19    /// Number of completed fixed-schedule executions.
20    pub fixed_tick: u64,
21}
22
23impl Default for FrameTime {
24    fn default() -> Self {
25        Self {
26            frame: 0,
27            real_delta: Duration::ZERO,
28            delta: Duration::ZERO,
29            elapsed: Duration::ZERO,
30            fixed_delta: Duration::from_secs_f64(1.0 / 60.0),
31            fixed_tick: 0,
32        }
33    }
34}
35
36impl FrameTime {
37    /// Returns the current game-frame time as an easy-to-use `f32` value.
38    #[must_use]
39    pub fn delta_seconds(&self) -> f32 {
40        self.delta.as_secs_f32()
41    }
42
43    /// Returns total running game time as an easy-to-use `f32` value.
44    #[must_use]
45    pub fn elapsed_seconds(&self) -> f32 {
46        self.elapsed.as_secs_f32()
47    }
48}
49
50/// Pause, stepping, scale, and fixed-schedule catch-up controls.
51#[derive(Resource, Clone, Debug)]
52pub struct TimeControl {
53    /// Whether variable time and ordinary fixed-schedule executions are paused.
54    pub paused: bool,
55    /// Multiplier applied to real time while the simulation is running.
56    pub time_scale: f64,
57    /// Time simulated by one fixed-schedule execution.
58    pub fixed_delta: Duration,
59    /// Maximum number of accumulated fixed-schedule executions run per application update.
60    pub max_fixed_steps: u32,
61    accumulator: Duration,
62    pending_steps: u32,
63}
64
65impl Default for TimeControl {
66    fn default() -> Self {
67        Self {
68            paused: false,
69            time_scale: 1.0,
70            fixed_delta: Duration::from_secs_f64(1.0 / 60.0),
71            max_fixed_steps: 8,
72            accumulator: Duration::ZERO,
73            pending_steps: 0,
74        }
75    }
76}
77
78impl TimeControl {
79    /// Pauses variable time and ordinary fixed-schedule executions.
80    pub fn pause(&mut self) {
81        self.paused = true;
82    }
83
84    /// Resumes variable time and ordinary fixed-schedule executions.
85    pub fn resume(&mut self) {
86        self.paused = false;
87    }
88
89    /// Queues one fixed-schedule execution to be consumed while paused.
90    pub fn step(&mut self) {
91        self.pending_steps = self.pending_steps.saturating_add(1);
92    }
93}
94
95/// Errors produced while advancing simulation time.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum TimeAdvanceError {
98    /// The configured fixed timestep is zero.
99    InvalidFixedDelta,
100}
101
102impl fmt::Display for TimeAdvanceError {
103    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            Self::InvalidFixedDelta => {
106                formatter.write_str("fixed delta must be greater than zero")
107            }
108        }
109    }
110}
111
112impl Error for TimeAdvanceError {}
113
114/// Advances frame and fixed-schedule bookkeeping by one application update.
115///
116/// Catch-up work is capped by [`TimeControl::max_fixed_steps`]. Remaining
117/// accumulated time is retained for later updates, up to one more capped
118/// update's worth; older backlog is dropped. A queued step is
119/// consumed only while paused and advances elapsed time by exactly one fixed
120/// timestep without consuming the accumulator.
121///
122/// # Errors
123///
124/// Returns [`TimeAdvanceError::InvalidFixedDelta`] when `control.fixed_delta`
125/// is zero, before mutating either the supplied [`TimeControl`] or
126/// [`FrameTime`].
127///
128/// # Panics
129///
130/// After fixed-delta validation, when the simulation is not paused, this may
131/// panic if `control.time_scale` is positive and non-finite, or if scaling
132/// `real_delta` by the non-negative time scale cannot be represented by
133/// [`Duration::mul_f64`]. Negative and `NaN` time scales are clamped to zero
134/// and do not panic.
135pub fn advance(
136    control: &mut TimeControl,
137    time: &mut FrameTime,
138    real_delta: Duration,
139) -> Result<u32, TimeAdvanceError> {
140    if control.fixed_delta.is_zero() {
141        return Err(TimeAdvanceError::InvalidFixedDelta);
142    }
143
144    let scaled_delta = if control.paused {
145        Duration::ZERO
146    } else {
147        real_delta.mul_f64(control.time_scale.max(0.0))
148    };
149    control.accumulator = control.accumulator.saturating_add(scaled_delta);
150
151    let mut fixed_steps = 0;
152    let fixed_delta = control.fixed_delta;
153    while control.accumulator >= fixed_delta
154        && fixed_steps < control.max_fixed_steps
155        && !control.paused
156    {
157        control.accumulator -= fixed_delta;
158        fixed_steps += 1;
159    }
160    if !control.paused && control.max_fixed_steps > 0 {
161        // Keep at most one more capped update of backlog, so one long stall
162        // does not make many later frames run the maximum number of steps.
163        control.accumulator = control
164            .accumulator
165            .min(fixed_delta.saturating_mul(control.max_fixed_steps));
166    }
167    let stepped_while_paused = control.paused && control.pending_steps > 0;
168    if stepped_while_paused {
169        control.pending_steps -= 1;
170        fixed_steps = 1;
171    }
172    let elapsed_delta = if stepped_while_paused {
173        fixed_delta
174    } else {
175        scaled_delta
176    };
177
178    time.frame = time.frame.saturating_add(1);
179    time.real_delta = real_delta;
180    time.delta = scaled_delta;
181    time.elapsed = time.elapsed.saturating_add(elapsed_delta);
182    time.fixed_delta = fixed_delta;
183    time.fixed_tick = time.fixed_tick.saturating_add(u64::from(fixed_steps));
184    Ok(fixed_steps)
185}
186
187#[cfg(test)]
188mod tests {
189    use std::time::Duration;
190
191    use bevy_ecs::prelude::Resource;
192
193    use super::{advance, FrameTime, TimeAdvanceError, TimeControl};
194
195    #[test]
196    fn default_starts_at_frame_zero_with_sixty_hz_fixed_delta() {
197        let time = FrameTime::default();
198
199        assert_eq!(time.frame, 0);
200        assert_eq!(time.real_delta, Duration::ZERO);
201        assert_eq!(time.delta, Duration::ZERO);
202        assert_eq!(time.elapsed, Duration::ZERO);
203        assert_eq!(time.fixed_delta, Duration::from_secs_f64(1.0 / 60.0));
204        assert_eq!(time.fixed_tick, 0);
205    }
206
207    #[test]
208    fn duration_accessors_return_seconds() {
209        let time = FrameTime {
210            delta: Duration::from_millis(125),
211            elapsed: Duration::from_millis(2_500),
212            ..FrameTime::default()
213        };
214
215        assert_eq!(time.delta_seconds(), 0.125);
216        assert_eq!(time.elapsed_seconds(), 2.5);
217    }
218
219    #[test]
220    fn frame_time_is_an_ecs_resource() {
221        fn assert_resource<T: Resource>() {}
222
223        assert_resource::<FrameTime>();
224    }
225
226    #[test]
227    fn frame_time_is_clone_and_copy() {
228        fn assert_clone_copy<T: Clone + Copy>() {}
229
230        assert_clone_copy::<FrameTime>();
231    }
232
233    #[test]
234    fn time_control_defaults_and_public_traits_are_stable() {
235        fn assert_resource_clone_debug<
236            T: Resource + Clone + std::fmt::Debug,
237        >() {
238        }
239        fn assert_error_traits<T: std::error::Error + Clone + Copy + Eq>() {}
240
241        assert_resource_clone_debug::<TimeControl>();
242        assert_error_traits::<TimeAdvanceError>();
243
244        let control = TimeControl::default();
245        assert!(!control.paused);
246        assert_eq!(control.time_scale, 1.0);
247        assert_eq!(control.fixed_delta, Duration::from_secs_f64(1.0 / 60.0));
248        assert_eq!(control.max_fixed_steps, 8);
249        assert_eq!(control.accumulator, Duration::ZERO);
250        assert_eq!(control.pending_steps, 0);
251        assert_eq!(
252            TimeAdvanceError::InvalidFixedDelta.to_string(),
253            "fixed delta must be greater than zero"
254        );
255    }
256
257    #[test]
258    fn normal_scaled_advance_updates_all_bookkeeping() {
259        let mut control = TimeControl {
260            time_scale: 0.5,
261            fixed_delta: Duration::from_millis(10),
262            ..TimeControl::default()
263        };
264        let mut time = FrameTime::default();
265
266        assert_eq!(
267            advance(&mut control, &mut time, Duration::from_millis(25)),
268            Ok(1)
269        );
270        assert_eq!(control.accumulator, Duration::from_micros(2_500));
271        assert_eq!(time.frame, 1);
272        assert_eq!(time.real_delta, Duration::from_millis(25));
273        assert_eq!(time.delta, Duration::from_micros(12_500));
274        assert_eq!(time.elapsed, Duration::from_micros(12_500));
275        assert_eq!(time.fixed_delta, Duration::from_millis(10));
276        assert_eq!(time.fixed_tick, 1);
277    }
278
279    #[test]
280    fn catch_up_cap_retains_backlog_for_later_frames() {
281        let mut control = TimeControl {
282            fixed_delta: Duration::from_millis(10),
283            max_fixed_steps: 2,
284            ..TimeControl::default()
285        };
286        let mut time = FrameTime::default();
287
288        assert_eq!(
289            advance(&mut control, &mut time, Duration::from_millis(35)),
290            Ok(2)
291        );
292        assert_eq!(control.accumulator, Duration::from_millis(15));
293        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
294        assert_eq!(control.accumulator, Duration::from_millis(5));
295        assert_eq!(time.fixed_tick, 3);
296        assert_eq!(time.elapsed, Duration::from_millis(35));
297    }
298
299    #[test]
300    fn pause_drains_one_queued_step_per_update_and_resume_restores_time() {
301        let mut control = TimeControl {
302            fixed_delta: Duration::from_millis(10),
303            ..TimeControl::default()
304        };
305        let mut time = FrameTime::default();
306        control.pause();
307        control.step();
308        control.step();
309
310        assert_eq!(
311            advance(&mut control, &mut time, Duration::from_secs(1)),
312            Ok(1)
313        );
314        assert_eq!(time.delta, Duration::ZERO);
315        assert_eq!(time.elapsed, Duration::from_millis(10));
316        assert_eq!(control.pending_steps, 1);
317        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
318        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(0));
319
320        control.resume();
321        assert_eq!(
322            advance(&mut control, &mut time, Duration::from_millis(10)),
323            Ok(1)
324        );
325        assert_eq!(time.elapsed, Duration::from_millis(30));
326        assert_eq!(time.fixed_tick, 3);
327    }
328
329    #[test]
330    fn steps_queued_while_running_persist_until_paused() {
331        let mut control = TimeControl {
332            fixed_delta: Duration::from_millis(10),
333            ..TimeControl::default()
334        };
335        let mut time = FrameTime::default();
336        control.step();
337
338        assert_eq!(
339            advance(&mut control, &mut time, Duration::from_millis(10)),
340            Ok(1)
341        );
342        assert_eq!(control.pending_steps, 1);
343        control.pause();
344        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(1));
345        assert_eq!(control.pending_steps, 0);
346    }
347
348    #[test]
349    fn negative_and_nan_time_scales_clamp_to_zero() {
350        for scale in [-1.0, f64::NAN] {
351            let mut control = TimeControl {
352                time_scale: scale,
353                fixed_delta: Duration::from_millis(10),
354                ..TimeControl::default()
355            };
356            let mut time = FrameTime::default();
357
358            assert_eq!(
359                advance(&mut control, &mut time, Duration::from_secs(1)),
360                Ok(0)
361            );
362            assert_eq!(control.accumulator, Duration::ZERO);
363            assert_eq!(time.delta, Duration::ZERO);
364            assert_eq!(time.elapsed, Duration::ZERO);
365        }
366    }
367
368    #[test]
369    #[should_panic]
370    fn positive_infinite_time_scale_panics_while_running() {
371        let mut control = TimeControl {
372            time_scale: f64::INFINITY,
373            ..TimeControl::default()
374        };
375        let mut time = FrameTime::default();
376
377        let _ = advance(&mut control, &mut time, Duration::from_secs(1));
378    }
379
380    #[test]
381    fn long_stall_backlog_is_bounded_to_one_capped_update() {
382        let mut control = TimeControl {
383            fixed_delta: Duration::from_millis(10),
384            max_fixed_steps: 2,
385            ..TimeControl::default()
386        };
387        let mut time = FrameTime::default();
388
389        assert_eq!(
390            advance(&mut control, &mut time, Duration::from_secs(5)),
391            Ok(2)
392        );
393        assert_eq!(control.accumulator, Duration::from_millis(20));
394        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(2));
395        assert_eq!(advance(&mut control, &mut time, Duration::ZERO), Ok(0));
396    }
397
398    #[test]
399    fn zero_max_fixed_steps_retains_the_entire_backlog() {
400        let mut control = TimeControl {
401            fixed_delta: Duration::from_millis(10),
402            max_fixed_steps: 0,
403            ..TimeControl::default()
404        };
405        let mut time = FrameTime::default();
406
407        assert_eq!(
408            advance(&mut control, &mut time, Duration::from_millis(25)),
409            Ok(0)
410        );
411        assert_eq!(control.accumulator, Duration::from_millis(25));
412        assert_eq!(time.elapsed, Duration::from_millis(25));
413        assert_eq!(time.fixed_tick, 0);
414    }
415
416    #[test]
417    fn zero_fixed_delta_errors_before_mutating_either_resource() {
418        let mut control = TimeControl {
419            paused: true,
420            time_scale: 2.0,
421            fixed_delta: Duration::ZERO,
422            max_fixed_steps: 3,
423            accumulator: Duration::from_millis(7),
424            pending_steps: 2,
425        };
426        let mut time = FrameTime {
427            frame: 4,
428            real_delta: Duration::from_millis(1),
429            delta: Duration::from_millis(2),
430            elapsed: Duration::from_millis(3),
431            fixed_delta: Duration::from_millis(4),
432            fixed_tick: 5,
433        };
434
435        assert_eq!(
436            advance(&mut control, &mut time, Duration::from_secs(1)),
437            Err(TimeAdvanceError::InvalidFixedDelta)
438        );
439        assert!(control.paused);
440        assert_eq!(control.time_scale, 2.0);
441        assert_eq!(control.fixed_delta, Duration::ZERO);
442        assert_eq!(control.max_fixed_steps, 3);
443        assert_eq!(control.accumulator, Duration::from_millis(7));
444        assert_eq!(control.pending_steps, 2);
445        assert_eq!(time.frame, 4);
446        assert_eq!(time.real_delta, Duration::from_millis(1));
447        assert_eq!(time.delta, Duration::from_millis(2));
448        assert_eq!(time.elapsed, Duration::from_millis(3));
449        assert_eq!(time.fixed_delta, Duration::from_millis(4));
450        assert_eq!(time.fixed_tick, 5);
451    }
452
453    #[test]
454    fn paused_updates_and_steps_preserve_accumulated_partial_time() {
455        let mut control = TimeControl {
456            fixed_delta: Duration::from_millis(10),
457            ..TimeControl::default()
458        };
459        let mut time = FrameTime::default();
460        advance(&mut control, &mut time, Duration::from_millis(6)).unwrap();
461        control.pause();
462        advance(&mut control, &mut time, Duration::from_secs(1)).unwrap();
463        control.step();
464        advance(&mut control, &mut time, Duration::ZERO).unwrap();
465        assert_eq!(control.accumulator, Duration::from_millis(6));
466
467        control.resume();
468        assert_eq!(
469            advance(&mut control, &mut time, Duration::from_millis(4)),
470            Ok(1)
471        );
472        assert_eq!(control.accumulator, Duration::ZERO);
473    }
474
475    #[test]
476    fn counters_durations_and_step_queue_saturate() {
477        let mut control = TimeControl {
478            paused: true,
479            fixed_delta: Duration::from_nanos(1),
480            accumulator: Duration::MAX,
481            pending_steps: u32::MAX,
482            ..TimeControl::default()
483        };
484        control.step();
485        assert_eq!(control.pending_steps, u32::MAX);
486
487        let mut time = FrameTime {
488            frame: u64::MAX,
489            elapsed: Duration::MAX,
490            fixed_tick: u64::MAX,
491            ..FrameTime::default()
492        };
493        assert_eq!(advance(&mut control, &mut time, Duration::MAX), Ok(1));
494        assert_eq!(control.accumulator, Duration::MAX);
495        assert_eq!(control.pending_steps, u32::MAX - 1);
496        assert_eq!(time.frame, u64::MAX);
497        assert_eq!(time.elapsed, Duration::MAX);
498        assert_eq!(time.fixed_tick, u64::MAX);
499    }
500}